Scaling, Hardware, Quotas and Caching

Adding workers is easy. Finding the limit they will hit, and sharing it fairly, is the real work.

BeginnerIntermediateExpert · 12 min read · Last updated:

In short

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.

Versions used

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.

Beginner Where limits come from

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:

ResourceTypical limitSign you have reached it
Model providerRequests and tokens per minute, concurrent requestsRejected calls asking you to retry later
Self-hosted modelAccelerator memory and generation speedGrowing wait before the first token
Tools and internal servicesTheir own rate limits and capacityTimeouts and errors from one dependency
Database and vector storeConnections, query load, index memoryPool exhaustion and slow retrieval
WorkersMemory, CPU, concurrent tasksQueue grows while other parts are idle
PeopleApproval and review capacityTasks wait hours for a decision
MoneyBudget per day or monthSpend 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.

Demandusers and events
Admitlimits per tenant
Queueabsorbs bursts
Workersbounded pool
Quotashared gateway

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).
Intermediate Admission and fairness

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

ControlWhat it prevents
Concurrent tasks per tenantOne customer occupying every worker with long runs
Token budget per tenantA few huge documents consuming the shared quota
Separate queues or weighted turnsA large backlog delaying everyone behind it
Priority classesBatch jobs competing with people waiting
Steps, time and spend limit per taskOne looping run behaving like a heavy customer
Reserved capacityContracted 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:

  1. Delay batch and background work.
  2. Turn off optional steps, such as extra drafts or self-review of low-risk answers.
  3. Route suitable tasks to a faster, tested model.
  4. Shorten limits on new low-priority tasks.
  5. Refuse new work with a clear message and a time to retry.
Never degrade safety

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.

Expert Autoscaling, hardware and caching

Autoscaling workers and model calls

Autoscaling adds or removes workers from a signal. For agents, choose signals about waiting work:

SignalQualityComment
Age of oldest waiting taskGoodTracks what users feel
Waiting tasks per workerGoodSimple, but ignores task length
Tasks in progress per workerUsefulShows how full the pool is
CPU useWeak for waiting workloadsUseful for parsing or local computation
Provider rejectionsA reason to stop scalingMore 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.

WorkloadUsual starting point
Agent loop, APIs, tool callsCPU
Document parsing and chunkingCPU; accelerators for heavy layout or image models
Embeddings and rerankingCPU at low volume; accelerator at high volume or tight latency
Serving a language modelAccelerator, sized by memory first
Speech recognition and synthesisDepends 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:

LayerSavesMain risk
Provider prompt cacheRepeated processing of an identical prefixLow hit rate if early text changes
Exact response cacheA whole model call for identical inputStale answers after data changes
Semantic cacheA call for a similar questionSimilar wording with a different correct answer
Embedding cacheRecomputing vectors for unchanged textMixing vectors from different models
Retrieval cacheRepeated searchesServing documents after access was removed
Tool result cacheRepeated reads of slow servicesActing 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.
Semantic caches need proof

"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 beforeAction
SeveralRequest provider quota, database capacity and tool allowances
Two or moreLoad test at the expected peak and at double that figure
OneRehearse the overload plan and confirm who can activate it
Day beforeRaise minimum workers, warm safe caches and pause risky releases
Day afterLower 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

  1. Replay realistic traffic, including long tasks and several tenants.
  2. Raise load until something breaks and record which part broke first.
  3. Check that limits return clear errors and that queues recover after the peak.
  4. Make one tenant flood the system and verify others stay within targets.
  5. Simulate reduced provider quota and a cold cache.
  6. 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

MistakeBetter approach
Adding workers when the quota is the limitCap the pool and request more quota
Immediate retries after rejectionHonor the wait time and add jitter
One global limit for all customersAdd shares per tenant and per task
Cache keys without tenant or permissionsInclude every input that changes the answer
Buying accelerators before measuring demandCompare cost at realistic utilization
Disabling checks during peaksReduce 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

Next steps