Latency, Load Testing and Capacity Planning
Users feel waiting time, quotas count tokens and queues punish systems that run nearly full. Plan for all three.
Break latency into queueing, model, tool and human time, remove sequential steps and stream useful progress. Size capacity from arrival rate × task duration, convert load into requests and tokens per minute against quotas, leave headroom because waiting rises sharply near full load and confirm the estimate with load tests that use realistic task mixes.
What you will learn: where agent time goes, how to reduce real and perceived waiting, how to estimate workers, quota and storage, and how to benchmark and load test without fooling yourself.
Prerequisites: Task, Tool and Planning Metrics and Scaling, Hardware, Quotas and Caching.
The example runs in November 2026 with Python 3.13 and only the standard library. It is a simplified simulation with invented arrivals and durations and one random seed. Its numbers illustrate a shape, not your system.
Anatomy of a slow task
| Part | What happens | Typical levers |
|---|---|---|
| Queueing | Waiting for a worker or quota | Capacity, priority, limits |
| Context preparation | Retrieval, memory, formatting | Parallel fetches, faster index |
| Time to first token | The provider reads input and starts | Smaller or cached context, model, region |
| Generation | Output produced token by token | Shorter output, faster model |
| Tools | Calls to other services | Faster services, parallel calls, timeouts |
| Repeats | More steps and retries | Better tools and instructions |
| People | Approvals and answers | Clear requests, notifications, expiry |
Because steps run one after another, small delays add up. Eight steps with three seconds of model time and one second of tools take over half a minute before any queueing. Removing steps is usually more effective than speeding each one up.
Always report percentiles. A median of eight seconds with a 95th percentile of two minutes describes a system that regularly disappoints.
Make the work shorter
- Run independent retrievals and tool calls at the same time.
- Fetch likely-needed data before the model asks, when it is cheap and safe to do so.
- Combine tools so common sequences take one step.
- Use a faster model for steps where tests show it is good enough.
- Keep context small and cache stable prefixes.
- Set a timeout on every call, and decide what the agent does when it fires.
- Reuse network connections and place services near each other.
The longest chain of dependent steps, the critical path, sets the minimum duration. Speeding up a branch that runs in parallel with a slower one changes nothing. Traces show the path (Agent Tracing and OpenTelemetry).
Share out a latency budget
Start from the promise to the user and divide it among the parts. For an illustrative target of 30 seconds at the 95th percentile, you might allow two for queueing, three for retrieval and context, twenty for model calls across all steps and five for tools. The parts' percentiles do not add exactly, so treat the shares as guides and measure the whole.
The budget turns vague complaints into specific questions. If model time takes thirty seconds alone, no amount of faster retrieval will meet the target: you need fewer steps, shorter generations or a different design, such as running the task in the background. Loops, Performance, Incidents and Maturity covers profiling when a budget is exceeded.
Perceived latency
People tolerate waiting better when they can see progress and act on partial results.
| Technique | Effect | Care needed |
|---|---|---|
| Immediate acknowledgment | Confirms the request arrived | Do not imply success |
| Streamed text | Reading starts early | Filtering must happen before display |
| Step updates | Shows what is being done | Hide sensitive details |
| Partial results | Useful early | Mark as incomplete |
| Background mode with notification | Frees the user | Clear status and cancel |
Streaming does not shorten the total time. Track both time to first useful output and time to completion.
Little's law
In a stable system, the average number of tasks in progress equals the arrival rate multiplied by the average time each spends there:
in progress = arrival rate × average duration
30 per minute = 0.5 per second; 0.5 × 40 seconds = 20 tasks in progress
It holds for averages whatever the pattern of arrivals, provided the system is not growing without limit. It tells you how many concurrent tasks you must hold on average, not how many you need to avoid waiting.
Why full systems are slow
The program computes demand for the numbers above, then simulates four hours with random arrivals and task lengths.
"""Size workers and token quota, then simulate bursty arrivals (invented load)."""
import heapq
import random
from math import ceil
ARRIVALS_PER_MIN = 30
MEAN_SECONDS = 40
INPUT_TOKENS, OUTPUT_TOKENS = 30_000, 2_000
def littles_law():
return ARRIVALS_PER_MIN / 60 * MEAN_SECONDS # tasks in progress
def simulate(workers, minutes=240, seed=7):
rng = random.Random(seed)
clock, free, waits = 0.0, [0.0] * workers, []
while True:
clock += rng.expovariate(ARRIVALS_PER_MIN / 60)
if clock > minutes * 60:
break
ready = heapq.heappop(free)
start = max(clock, ready)
waits.append(start - clock)
heapq.heappush(free, start + rng.expovariate(1 / MEAN_SECONDS))
waits.sort()
return sum(waits) / len(waits), waits[int(0.95 * len(waits))]
if __name__ == "__main__":
busy = littles_law()
print(f"average tasks in progress: {busy:.0f}")
print(f"input tokens per minute: {ARRIVALS_PER_MIN * INPUT_TOKENS:,}")
print(f"output tokens per minute: {ARRIVALS_PER_MIN * OUTPUT_TOKENS:,}")
print()
for workers in (21, 24, 28, 34):
mean, p95 = simulate(workers)
print(f"{workers} workers (load {busy / workers:>4.0%}): "
f"mean wait {mean:5.1f}s p95 wait {p95:5.1f}s")
print(f"\nrule of thumb at 70% load: {ceil(busy / 0.7)} workers")
Output:
average tasks in progress: 20
input tokens per minute: 900,000
output tokens per minute: 60,000
21 workers (load 95%): mean wait 21.5s p95 wait 89.4s
24 workers (load 83%): mean wait 3.1s p95 wait 20.4s
28 workers (load 71%): mean wait 0.3s p95 wait 1.8s
34 workers (load 59%): mean wait 0.0s p95 wait 0.0s
rule of thumb at 70% load: 29 workers
Twenty-one workers exceed the average need of 20, yet the slowest twentieth of tasks wait around a minute and a half before starting. A few more workers change the picture dramatically. Beyond about 28, extra capacity buys little.
This curve is typical of queues: waiting climbs steeply as load approaches capacity, and variable task lengths make it worse. The 70 percent figure in the code is a planning convention, not a law. Choose headroom from your latency target, the cost of idle workers and how quickly you can add more. A different random seed gives different numbers, so run several before relying on a simulation.
Quota and rate limits
Workers are often cheap; model quota is often the real constraint. In the example, 30 tasks a minute need 900,000 input tokens and 60,000 output tokens a minute. Compare each with the limit for that model and account, including how cached tokens are counted. Anthropic's rate limit documentation, for instance, notes that for most models only uncached input counts toward the input limit, and that limits may be enforced over short intervals.
Add the traffic people forget: retries, evaluation runs, background jobs and other applications sharing the account. Separate interactive and batch quota where the provider allows it.
A sizing worksheet
| Resource | Estimate | Illustration |
|---|---|---|
| Concurrent tasks | Peak arrivals × duration | 0.5/s × 40 s = 20 |
| Worker instances | Concurrency with headroom ÷ tasks per instance | 29 ÷ 4 per instance = 8 |
| Database connections | Instances × pool size | 8 × 10 = 80 |
| Vector storage, raw | Vectors × dimensions × 4 bytes | 10 million × 1,536 × 4 ≈ 61 GB |
| Trace storage | Tasks per day × size × days kept | 100,000 × 50 KB × 30 ≈ 150 GB |
| People | Reviews per hour × minutes each | 40 × 3 min = 2 hours of work per hour |
The vector figure covers only 32-bit values; indexes, metadata and replicas add substantially, while compressed formats reduce it. Measure the instance's real concurrent capacity, since memory per task usually decides it. The last row shows two reviewers' worth of continuous work, plus cover for breaks and peaks.
Plan for peaks and failure
- Use the peak hour, and the burst within it, not the daily average.
- Allow for losing one zone or node group without breaching targets.
- Check how long new capacity takes to become useful.
- Recalculate if duration rises: a provider that becomes twice as slow doubles concurrency at the same arrival rate.
- Decide in advance what is delayed or refused beyond capacity.
The fourth point surprises teams. Nothing about demand changes, yet workers fill, queues grow and retries add load. Timeouts and admission limits contain the effect.
Load testing agents
| Test | Question |
|---|---|
| Baseline | How fast is one task with no contention? |
| Load | Are targets met at expected peak? |
| Stress | What breaks first, and how? |
| Spike | Does a sudden jump recover? |
| Soak | Does anything leak or grow over many hours? |
| Degraded | What if the provider is slow or limits are cut? |
Making the test realistic
- Mix short, typical and very long tasks in observed proportions.
- Generate arrivals at a set rate that does not slow when the system slows; a fixed pool of waiting test users hides overload.
- Use simulated tools with realistic delays and errors.
- Decide when to call the real model: stubs test your system cheaply, real calls test quotas and provider behavior at a cost.
- Vary inputs so that caches are not unrealistically warm.
- Check correctness during load, not only speed.
- Set a spend limit, warn providers if required and never touch real customers.
Benchmarking changes
When comparing two setups, hold the task set, concurrency and time of day as steady as you can, repeat runs and alternate their order. Provider latency varies, so a single morning's result may reverse by afternoon. Report success rate with speed; a faster setup that completes fewer tasks is not faster at the job. For self-hosted models, measure with your own prompt and output lengths, because published throughput figures depend heavily on them (Inference Optimization and Quantization).
Reading and reporting results
For each load level report completed tasks per minute, success rate, queue wait, completion time at several percentiles, rejected calls, resource use and spend. Plot them against load. The useful point is where waiting or errors begin to climb: record it as measured capacity, with the task mix and settings that produced it.
| Pattern in results | Suggests |
|---|---|
| Throughput flat while queue grows | A limit has been reached somewhere downstream |
| Rejections rise before CPU or memory | Quota is the constraint |
| Time climbs steadily during a long test | A leak, a growing table or accumulating history |
| Success falls as load rises | Timeouts or degraded fallbacks are affecting correctness |
| Slow recovery after a spike | Retries or backlog are sustaining the overload |
Fix one constraint, then rerun, because the next one appears immediately behind it.
An illustrative plan on one page
State the demand assumption, such as 30 tasks a minute at peak with an average of 40 seconds. List what that requires: about 20 tasks in flight, 29 task slots at the chosen headroom, 900,000 input and 60,000 output tokens a minute, and the database connections and storage that follow. Beside each, give the current limit and the date by which it must rise. End with the behavior beyond capacity, the load test that confirmed the figures and the person who revisits them. A reader should be able to see which assumption, if wrong, would break the plan first.
Keep the plan current
Compare forecast with reality each month: arrivals, duration, tokens per task and utilization. Alert on queue age, quota use and saturation before users notice. After each release, check steps and tokens per task, since a prompt change can alter capacity needs. Keep the worksheet in version control beside the cost model (Agent Cost Model and Token Economics).
Trading speed, cost and quality
Improvements in one dimension usually move another. Decide which matters for each task type and write it down:
- Live chat favors quick first output, small steps and a clear route to a person.
- Research or coding tasks can run longer if progress is visible and results are better.
- Overnight processing favors low cost and completion before a deadline, which suits batch interfaces.
- Safety-critical actions favor verification and approval even when they add delay.
Faster service tiers, reserved capacity and speculative parallel calls buy time with money. Check the gain at the percentile you care about, because an option that improves the median may do little for the slowest tasks. Record the chosen trade-off with the target, so a later cost or speed project does not undo it unknowingly.
Common mistakes
| Mistake | Better approach |
|---|---|
| Sizing from averages | Use peaks, percentiles and headroom |
| Running near full load | Leave room for variation and failures |
| Ignoring token quota | Convert tasks into requests and tokens |
| Load tests that wait for replies before sending more | Drive a fixed arrival rate |
| Only short test prompts | Replay a realistic mix |
| Celebrating streaming as speed | Measure completion too |
Checklist
- Latency is broken down and reported by percentile.
- The critical path is known for main task types.
- Concurrency is estimated from peak arrivals and duration.
- Quota covers peak tokens and other traffic.
- Headroom matches the latency target and failure plan.
- Load, spike and degraded tests have been run.
- Correctness is checked during tests.
- Forecast and actual are reviewed regularly.
Frequently asked questions
What response time should an agent meet?
It depends on the task and user; set targets from what people need and measure both first output and completion.
Why does adding workers not help?
The limit may be model quota, a tool, a database or reviewers, so find where tasks actually wait.
How much headroom is enough?
Enough to meet your target during peaks and a failure; simulate and test rather than rely on one percentage.
Can we load test without paying for model calls?
Use a stub with realistic delays for most tests, then run limited real tests to confirm quotas and latency.
References and further reading
- Claude API rate limits.
- Google SRE book: handling overload.
- k6: open and closed load models.
- Amazon Builders' Library: load shedding.
Next steps
Agent FinOps, Budgets and Chargeback
Turn capacity into budgets.
Scaling, Hardware, Quotas and Caching
Enforce limits and share capacity.
Loops, Performance, Incidents and Maturity
Profile and respond when targets slip.