Sub topic 5
Latency objectives and tail latency
This chapter assumes you can read basic Python, know what p50 and p99 mean, and have seen an inference endpoint behind HTTP or gRPC. Earlier chapters covered why batching raises throughput and how dynamic batching groups requests. Here you set the latency target that limits how aggressively you can batch.
Why averages hide the problem
The mean latency of a service says little about what users experience. A server where 98% of requests take 20 ms and 2% take 800 ms has a mean of about 36 ms, which looks healthy. One request in fifty is still forty times slower than the rest. A user who makes several calls per page load will hit that slow path often.
Percentiles describe the distribution directly. The p99 is the latency that 99% of requests beat. The slowest 1% of requests, and everything beyond that point, is the tail.
| Metric | Meaning | Typical use |
|---|---|---|
| p50 (median) | Half of requests are faster | Typical experience |
| p95 | 1 in 20 requests is slower | Early warning of queueing |
| p99 | 1 in 100 requests is slower | Common SLO target |
| p99.9 | 1 in 1000 requests is slower | Strict or high-fan-out services |
| max | Slowest observed request | Debugging only, because it is noisy |
SLI, SLO, and SLA
Three terms are often mixed up:
- A service level indicator (SLI) is a measured quantity, such as "the fraction of requests that complete in under 100 ms".
- A service level objective (SLO) is an internal target for that indicator, such as "99% of requests complete in under 100 ms, measured over 30 days".
- A service level agreement (SLA) is a contract with consequences, usually looser than the SLO so you have room to react before you breach it.
A usable latency SLO names four things: the percentile, the threshold, the measurement window, and the measurement point. Measure at the client or load balancer if you can. Server-side timers miss network time and the time a request spends waiting in an accept queue before your code sees it.
The gap between 100% and your target is the error budget. An SLO of 99% under 100 ms allows 1% of requests to be slower. Spend that budget deliberately on batching delay, not by accident.
Measuring percentiles correctly
The following script simulates latencies with a long tail and computes the mean and percentiles with the nearest-rank method.
import math
import random
def percentile(sorted_values, p):
"""Nearest-rank percentile; p is in (0, 100]."""
rank = math.ceil(p / 100 * len(sorted_values))
return sorted_values[rank - 1]
random.seed(7)
# Lognormal latencies in milliseconds: most are fast, a few are very slow.
samples = sorted(random.lognormvariate(3.2, 0.6) for _ in range(10_000))
mean = sum(samples) / len(samples)
print(f"mean={mean:.1f} ms")
for p in (50, 95, 99, 99.9):
print(f"p{p}={percentile(samples, p):.1f} ms")The p99 comes out well above the mean, and p99.9 is higher still. Two pitfalls apply when you move this to production:
- Do not average percentiles across replicas. The mean of five p99 values is not the p99 of the combined traffic. Export histograms with fixed buckets and merge the bucket counts, then compute the quantile from the merged counts.
- Do not use summary quantiles computed inside each process for fleet-wide SLOs, for the same reason.
In Prometheus, a fleet-wide p99 from histogram buckets looks like this:
histogram_quantile(0.99, sum by (le) (rate(request_latency_seconds_bucket[5m])))Place a bucket boundary at or near your SLO threshold. Otherwise the quantile is interpolated inside a wide bucket and the result is inaccurate exactly where you need it.
Where tail latency comes from in a batching server
A request's latency is a sum of stages. In a server with dynamic batching, the stages are:
- Network, TLS, and request parsing.
- Waiting in the queue while a previous batch occupies the accelerator.
- Waiting for the batch to fill, up to the maximum queue delay.
- Model execution for the whole batch.
- Postprocessing and the response.
Stages 2 and 3 are the ones your configuration controls, and they behave differently. The batch formation wait is bounded: it can never exceed the maximum queue delay you set. The queue wait is not bounded. It grows sharply as utilization approaches 100%, because requests arrive while the accelerator is still busy. This is why the tail often looks fine at 50% load and collapses at 90%.
Other common sources of tail latency are not specific to batching:
- Garbage collection pauses or Python global interpreter lock contention in the serving process.
- Variable input size, such as long sequences or large images, which makes one batch slower than another. Every request in a batch waits for the slowest member.
- Padding waste, where short inputs are padded up to the longest input in the batch.
- A replica that has just started and has not warmed up its caches or compiled kernels.
- Noisy neighbors on shared hosts, and retries from clients that time out too early.
Tail amplification with fan-out
If one user request calls several models or replicas and waits for all of them, the slowest call decides the total. Suppose each call has a 1% chance of being slow. The chance that at least one of n parallel calls is slow is 1 - 0.99^n:
- n = 1: 1%
- n = 10: about 9.6%
- n = 100: about 63.4%
A p99 target for the whole request therefore needs a stricter target for each component. This is the main reason strict services track p99.9 on their inner calls.
Turning an SLO into a batching budget
The SLO caps the sum of every stage in the worst case. You can then work backwards to the maximum queue delay. A request that arrives just after a batch started waits for that batch to finish, then waits up to the maximum queue delay, then runs in its own batch. The worst-case latency for a request that does not overflow the queue is roughly:
overhead + compute + max_wait + compute
The function below checks a candidate configuration against an SLO.
def worst_case_ms(overhead_ms, max_wait_ms, compute_ms):
"""Arrive just after a batch starts: wait for it, wait to fill, then run."""
return overhead_ms + compute_ms + max_wait_ms + compute_ms
def fits_slo(slo_ms, overhead_ms, max_wait_ms, compute_ms, headroom=0.8):
"""Keep worst case under a fraction of the SLO to leave room for load spikes."""
worst = worst_case_ms(overhead_ms, max_wait_ms, compute_ms)
return worst, worst <= slo_ms * headroom
# p99 SLO of 100 ms; a batch of 8 takes 30 ms; network and parsing take 10 ms.
for wait in (5, 10, 20, 30):
worst, ok = fits_slo(100, 10, wait, 30)
print(f"max_wait={wait:>2} ms -> worst case {worst} ms, within headroom: {ok}")With these numbers, a 10 ms wait gives an 80 ms worst case, which fits in 80% of the SLO. A 20 ms wait gives 90 ms, which leaves too little room for spikes. Measure compute time at your real maximum batch size, because it grows with batch size and the budget must use the slowest case.
This calculation assumes the queue is not saturated. Once arrivals exceed capacity, queue wait is unbounded and no batching setting can save the SLO. The fix at that point is more replicas, which later chapters cover.
Common errors
- Setting an SLO from the mean. Use a percentile.
- Testing latency with a single client sending one request at a time. This never forms a batch and never queues, so it measures neither effect. Load test at realistic concurrency.
- Choosing a maximum queue delay without measuring compute time at maximum batch size.
- Reporting p99 averaged across pods.
- Ignoring client timeouts. If the client gives up at 200 ms and retries, the server still does the abandoned work, which adds load and worsens the tail.
- Comparing p99 over a short window. A 1-minute p99 on a low-traffic service rests on few samples, so use a longer window or enough traffic to support the percentile.
Exercise
Your p99 SLO is 120 ms. Network and parsing take 15 ms, a batch at your maximum batch size takes 35 ms to execute, and you want the worst case to stay under 80% of the SLO. What is the largest maximum queue delay (in whole ms) that fits, using worst case = overhead + compute + max_wait + compute?
Show answer
80% of 120 ms is 96 ms. The fixed parts are 15 + 35 + 35 = 85 ms. That leaves 96 - 85 = 11 ms, so the largest maximum queue delay is 11 ms.
Exercise
A request fans out to 20 replicas in parallel and each replica has a 0.5% chance of exceeding the target latency. What is the approximate chance that the overall request is slow, and why can't you fix this by averaging each replica's p99?
Show answer
The chance is 1 - 0.995^20, which is about 9.5%. Averaging p99 values does not describe the combined distribution, and it hides that the slowest call sets the overall latency. You need merged histograms for fleet-level percentiles and stricter per-replica targets for fan-out calls.