Scaling, Hardware, Quotas and Caching
Adding workers is easy. Finding the limit they will hit, and sharing it fairly, is the real work.
An agent system is usually limited by model quotas, downstream tools or databases long before CPU. Measure demand in tasks, requests and tokens, put admission control in front of scarce resources, give each tenant its own share, scale on waiting work up to a safe maximum and cache only what stays correct and private.
What you will learn: how to find the binding limit, work with provider rate limits, protect tenants from each other, autoscale without causing damage, decide when accelerators matter and cache safely.
Prerequisites: Deploying Agents to Production and Serverless, Streaming APIs, Queues and State.
The example runs in November 2026 with Python 3.13 and only the standard library. Its tenants, limits and traffic are invented. Provider behavior described with a link was read in November 2026; limits differ by provider, model and account tier.
Find the binding limit
A system moves only as fast as its tightest constraint. For each part of a task, write down what limits it:
| Resource | Typical limit | Sign you have reached it |
|---|---|---|
| Model provider | Requests and tokens per minute, concurrent requests | Rejected calls asking you to retry later |
| Self-hosted model | Accelerator memory and generation speed | Growing wait before the first token |
| Tools and internal services | Their own rate limits and capacity | Timeouts and errors from one dependency |
| Database and vector store | Connections, query load, index memory | Pool exhaustion and slow retrieval |
| Workers | Memory, CPU, concurrent tasks | Queue grows while other parts are idle |
| People | Approval and review capacity | Tasks wait hours for a decision |
| Money | Budget per day or month | Spend alarms before technical ones |
The last two surprise teams. If one reviewer can check 40 actions an hour and the agent proposes 400, more workers only lengthen the approval queue.
Measure demand in the right units
One agent task is several model calls, and each call carries input and output tokens. So "tasks per minute" must be converted before you compare it with a quota:
requests per minute = tasks per minute × model calls per task
input tokens per minute = tasks per minute × input tokens per task
output tokens per minute = tasks per minute × output tokens per task
Use a high percentile as well as the average, because long tasks consume far more than typical ones. Latency, Load Testing and Capacity Planning works through a full capacity estimate.
Working with provider rate limits
Providers limit how fast an account may call them. Anthropic's rate limit documentation, for example, measures requests, input tokens and output tokens per minute, returns status 429 with a retry-after value when a limit is exceeded, and notes that limits may be applied over intervals shorter than a minute. For most of its models, cached input tokens do not count toward the input limit. Other providers use their own units and rules, so read each one.
Good manners at the limit:
- Wait at least as long as the provider asks, then add a small random delay.
- Retry a limited number of times; after that, requeue the task.
- Smooth bursts. A minute's allowance spent in two seconds may still be rejected.
- Send all calls through one gateway so that one place knows the remaining budget.
- Ask for higher limits well before a launch; approval takes time.
- Test fallbacks. A second model needs its own quota and its own evaluation (Model Routing, Fallbacks and Gateways).
Admission control and token buckets
Admission control decides whether to accept work now, delay it or refuse it. Refusing early with a clear message is kinder than accepting everything and timing out.
A token bucket is the usual tool. A bucket holds up to a set number of units and refills at a steady rate. Work takes units; when there are not enough, it waits or is refused. The capacity controls burst size and the refill rate controls the sustained pace. For model calls, keep separate buckets for requests and tokens, reserve an estimate before the call and correct it with actual usage afterward.
Why one shared limit is unfair
In this simulation a busy tenant sends ten times as much traffic as a small one. Compare a single shared limit with an added limit for each tenant. In each second the busy tenant's requests arrive first.
"""Token buckets with per-tenant limits protect one tenant from another."""
class Bucket:
def __init__(self, capacity, per_second):
self.capacity, self.rate = capacity, per_second
self.level, self.at = capacity, 0.0
def refill(self, now):
self.level = min(self.capacity, self.level + (now - self.at) * self.rate)
self.at = now
def admit(buckets, cost, now):
"""Take from every bucket, or from none."""
for b in buckets:
b.refill(now)
if any(b.level < cost for b in buckets):
return False
for b in buckets:
b.level -= cost
return True
def simulate(per_tenant):
shared = Bucket(capacity=100, per_second=10)
tenants = {"busy": Bucket(60, 6), "small": Bucket(60, 6)}
accepted = {"busy": 0, "small": 0}
offered = {"busy": 0, "small": 0}
for second in range(60):
# the busy tenant sends 20 requests a second, the small one sends 2
for name, count in (("busy", 20), ("small", 2)):
for _ in range(count):
offered[name] += 1
limits = [shared] + ([tenants[name]] if per_tenant else [])
accepted[name] += admit(limits, 1, second)
return accepted, offered
if __name__ == "__main__":
for per_tenant in (False, True):
accepted, offered = simulate(per_tenant)
print("shared limit plus per-tenant limits" if per_tenant else "shared limit only")
for name in accepted:
print(f" {name:<5} {accepted[name]:>3} of {offered[name]:>4} accepted "
f"({accepted[name] / offered[name]:.0%})")
Output:
shared limit only
busy 676 of 1200 accepted (56%)
small 14 of 120 accepted (12%)
shared limit plus per-tenant limits
busy 414 of 1200 accepted (34%)
small 120 of 120 accepted (100%)
With only a shared limit, the small tenant gets about one request in eight through, although its demand is far below the total allowance. With a limit per tenant, it gets everything it asks for.
Note the price: total accepted requests fall, because each tenant is capped even when others are quiet. Many systems add borrowing: each tenant has a guaranteed share and may use spare capacity above it, which is withdrawn as soon as others need it. Decide that policy deliberately and write it down for customers.
Fairness beyond request counts
| Control | What it prevents |
|---|---|
| Concurrent tasks per tenant | One customer occupying every worker with long runs |
| Token budget per tenant | A few huge documents consuming the shared quota |
| Separate queues or weighted turns | A large backlog delaying everyone behind it |
| Priority classes | Batch jobs competing with people waiting |
| Steps, time and spend limit per task | One looping run behaving like a heavy customer |
| Reserved capacity | Contracted service levels being starved |
Apply limits at more than one level: per user, per tenant, per agent and globally. Return a distinct error for each so that support staff can tell which limit was hit. Strict priority can starve low-priority work forever, so give every class a small guaranteed share.
Degrade on purpose
When demand exceeds capacity, choose what gets worse:
- Delay batch and background work.
- Turn off optional steps, such as extra drafts or self-review of low-risk answers.
- Route suitable tasks to a faster, tested model.
- Shorten limits on new low-priority tasks.
- Refuse new work with a clear message and a time to retry.
Approval steps, permission checks, output filtering and audit logging must not be on the list of things to switch off under load. If they cannot keep up, accept less work.
Autoscaling workers and model calls
Autoscaling adds or removes workers from a signal. For agents, choose signals about waiting work:
| Signal | Quality | Comment |
|---|---|---|
| Age of oldest waiting task | Good | Tracks what users feel |
| Waiting tasks per worker | Good | Simple, but ignores task length |
| Tasks in progress per worker | Useful | Shows how full the pool is |
| CPU use | Weak for waiting workloads | Useful for parsing or local computation |
| Provider rejections | A reason to stop scaling | More workers make it worse |
The loop needs guard rails: a minimum that covers normal start-up delay, a maximum derived from the tightest downstream limit, quick scale-up, slow scale-down and a pause between changes to avoid swinging. Workers must stop safely when removed (Docker and Kubernetes for Agents).
Model calls also need scaling control, separate from workers. A shared concurrency limit at the gateway can lower itself when rejections appear and raise itself slowly while calls succeed, much as network protocols probe for capacity.
CPU or GPU
If you call a hosted model, your own services are mostly waiting and ordinary CPU machines are enough. Accelerators matter when you run models yourself.
| Workload | Usual starting point |
|---|---|
| Agent loop, APIs, tool calls | CPU |
| Document parsing and chunking | CPU; accelerators for heavy layout or image models |
| Embeddings and reranking | CPU at low volume; accelerator at high volume or tight latency |
| Serving a language model | Accelerator, sized by memory first |
| Speech recognition and synthesis | Depends on model and real-time needs; measure |
An accelerator is paid for whether busy or idle. Self-hosting makes economic sense when steady demand keeps it well used, or when privacy, location or control require it. Count engineering time, spare capacity for failures and slow start-up in the comparison. NVIDIA, vLLM and GPU Sizing and Inference Optimization and Quantization go deeper.
Caching layers
A cache avoids repeating work. Each layer saves something different and fails differently:
| Layer | Saves | Main risk |
|---|---|---|
| Provider prompt cache | Repeated processing of an identical prefix | Low hit rate if early text changes |
| Exact response cache | A whole model call for identical input | Stale answers after data changes |
| Semantic cache | A call for a similar question | Similar wording with a different correct answer |
| Embedding cache | Recomputing vectors for unchanged text | Mixing vectors from different models |
| Retrieval cache | Repeated searches | Serving documents after access was removed |
| Tool result cache | Repeated reads of slow services | Acting on old state |
Rules for safe caching
- Put everything that affects the answer in the key: tenant, permissions, model, prompt version, tool versions, data version and settings.
- Check access when serving, not only when storing.
- Give every entry an expiry, and remove entries when the source changes.
- Never cache the result of an action as a substitute for performing or checking it.
- Be able to delete a person's cached data when required.
- Measure hit rate, saved cost and wrong hits, and turn off layers that do not pay.
"Can I cancel my order?" and "Can I cancel my subscription?" look alike and have different answers. Test with near-miss pairs, scope entries narrowly and do not use similarity caching where a wrong answer is costly.
Cache stampedes
When a popular entry expires, many requests may recompute it at once. Let one request refresh it while others wait briefly or use the slightly old value if that is acceptable, and spread expiry times so entries do not all lapse together.
Planning for a launch or a surge
Predictable peaks are the easiest to survive if you prepare early. Estimate arrivals for the busiest hour, convert them into requests and tokens and compare each with the limit that applies. Add the work that surges create indirectly: retries, new users who explore with long tasks and a cold cache that has not yet seen their questions.
| Weeks before | Action |
|---|---|
| Several | Request provider quota, database capacity and tool allowances |
| Two or more | Load test at the expected peak and at double that figure |
| One | Rehearse the overload plan and confirm who can activate it |
| Day before | Raise minimum workers, warm safe caches and pause risky releases |
| Day after | Lower minimums, compare forecast with actual and record lessons |
Offer a waiting list or staged access if capacity cannot be confirmed. A smaller group served well tells you more than a large group seeing errors.
Prove the limits with tests
- Replay realistic traffic, including long tasks and several tenants.
- Raise load until something breaks and record which part broke first.
- Check that limits return clear errors and that queues recover after the peak.
- Make one tenant flood the system and verify others stay within targets.
- Simulate reduced provider quota and a cold cache.
- Repeat after changing a model, prompt or tool, because token use changes.
Use test accounts and simulated tools so that load tests do not send messages or change real records, and tell your providers if their terms require it.
Common mistakes
| Mistake | Better approach |
|---|---|
| Adding workers when the quota is the limit | Cap the pool and request more quota |
| Immediate retries after rejection | Honor the wait time and add jitter |
| One global limit for all customers | Add shares per tenant and per task |
| Cache keys without tenant or permissions | Include every input that changes the answer |
| Buying accelerators before measuring demand | Compare cost at realistic utilization |
| Disabling checks during peaks | Reduce intake instead |
Checklist
- The binding limit is known for each major task type.
- Demand is expressed in requests and tokens as well as tasks.
- One gateway enforces provider quotas and retry rules.
- Each tenant has limits on rate, concurrency and spend.
- Autoscaling has minimum, maximum and slow scale-down.
- An overload plan lists what degrades and what never does.
- Cache keys include identity, versions and data freshness.
- A noisy-neighbor test has passed.
Frequently asked questions
Why are we rate limited when average use is low?
Bursts, token limits or shorter enforcement windows can trigger rejections even when the minute average looks safe.
Should every tenant get the same limit?
Not necessarily; set limits by contract and need, keep a guaranteed minimum and publish the policy.
Does caching reduce quality?
Exact caches need only freshness control, while similarity caches can return wrong answers and must be tested carefully.
When is self-hosting cheaper?
Only when your measured, steady demand keeps hardware busy enough to cover operating effort and spare capacity.
References and further reading
- Claude API rate limits: units, headers and retry behavior for one provider.
- OpenAI: prompt caching: how one provider caches repeated prefixes.
- KEDA concepts: scaling workers from queue length.
- Google SRE book: handling overload: quotas, shedding and degraded responses.
Next steps
Latency, Load Testing and Capacity Planning
Turn demand into workers and quota.
Reducing Tokens, Tool Calls and Spend
Use fewer tokens for the same result.
High Availability and Disaster Recovery
Keep working when a whole part fails.