Rate Limit ограничивает скорость потребления ресурса. Quota ограничивает объём доступного ресурса в окне или по entitlement. Budget ограничивает допустимую стоимость, токены, compute, tool calls или иной измеримый расход для task, user, tenant, workflow или системы.
№16 Test-Time Compute решает, сколько дополнительного cognitive compute стоит потратить на конкретную задачу для качества; №64 задаёт инфраструктурные/экономические ceilings и entitlement, которые нельзя превышать. №57 Queues буферизует принятую работу и регулирует worker concurrency; №64 решает admission/rate/quota before or around enqueue/execution. №63 Retry восстанавливает transient failures; все retry attempts расходуют rate/cost budgets. №48 Policies отвечает «разрешено ли действие по правилам»; №64 — «есть ли capacity/entitlement/budget». №65 Model Gateway применяет provider/model quotas на model boundary и использует №64 counters/decisions. №70 Serving владеет inference capacity/batching; №64 ограничивает demand.
Prerequisites: №16 Test-Time Compute, №46 Observability, №48 Guardrails, №50 Contracts, №57 Queues, №63 Retry. Forward references: №65 Model Gateway, №68 Durable Workflow, №69 Distributed Reliability, №70 Model Serving, №76 Governance.
REQUEST-TIME: YES — admission/consume/reserve before expensive work. CONTROL PLANE: limit definitions, windows, hierarchy, plans/entitlements, hard/soft thresholds. DATA PLANE: counters, reservations, usage events, decisions. OFFLINE: reconciliation, billing-like aggregation, capacity planning, abuse/load tests.
Success: every controlled operation obtains an explicit admission decision and usage is accounted to correct scopes. Retryable: transient limiter-store failure only where fail behavior permits. Permanent: hard quota/budget exhausted until reset/change. Idempotency: usage commit/reservation requires operation_id to avoid double charging. Persist: policy/version, scope, dimensions, reserved/committed amount, decision, reset/expiry. Trace: check→reserve→execute→commit/release. Security: caller cannot choose a cheaper tenant/scope or raise own limits.
№64 не владеет cognitive search strategy, product billing invoices, authentication, queue execution, provider routing or model serving. Она владеет RESOURCE ADMISSION, FAIR-SHARE LIMITING, QUOTA ENTITLEMENT AND OPERATIONAL/ECONOMIC BUDGET ENFORCEMENT.
100 requests/min, 20 tool calls/sec, 60k tokens/min.
10k requests/day, 50 GB storage, 1M documents/month.
$5/task, 100k tokens/run, 40 model calls/research, 3 min GPU time.
4 active browser sessions, 8 GPU jobs, 20 concurrent model calls.
Protect API/service from bursts.
Closer to actual model capacity/cost than request count alone.
Emails, publishes, browser actions, DB writes can have separate limits.
| Algorithm | Strength | Weakness |
|---|---|---|
| FIXED WINDOW | Очень простой counter per minute/hour. | Boundary burst: 100 at 12:00:59 + 100 at 12:01:00. |
| SLIDING WINDOW | Более ровный limit over real interval. | More state/compute. |
| TOKEN BUCKET | Allows controlled bursts + sustained rate. | Needs refill/atomic consume semantics. |
| LEAKY BUCKET | Smooths outgoing flow at steady rate. | May increase queue latency. |
| CONCURRENCY SEMAPHORE | Controls simultaneous in-flight work. | Doesn't limit total volume over time. |
Provider/API call count.
Prompt + completion token throughput.
Local inference accelerator capacity.
Computer-use/browser fleet pressure.
Search/provider API entitlement.
Publishing/email/database mutation rate.
Uploads/downloads/storage transfer.
Enqueues/processing rate by class.
1M model tokens/day, 10k searches/month, 500 document imports/day.
50 GB artifacts, 100k indexed documents, 20 active schedules.
2 concurrent deep-research runs, 3 connected sources, 10 worker seats.
| Window | Example | Important detail |
|---|---|---|
| CALENDAR DAY | 100k searches/day. | Which timezone defines day? |
| ROLLING 24H | 100k over previous 24 hours. | Different semantics from calendar day. |
| CALENDAR MONTH | 10M tokens/month. | Month boundaries and tenant billing timezone. |
| LIFETIME / PROJECT | 500 GPU hours for experiment. | No automatic reset. |
| CAPACITY | 100 GB currently stored. | Usage decreases after deletion. |
remaining and reset_at when meaningful, so caller can defer instead of blind retry.Max 30 model calls, 120k tokens, $2 equivalent cost, 5 browser minutes.
All retries/subagents/tools share one parent budget.
Per-day/month usage ceiling or plan allowance.
Protects shared billing/capacity across users.
Cap spend/rate to one external model/search/provider.
Hard daily/monthly ceiling against runaway automation.
Controller decides whether another candidate, critic, search branch or stronger model is likely to improve answer enough.
Infrastructure says: task has 100k tokens / 20 calls / $X ceiling. Cognitive controller may stop earlier, but cannot exceed ceiling.
At 70–80%: reduce optional enrichment, use cheaper model, stop extra candidates, alert.
At 100%: reject new costly operation, except explicit reserved completion semantics.
Rare, audited, explicit authority; not model self-override.
{
"operation_id": "OP-...",
"subject": {
"user_id": "...",
"tenant_id": "tenant_A"
},
"resource": "MODEL_TOKENS",
"dimensions": {
"provider": "provider_A",
"model": "model_X"
},
"estimated": 12000,
"reserved": 15000,
"actual": 10842,
"budget_refs": [
"budget://task/...",
"budget://tenant/..."
],
"rate_scope": "tenant_A:model_X",
"status": "COMMITTED",
"timestamp": "..."
}Operation identity позволяет:
Attempt_id может быть отдельным от logical operation_id.
One user cannot consume entire tenant pool.
Large organization cannot starve other tenants beyond allocated capacity.
Background indexing does not consume all interactive capacity.
Priority classes get reserved shares/limits, not unlimited bypass.
| Resource | Concurrency example | Why |
|---|---|---|
| MODEL PROVIDER | 20 in-flight requests | Protect provider/socket/latency and quota. |
| LOCAL GPU | 1–4 generations | VRAM and batching capacity are finite. |
| BROWSER AGENTS | 5 active sessions | CPU/RAM/browser fleet and site pressure. |
| OCR | 2 GPU jobs | Prevent document ingestion from starving inference. |
| EXTERNAL WRITE TOOL | Small bounded concurrency | Reduce blast radius and provider abuse. |
User requested one research step.
Provider timeout → retry → retry. Rate, tokens and cost consumed each time.
Operation result = one logical outcome, but usage includes every real attempt.
Architectural «умность» превращается в runaway spend/capacity.
Subagent receives bounded calls/tokens/time/cost that fit parent remaining budget.
Unused child reservation returns to parent for later steps.
Provider request/minute entitlement.
Prompt/completion throughput entitlement.
Protect provider and own latency.
Optional operational cap under organization billing limit.
Max simultaneous generations/batches per device/profile.
Per task/tenant/day if capacity is shared.
Model/context request may be rejected/routed if predicted memory exceeds safe profile.
If local capacity delay exceeds SLA, route/fail/defer according to №65 policy.
Tool call fixed unit, file size, embedding input token count.
Input tokens known + max output tokens gives conservative model reservation.
Reserve per step and re-check parent remaining budget before each expansion.
{
"decision": "ALLOW|DEFER|DENY|DEGRADE",
"reason_code": "RATE_EXCEEDED",
"scope": "tenant_A:model_X",
"resource": "MODEL_TOKENS",
"requested": 12000,
"remaining": 8300,
"reserved": 0,
"limit": 100000,
"reset_at": "...",
"retry_after_ms": 4200,
"budget_ref": "budget://tenant/...",
"policy_version": "limits-v7",
"obligations": [
"USE_CHEAPER_MODEL",
"MAX_OUTPUT_2000"
]
}Caller может:
| Control | Typical default | Reason |
|---|---|---|
| SECURITY / ABUSE LIMIT | FAIL CLOSED or conservative local emergency limit | Unlimited access may be unsafe. |
| HARD SPEND BUDGET | FAIL CLOSED | Cannot prove spend is allowed. |
| LOW-RISK PERFORMANCE RATE LIMIT | CONTEXTUAL | Short fail-open may preserve availability if downstream has own protection. |
| LOCAL CONCURRENCY | LOCAL STATE CONTINUES | Process can often enforce semaphore without central service. |
Needed for hard budget/spend/reservation where overshoot is unacceptable.
Each worker gets small token allowance; lower coordination overhead but bounded overshoot.
Good for soft alerts/capacity analytics, not a hard spend gate.
One request uses enormous context/output limits.
Agent repeatedly calls search/browser/tool.
User input triggers many subagents/candidates.
Outage turns one request into many provider calls.
Allowed operations by resource/scope.
Rate/quota/budget/concurrency rejection reasons.
Used / available by tenant/provider/resource window.
Remaining capacity before saturation.
Outstanding reserved vs committed usage.
Usage above hard target due to races/accounting gaps.
Usage by user/tenant/workflow/model/tool.
Fraction of resource usage caused by retries.
Exactly at limit allowed; next unit gets expected decision.
Burst capacity and refill behave as configured.
100 concurrent requests cannot oversubscribe hard budget.
Retries consume real resources without double-charging logical bookkeeping.
Caller cannot forge scope or consume another tenant's entitlement.
Calendar/rolling reset semantics are correct around boundaries.
Fail-open/closed behavior matches policy class.
Approaching cap suppresses optional work before hard failure.
Usage / limit by scope, window and resource dimension.
Requests deferred/denied because velocity exceeded.
Tenants/users hitting period/capacity entitlement ceilings.
Tasks/workflows stopped/degraded by spend ceiling.
Actual usage beyond hard ceiling. Target: zero/bounded by contract.
% tokens/calls/cost consumed by retries.
Capacity distribution across tenants/users/work classes.
Remaining RPM/TPM/concurrency before saturation.
limits/ ├── policy.py ├── rate.py ├── quota.py ├── budget.py ├── reservation.py ├── concurrency.py ├── usage.py └── tests/ limit_policies( policy_id, scope_type, resource, window_type, limit_value, hard, version ) usage_counters( scope_key, resource, window_start, used, updated_at, primary key(...) ) budget_reservations( operation_id primary key, budget_ref, reserved, committed, status, expires_at ) admit(ctx, estimated): derive trusted scopes check policy permission check rate check quota check budget check concurrency reserve if needed return structured decision
Redis/distributed token buckets can come later if multi-instance QPS makes PostgreSQL/local allocation insufficient.
| Signal | Potential upgrade |
|---|---|
| High-QPS multi-instance API | Dedicated distributed limiter / Redis-like atomic token buckets. |
| Strict spend caps under heavy concurrency | Strong reservation ledger / transactional budget service. |
| Many providers/models | Centralized enforcement in №65 Model Gateway. |
| Complex workflow/subagent budgets | Hierarchical budget propagation integrated with №68 workflow state. |
| Multi-region active-active | Regional allocations + global reconciliation; see №69. |
| Large local inference cluster | Capacity/admission integration with №70 serving scheduler. |
| Вопрос | Ответ |
|---|---|
| Стоит ли реализовывать? | Да. Минимальные rate/concurrency/task-budget/global-cap controls нужны production AI по умолчанию. |
| Separate Component? | YES логически. На старте это может быть common middleware/library + PostgreSQL counters + local semaphores. |
| Минимум 80% ценности? | Rate + concurrency + task ceilings + tenant/global budget + provider limits + reservation + retry accounting + metrics. |
| Когда overkill? | Globally distributed millisecond-precise quota service для одного локального сервера и нескольких пользователей. |
| Trigger? | Minimum always ON; advanced hierarchy/distribution when shared capacity, cost exposure, multi-tenancy or scale appear. |
| Как измерить uplift? | Prevented overload/spend incidents, fairness, provider 429 reduction, budget overshoot, queue stability, retry amplification, cost predictability. |
| Можно ли rule/tool/code вместо LLM-agent? | Да, полностью. Enforcement must be deterministic. LLM may estimate complexity, but cannot grant itself more quota or override hard budget. |
Проверять capacity/budget до дорогой операции.
Velocity, entitlement and spend ceiling solve different problems.
Requests alone do not represent AI cost/capacity.
Task/user/tenant/provider/global limits are checked together.
Parallel operations must not oversubscribe hard budget.
Every actual attempt consumes capacity and spend.
Soft thresholds can disable optional compute safely.
Scope and plan derive from trusted identity/control plane.
Alerting after overspend is observability, not a budget control.
REQUEST / JOB / SUBAGENT / TOOL CALL
↓
TRUSTED IDENTITY + TENANT
↓
POLICY:
is the action allowed?
↓
RESOURCE ADMISSION:
↓
RATE LIMIT
how fast?
↓
QUOTA
how much entitlement remains?
↓
BUDGET
how much are we willing/allowed to spend?
↓
CONCURRENCY
can it run now?
↓
HIERARCHICAL CHECKS
task
user
tenant
provider
global
↓
ESTIMATE COST
↓
RESERVE IF NECESSARY
↓
EXECUTE
↓
MEASURE ACTUAL USAGE
↓
COMMIT
↓
RELEASE UNUSED RESERVATION
IF RATE FULL:
defer / queue / 429 + Retry-After
IF CONCURRENCY FULL:
queue / backpressure / alternate capacity
IF SOFT BUDGET NEAR:
stop optional branches
reduce candidates
cheaper compatible route
preserve required verification
IF HARD BUDGET EXHAUSTED:
no new spend
bounded partial / defer / explicit failure
RETRIES:
each real attempt counts
SUBAGENTS:
child budget comes from parent budget
PROVIDER LIMITS:
RPM
TPM
concurrency
spend/capacity
LOCAL MODELS:
GPU slots
GPU seconds
VRAM class
queue latency
CORE DISTINCTION:
№16 TEST-TIME COMPUTE:
"IS MORE THINKING WORTH IT?"
№64 RESOURCE BUDGET:
"IS MORE RESOURCE USE ALLOWED?"
CORE PRINCIPLE:
DO NOT WAIT UNTIL
THE BILL, GPU, PROVIDER
OR QUEUE IS ALREADY ON FIRE.
CONTROL DEMAND
BEFORE EXECUTION.
RATE PROTECTS VELOCITY.
QUOTA PROTECTS ENTITLEMENT.
BUDGET PROTECTS SPEND.
CONCURRENCY PROTECTS
IN-FLIGHT CAPACITY.
AND NONE OF THEM
SHOULD BE OVERRIDDEN
BY THE MODEL THAT
WANTS MORE RESOURCES.
A. Related ECC ideas. Context-as-cache, scoped memory, lifecycle hooks, selective capabilities, feature flags, deterministic enforcement, provider-neutral adapters and eval-gated learning are applied only where relevant to №64 Rate Limits / Quotas / Budgets.
B–E. Existing boundary and placement. The existing conceptual boundary, class PRODUCTION, default ON and owner Production Fabric remain authoritative. Runtime/control/data/offline placement is unchanged; durable state stays outside model context.
F–H. Hooks and contracts. Use bounded PRE_MODEL/POST_MODEL, PRE_TOOL/POST_TOOL, CHECKPOINT and TASK_COMPLETED events as applicable. Illustrative fields and canonical contracts are defined in NEW_CONTRACTS_SPEC.md; no universal schema is implied.
I–J. Security and evaluation. Host-side schema, permission, secret, budget, idempotency and audit checks take precedence over LLM output. Optional mechanisms require a feature flag and WITH/WITHOUT ablation; measure quality, acceptance, correction, latency, cost, escalations and severe errors.
K–L. Task profiles and cross-references. A TaskProfile selects the relevant skill, tool/context slice, memory scope and enforcement profile independently from FAST/STANDARD/DEEP. See cross-reference map, hook spec and ablation plan. Provider adapters remain outside the core.