Latency, Throughput and Dynamic Batching
A model service has two performance numbers that pull in opposite directions. Latency is how long one request takes; users and calling services feel it. Throughput is how many requests per second the service can handle; the budget feels it, because it decides how many machines you need. Making the model faster helps both. Beyond that, most tuning trades one for the other: batching requests raises throughput and adds waiting time, running machines less busy lowers latency and raises the bill. This lesson gives the three tools to reason about it: percentiles, a little queueing theory, and a simulation of dynamic batching.
Latency is a distribution: percentiles
The mean latency is almost useless for a service. A few slow requests (a garbage-collection pause, a cache miss, a large input) barely move the mean but are exactly what users complain about. Latency is described by percentiles: the p50 (median) is the typical request, the p95 and p99 are the slow tail. "p99 = 120 ms" means 99 % of requests finish within 120 ms. Service level objectives are written in percentiles (SLOs), and monitoring systems estimate them from histograms (histogram quantiles).
The tail matters even more when one user action needs several calls. If a page calls services in parallel and must wait for all of them, and each is independently slower than its p99 with probability 0.01, the page is slow when any of them is:
For that is about 0.096: almost one page in ten sees at least one p99-slow call.
import numpy as np
rng = np.random.default_rng(0)
n = 100_000
lat = rng.lognormal(np.log(20), 0.35, n) # typical requests: around 20 ms
slow = rng.random(n) < 0.02 # 2 % hit a pause or a cache miss
lat[slow] += rng.uniform(100, 300, slow.sum())
p50, p95, p99 = np.percentile(lat, [50, 95, 99])
print(f"mean {lat.mean():.1f} ms | p50 {p50:.1f} | p95 {p95:.1f} | p99 {p99:.1f} | max {lat.max():.0f}")
calls = rng.choice(lat, size=(20_000, 10)) # a page that waits for 10 parallel calls
page = calls.max(axis=1)
print(f"page latency (max of 10 calls): p50 {np.percentile(page, 50):.1f} ms, p95 {np.percentile(page, 95):.1f} ms")
print(f"share of pages with a call above the p99: {(calls > p99).any(axis=1).mean():.3f}, "
f"formula 1 - 0.99^10 = {1 - 0.99 ** 10:.3f}")mean 25.2 ms | p50 20.2 | p95 38.4 | p99 222.7 | max 341
page latency (max of 10 calls): p50 35.8 ms, p95 269.8 ms
share of pages with a call above the p99: 0.096, formula 1 - 0.99^10 = 0.096
The 2 % of slow requests move the mean only from about 20 to 25.2 ms, and the p95 (38.4 ms) does not see them at all, but they set the p99 at 222.7 ms. A page that waits for ten such calls has a median of 35.8 ms and a p95 of 269.8 ms: what is a rare tail event for one service is the common case for the page. The simulated share of pages with at least one call above the p99, 0.096, matches the formula.
Queueing: why latency explodes near full load
Requests do not arrive evenly. Even at an average load the server can handle, some moments bring several requests at once and they queue. The simplest model that captures this is the M/M/1 queue: random (Poisson) arrivals at rate , one server, exponential service times with rate (mean service time ). Its utilisation is
and as long as the mean time in the system (waiting plus service) is
The factor is the whole story: at 50 % utilisation a request takes on average twice its service time, at 80 % five times, at 90 % ten times, at 95 % twenty times. For M/M/1 the time in the system is even exponentially distributed with rate , so its p99 is , about 4.6 times the mean. Real services are not exactly M/M/1 (service times are less variable, there are several workers), but the shape, flat at low load and steep near saturation, is universal. It is why capacity plans keep servers well below 100 % busy (capacity planning), and why the previous lesson sized replicas at 60 %. Little's law from that lesson still holds on top.
import numpy as np
import matplotlib.pyplot as plt
def simulate(lam, mu, n=60_000, seed=0):
rng = np.random.default_rng(seed)
arr = np.cumsum(rng.exponential(1 / lam, n))
svc = rng.exponential(1 / mu, n)
done, free = np.empty(n), 0.0
for i in range(n):
free = max(arr[i], free) + svc[i]
done[i] = free
return (done - arr)[n // 10:] # drop the warm-up
mu = 100.0 # 10 ms mean service time
print(" rho | mean W sim / theory (ms) | p99 sim / theory (ms)")
rhos, p99s = [0.5, 0.7, 0.8, 0.9, 0.95], []
for rho in rhos:
w = simulate(rho * mu, mu) * 1000
p99s.append(np.percentile(w, 99))
theory = 1000 / (mu - rho * mu)
print(f"{rho:4.2f} | {w.mean():6.1f} / {theory:6.1f} | {p99s[-1]:6.1f} / {np.log(100) * theory:6.1f}")
r = np.linspace(0.3, 0.97, 100)
plt.figure(figsize=(6, 3.4))
plt.plot(r * 100, 1000 / (mu * (1 - r)), label="mean W (theory)")
plt.plot(r * 100, np.log(100) * 1000 / (mu * (1 - r)), label="p99 (theory)")
plt.plot(np.array(rhos) * 100, p99s, "o", label="p99 (simulation)")
plt.xlabel("utilisation (%)"); plt.ylabel("time in system (ms)"); plt.yscale("log")
plt.title("M/M/1, mean service time 10 ms"); plt.legend(); plt.tight_layout()
plt.show() rho | mean W sim / theory (ms) | p99 sim / theory (ms)
0.50 | 19.9 / 20.0 | 93.4 / 92.1
0.70 | 33.4 / 33.3 | 164.3 / 153.5
0.80 | 49.3 / 50.0 | 245.8 / 230.3
0.90 | 94.5 / 100.0 | 482.6 / 460.5
0.95 | 175.6 / 200.0 | 903.8 / 921.0
The simulated means follow closely up to 80 % (49.3 ms against 50.0) and fall a bit short at 90 and 95 %, where a run of 54,000 requests is not long enough to see the rare very long queues; the p99 follows in the same way. In the plot (log scale), the p99 grows from about 90 ms at 50 % utilisation to about 900 ms at 95 %, for a model whose average work per request never changed from 10 ms.
Dynamic batching
Most models are much more efficient on a batch than on single rows. A forward pass has a fixed cost (Python and framework overhead, a kernel launch, reading the weights from memory) plus a cost per row; on a GPU the per-row part is tiny until the batch is large (GPU inference). With a batch time of
for rows, fixed cost and per-row cost , one worker can process at most
rows per second with batches of , which grows towards as grows. With ms and ms, single requests give at most 111 per second, batches of 16 give 667.
But clients send one request at a time. Dynamic batching collects them on the server: requests wait in a queue, and the batcher starts a batch when either max batch size requests are waiting or the oldest request has waited max wait (and the worker is free). bounds the batch cost; bounds the extra latency a request pays for waiting at low load. Serving systems such as NVIDIA Triton, Ray Serve and TorchServe (archived since 2025) implement exactly these two knobs; LLM servers go further with continuous batching, where requests join and leave a running batch between generated tokens.
From scratch: simulating the batcher
One worker, Poisson arrivals, ms, ms. For each policy the simulation reports the latency percentiles (waiting plus batch time), the mean batch size, and whether the worker keeps up at all (achieved throughput versus offered load).
import numpy as np
A, B_COST = 0.008, 0.001 # batch time s(n) = a + b n, in seconds
def serve(lam, max_batch, max_wait, n=20_000, seed=0):
arr = np.cumsum(np.random.default_rng(seed).exponential(1 / lam, n))
lat, sizes, free, i = np.empty(n), [], 0.0, 0
while i < n:
ready = max(free, arr[i]) # worker free and at least one request waiting
j_full = min(i + max_batch - 1, n - 1)
launch = max(ready, min(arr[i] + max_wait, arr[j_full])) # full batch, or oldest waited T
size = min(max_batch, int(np.searchsorted(arr, launch, side="right")) - i)
free = launch + A + B_COST * size
lat[i:i + size] = free - arr[i:i + size]
sizes.append(size); i += size
keep = lat[n // 10:] * 1000
throughput = n / (free - arr[0])
return np.percentile(keep, 50), np.percentile(keep, 99), np.mean(sizes), throughput
for lam in (80, 300, 600):
print(f"offered load {lam} requests/s")
for max_batch, max_wait in [(1, 0), (8, 0), (8, 0.004), (32, 0.004), (32, 0.020)]:
p50, p99, size, thr = serve(lam, max_batch, max_wait)
status = "ok" if thr > 0.98 * lam else f"OVERLOADED ({thr:.0f}/s served)"
cap = max_batch / (A + B_COST * max_batch)
print(f" B={max_batch:2d} T={max_wait * 1000:2.0f} ms (cap {cap:4.0f}/s): p50 {p50:7.1f} ms "
f"p99 {p99:7.1f} ms mean batch {size:4.1f} {status}")offered load 80 requests/s
B= 1 T= 0 ms (cap 111/s): p50 16.4 ms p99 76.3 ms mean batch 1.0 ok
B= 8 T= 0 ms (cap 500/s): p50 11.4 ms p99 19.8 ms mean batch 1.2 ok
B= 8 T= 4 ms (cap 500/s): p50 13.2 ms p99 20.0 ms mean batch 1.4 ok
B=32 T= 4 ms (cap 800/s): p50 13.2 ms p99 20.0 ms mean batch 1.4 ok
B=32 T=20 ms (cap 800/s): p50 27.8 ms p99 33.8 ms mean batch 2.6 ok
offered load 300 requests/s
B= 1 T= 0 ms (cap 111/s): p50 62606.4 ms p99 112752.6 ms mean batch 1.0 OVERLOADED (111/s served)
B= 8 T= 0 ms (cap 500/s): p50 18.2 ms p99 30.1 ms mean batch 3.5 ok
B= 8 T= 4 ms (cap 500/s): p50 18.1 ms p99 29.9 ms mean batch 3.6 ok
B=32 T= 4 ms (cap 800/s): p50 18.1 ms p99 29.5 ms mean batch 3.6 ok
B=32 T=20 ms (cap 800/s): p50 27.7 ms p99 40.0 ms mean batch 7.1 ok
offered load 600 requests/s
B= 1 T= 0 ms (cap 111/s): p50 80805.4 ms p99 145567.3 ms mean batch 1.0 OVERLOADED (111/s served)
B= 8 T= 0 ms (cap 500/s): p50 3824.9 ms p99 6846.3 ms mean batch 8.0 OVERLOADED (500/s served)
B= 8 T= 4 ms (cap 500/s): p50 3828.3 ms p99 6849.8 ms mean batch 8.0 OVERLOADED (500/s served)
B=32 T= 4 ms (cap 800/s): p50 31.8 ms p99 55.9 ms mean batch 12.2 ok
B=32 T=20 ms (cap 800/s): p50 35.2 ms p99 57.5 ms mean batch 14.3 ok
What the table shows:
- Batching is what makes the load possible. Without batching () one worker handles at most 111 requests per second; at 300 and 600 per second the queue grows without bound and latencies reach minutes. With the worker copes with 300 per second (p99 30.1 ms) but not with 600 (capacity 500); with it handles 600 per second at a p99 of 55.9 ms.
- Batching helps latency even at low load. At 80 per second, without waiting (: the worker takes whatever is queued when it becomes free) has a lower p99 than (19.8 against 76.3 ms), because the occasional cluster of requests is served in one pass instead of queueing.
- Waiting is a cost when traffic is light. At 80 per second, ms nearly doubles the batch size (2.6 against 1.4) but raises the p50 from 13.2 to 27.8 ms: requests wait for companions that rarely come. At 600 per second the batches fill anyway (12.2 rows with ms), so hardly matters there.
- The batch size grows with the load by itself. With , ms, the mean batch is 1.4 rows at 80 per second, 3.6 at 300 and 12.2 at 600. That self-adjustment is the point of dynamic batching: the service stays efficient at high load and responsive at low load.
The parameters here ( ms, ms) are illustrative; measure for your model and hardware by timing batches of different sizes, then simulate or load-test the policies against your traffic.
Pitfalls
- Reporting the mean. Report p50, p95, p99 (and the max for debugging), over a stated window and request mix.
- Benchmarking without queueing. Timing one request at a time measures service time, not latency under load; load-test with realistic arrival rates.
- Running hot. Utilisation above about 80 % makes the tail explode at the first burst; leave headroom, autoscale on queue length or latency, and shed load when overloaded (load shedding).
- Max wait too long. At low traffic every request pays up to ; choose as a small share of the latency budget.
- Batches that mix very different inputs. Padding to the longest sequence in a batch wastes the gain; group by length.
- Measuring in the client only. Separate queue time, batch time and network time in metrics, or you cannot tell which to fix.
Practice
- An M/M/1 service has a mean service time of 5 ms. What is its mean time in the system at 100 and at 180 requests per second?
- A model's batch time is ms. What is the maximum throughput of one worker with and with ?
- Traffic is low at night (20 requests per second) and the batcher uses , ms. What do night-time users notice, and what would you change?
Answers
- per second. At : ms (). At : s ms (). The load grew by 80 %, the mean latency by a factor of five.
- : per second. : per second.
- With 20 requests per second, 32 requests take about 1.6 s to accumulate, so almost every batch is started by the 50 ms timeout and most requests wait tens of milliseconds for nothing. Lower (a few ms), or make it adaptive: start immediately when the worker is idle and the queue is short.
Test yourself
Why are latency SLOs written as percentiles such as p99 rather than as the mean?
- Percentiles are easier to compute
- The mean hides the slow tail that users actually experience
- The mean is always larger
- Monitoring systems cannot compute means
In an M/M/1 queue, how many times its service time does a request spend in the system on average at 90 % utilisation?
- 1.1
- 2
- 10
- 90
What do the two knobs of a dynamic batcher control?
- Max batch size bounds batch cost and throughput gain; max wait bounds the extra latency at low load
- Both control the model's accuracy
- Max wait sets the timeout of the client
- Max batch size sets the number of replicas
With batch time , what happens to one worker's maximum throughput as the batch size grows?
- It falls
- It stays constant
- It grows towards , because the fixed cost is shared by more rows
- It grows without limit