Skip to content

Latency, throughput and queueing

Phase 4 · Concurrency and performance · 15 min read

What you'll be able to do

  • Translate a traffic estimate into requests per second, requests in flight, server capacity, and storage.
  • Read p50, p95, and p99 latency without hiding slow users behind an average.
  • Explain when a faster service, more headroom, or a different load test will improve response time.

Five quantities, one request path

Latency is elapsed time for one request, from the caller's send to its usable response. Throughput is completed work per unit time, such as requests per second (QPS) or tokens per second. Bandwidth is data transferred per unit time, such as MB/s. Ample network bandwidth does not imply spare CPU capacity.

Concurrency counts requests in the system, including those waiting. Say where the system starts and ends: the caller's view includes network transit, while the server's view does not. Utilization is the fraction of a resource's capacity in use. For a worker able to complete 100 similar requests/s, 80 requests/s means about 80% utilization. Expensive requests change that estimate.

Little's Law connects long-run averages for a stable system: L = λ × W, where L is average requests in flight, λ is arrival rate, and W is time in the system. Units must match, and L and W must use the same boundary. At 200 requests/s and 50 ms (0.050 s) average time spent in a server, L = 200 × 0.050 = 10 requests in flight in that server, including waiting and processing. If W is instead measured from the caller's send to its response, L counts requests the callers have outstanding, including those on the network.

rate_per_second = 200
average_seconds = 50 / 1000
print(rate_per_second * average_seconds)  # 10.0

Averages hide the tail

Percentiles mark positions in sorted observations: p50 is the median, while p95 and p99 describe the slow end. With many observations, about 95% fall at or below p95. Conventions differ, especially for small samples, so keep the method consistent. The lab interpolates at zero-based rank (n - 1) * p / 100: for [1, 2, 3, 4, 10], p95 is 8.8, although only four of the five measured values are at or below it. A 100 ms mean could hide a painful tail.

The tail becomes prominent when one user request waits for many backends. Suppose 100 independent calls run in parallel, each with a 1% chance of being slow, and the response waits for all. The chance of at least one slow call is 1 − 0.99^100 ≈ 0.634, or 63%. Shared outages can correlate calls; partial results can change what the user sees.

Never average p99 values from shards or time windows: ranks cannot be combined that way. Pool raw observations or merge compatible histograms, then recalculate. Report request count and errors too; dropping timeouts can make a failing service look fast. Observability covers surrounding metrics.

Why a busy server slows before it is full

Imagine one worker serving requests in arrival order. If it is busy, the next request waits. Near capacity, small timing variations create a queue that takes longer to drain. Latency bends sharply upward near full utilization; no percentage is safe for every workload.

For a stylized M/M/1 queue, arrivals and service times have particular random distributions, one worker serves one request at a time, and λ must be less than service rate μ. Its average total time in the system, including service, is W = 1 / (μ − λ). With μ = 100 requests/s:

Arrivals λ Utilization λ/μ Mean total time W
50/s 50% 1/50 s = 20 ms
80/s 80% 1/20 s = 50 ms
90/s 90% 1/10 s = 100 ms
95/s 95% ⅕ s = 200 ms

The worker's mean service time remains 10 ms; the rest is waiting. Real systems have multiple workers, variable costs, and shared dependencies, so this is an illustration. Leave headroom for bursts and failures; choose a limit by testing p95/p99 and errors at peak. At capacity, an unbounded queue grows until something rejects, times out, or fails.

Measure the workload users actually send

An open load generator schedules arrivals independently of completion, such as 100 new requests each second. In a closed test, each client sends another request only after its last one finishes. A server stall then slows arrivals, concealing overload if real demand keeps coming. Report arrival rate, concurrency, request mix, and duration.

Coordinated omission happens when a test records only requests it managed to send. A client meant to send every 10 ms pauses for one 1-second response, omitting roughly 100 scheduled requests that would have waited in an open workload. For open demand, schedule independently of responses and account for delay from intended send time. Measure at the external client so queueing and network count.

Warm up connections, caches, and workers before comparing steady-state runs; measure cold starts separately if users experience them. Put the generator on another machine, verify it keeps up, and report failures and timeouts.

Napkin math before the load test

These are rough orders of magnitude, not benchmarks. Hardware, locality, payload, contention, and the work inside an API call can move each by a lot. Use them to spot a suspicious plan, then measure your system.

Operation Rough time scale
One main-memory access ~100 nanoseconds
One small random SSD read tens to hundreds of microseconds
Same-region network round trip sub-millisecond to several milliseconds
Cross-region network round trip tens to hundreds of milliseconds
Remote API call including server work tens of milliseconds to seconds

For capacity, suppose 50,000 daily users make 20 requests each. That is 1,000,000 requests/day, or 1,000,000 / 86,400 ≈ 11.6 average QPS. If peak is ten times average, plan for about 116 QPS. If a load test shows one server handles 40 QPS at the target p99, three servers barely fit (120 QPS); four carry about 29 QPS each and leave room for one server to fail (116 / 3 ≈ 38.7). If each request also writes 2 KB, storage grows by about 2 GB/day or 60 GB in 30 days, before indexes, replication, and backups. Every bold number depends on the stated assumptions; revise them with traffic and data measurements.

Budget latency and choose a lever

An end-to-end latency budget allocates time to each hop, including queueing and slack. For a 500 ms target, one plan is 50 ms network, 100 ms app work, 120 ms database, 130 ms downstream call, and 100 ms reserve: 50 + 100 + 120 + 130 + 100 = 500 ms. Trace real requests to see which hop consumes the budget. A downstream timeout must be shorter than the caller's remaining deadline, with time left to handle failure and return a response. The timeouts and retries lesson covers the failure behavior.

The lever depends on the bottleneck. Batching amortizes setup work and often raises throughput, but waiting to fill a batch raises individual latency. Pipelining overlaps stages or sends later work before earlier replies, reducing idle time while increasing work in flight. Caching avoids repeated work, but misses still need capacity. Parallelism can shorten independent work when resources are available, while extra contention can worsen tails. A queue can absorb a short burst and protect a worker, but it moves waiting time; it cannot make sustained overload disappear. Measure both throughput and user-visible tail latency after each change.

For AI engineers

For AI engineers

In LLM serving, time to first token, generated tokens per second, and total response latency answer different questions. Batching prompts can raise GPU throughput while a request waits longer to enter the batch. For a multi-step agent, one slow tool call can dominate the whole run; a mean-only dashboard hides the runs users abandon.

Budget a RAG request from the user's click: for a 2,000 ms target, allow 100 ms ingress, 150 ms embedding, 100 ms retrieval, 150 ms reranking, 1,200 ms generation, and 300 ms reserve. The sum is 2,000 ms, but the allocation is a planning example, not a prediction. Measure p95/p99 for the whole request and for each stage, including queueing and first-token delay. Streaming can improve perceived responsiveness even when total generation time stays similar.

Common mistakes

  • Reporting only the mean: include p50, p95, p99, counts, timeouts, and errors for the user-facing request.
  • Testing on the server machine: load-generation work competes with the service and distorts capacity.
  • Skipping warm-up: cold connections and caches can dominate a short run; report cold and warm behavior separately.
  • Running at 95% because it sounds efficient: test headroom against bursts, failures, and your p99 target.
  • Retrying overload immediately: retries add arrival work to an already busy dependency. Respect remaining deadlines and cap attempts.
  • Mixing units or optimizing the wrong metric: convert milliseconds to seconds in Little's Law; throughput gains can worsen user latency.

Check yourself

A service receives 300 requests/s and average end-to-end latency, measured at the caller, rises from 40 to 100 ms. About how many requests are now in flight?

Little's Law gives L = 300 × 0.100 = 30 requests outstanding at the callers, up from 300 × 0.040 = 12. That count includes network transit, so not all 30 are necessarily inside the server. The increase may include requests waiting in a queue.

Two equal-sized shards report p99 values of 100 ms and 900 ms. Can you report 500 ms as their combined p99?

No. Pool request latencies, or merge compatible histograms, and find the combined 99th percentile. The two shard p99 values do not contain enough information to calculate it.

A fixed group of test clients sends its next request only after a response. The server pauses for a second, yet the reported p99 barely changes. What should you inspect?

This is a closed workload. Check whether arrivals fell during the pause and whether scheduled requests were omitted. For an open-demand scenario, schedule arrivals independently and measure from intended send time at the client.

A worker is at 95% utilization and requests begin timing out. Would a bigger input queue solve sustained overload?

No. It may absorb a brief burst, but if arrivals keep approaching or exceeding capacity, waiting grows. Reduce work, add capacity, shed excess load, or control arrivals, then measure the tail again.

Lab

Build a deterministic latency toolkit in code/latency-throughput/. Calculate interpolated percentiles, Little's Law, fan-out risk, and M/M/1 mean total time. Simulate a single FIFO worker from given arrival and service times. Summarize observed latencies with count, mean, p50, p95, p99, and max. Run: cd code/latency-throughput && PYTHONPATH=starter python -m pytest tests -q

Go deeper