Sub topic 3
Why percentiles beat averages
Latency targets only work if the number you set describes what users experience. The average (mean) latency often fails at that. This chapter explains why, shows how to compute and combine percentiles correctly, and covers the mistakes that make percentile dashboards misleading.
I assume you can read short Python snippets and know the request path through a load balancer, a service and a database. I also assume you know the difference between latency (time for one request) and throughput (requests per second) from the earlier chapter.
Latency is a distribution
A service does not have one latency. Every request has its own, and the set of those values forms a distribution. Most requests hit a warm cache and an idle thread, and finish quickly. A few wait on a garbage-collection pause, a lock, a cold cache, a retry or a slow disk read. Latency distributions are therefore usually right-skewed: a tall cluster of fast requests and a long tail of slow ones.
The histogram below shows 1,000 requests grouped by the slowest time allowed in each bucket.
A single number must summarize this shape. The mean and the percentiles summarize it in very different ways.
What the mean hides
The mean adds every latency and divides by the count. A few extreme values pull it far from where most requests sit. Consider ten requests:
import math
def percentile(samples, p):
ordered = sorted(samples)
rank = math.ceil(p / 100 * len(ordered))
return ordered[rank - 1]
latencies_ms = [12, 15, 14, 13, 16, 18, 20, 22, 250, 900]
print(percentile(latencies_ms, 50)) # 16
print(percentile(latencies_ms, 99)) # 900
print(sum(latencies_ms) / len(latencies_ms)) # 128.0The mean is 128 ms. No request took anything close to 128 ms. Eight of the ten finished in 22 ms or less, and the other two took 250 ms and 900 ms. The mean describes neither the typical request nor the slowest ones.
The mean fails in two directions:
- It overstates the typical experience. A handful of slow requests drag it up, so a team may chase a problem that most users never see.
- It understates the worst experience. If you set a target of "average under 200 ms", the service above passes while one request in ten takes a quarter of a second or more.
The mean can also stay flat while the tail gets worse. If a change speeds up the fast majority by 2 ms and makes the slowest 1% twice as slow, the mean may barely move.
What a percentile says
The pN percentile (written pN, for example p99) is the value below which N% of requests fall. Put another way, p99 = 300 ms means 99% of requests finished in 300 ms or less and 1% took longer. The median, p50, splits the requests in half.
A percentile gives you a statement you can check against requests. "p99 under 300 ms" translates directly into "at most 1 request in 100 may be slower than 300 ms". That makes it a target you can verify, which the mean is not.
Common choices:
| Percentile | Reads as | Typical use |
|---|---|---|
| p50 | The typical request | Describing normal behavior and the effect of caching |
| p90 | 1 request in 10 is slower | Spotting early signs of load or contention |
| p95 | 1 request in 20 is slower | Common target for interactive features |
| p99 | 1 request in 100 is slower | Standard target for user-facing services |
| p99.9 | 1 request in 1,000 is slower | High-volume services, payments, strict agreements |
The nearest-rank method
The percentile function above uses the nearest-rank method. Sort the samples, compute rank = ceil(p/100 × n), and take the value at that position (counting from 1). With 10 samples, p50 is the 5th value and p99 is the 10th, which is why p99 equals the maximum here.
Monitoring tools may interpolate between neighboring values instead. The results differ slightly on small samples and agree on large ones. Pick one method and use it consistently when you compare runs.
A safer version for reuse guards against p = 0 and avoids floating-point drift by multiplying before dividing:
import math
def percentile(samples, p):
ordered = sorted(samples)
rank = max(1, math.ceil(p * len(ordered) / 100))
return ordered[rank - 1]Why the tail matters
It is tempting to treat p99 as a corner case because it affects "only 1%" of requests. Four things make that reasoning wrong.
- Users make many requests. A page load may issue 20 to 100 requests. If each has a 1% chance of being slow, a large share of page loads include at least one slow request. The chance is
1 - 0.99^n: about 18% for 20 requests and 63% for 100. - Slow requests are not random. They often belong to the users with the most data: the largest accounts, the longest carts, the biggest inboxes. Those users are frequently the most valuable.
- Slow requests hold resources longer. By Little's law (a later chapter), in-flight requests equal arrival rate times time in the system. A slow request occupies a thread, a connection and memory for longer. A growing tail can exhaust a pool even when the mean looks fine.
- Dependencies compound it. When one request waits for several backend calls, the slowest call decides the total. The fan-out chapter covers this in detail.
The tail also tends to signal trouble before the median does. Queueing, retries and lock contention usually hit the slowest requests first.
Reading a histogram
Real systems rarely keep every sample. Metrics libraries record counts in buckets, each with an upper bound, and compute percentiles from the cumulative counts. This is cheap to store and can be merged across servers, as the next section shows.
import math
def bucket_percentile(buckets, p):
"""buckets: list of (upper_bound_ms, count), sorted by upper bound."""
total = sum(count for _, count in buckets)
rank = max(1, math.ceil(p * total / 100))
seen = 0
for upper, count in buckets:
seen += count
if seen >= rank:
return upper
buckets = [(10, 700), (25, 250), (100, 40), (500, 9), (2000, 1)]
print(bucket_percentile(buckets, 50)) # 10
print(bucket_percentile(buckets, 95)) # 25
print(bucket_percentile(buckets, 99)) # 100The answer is the upper bound of the bucket that contains the requested rank, so it is an upper estimate. Its precision depends on bucket width. If your target is p99 under 300 ms and no bucket boundary lies near 300 ms, you cannot tell whether you meet it. Put bucket boundaries at or near each target value.
Mistakes that break percentile reporting
Averaging percentiles
You cannot compute a fleet-wide percentile by averaging per-server percentiles. A percentile depends on the full set of requests, and a server that handles few requests counts as much as a busy one.
import math
def percentile(samples, p):
ordered = sorted(samples)
rank = max(1, math.ceil(p * len(ordered) / 100))
return ordered[rank - 1]
server_a = [10] * 90 # 90 fast requests
server_b = [500] * 10 # 10 slow requests
avg_of_p99 = (percentile(server_a, 99) + percentile(server_b, 99)) / 2
true_p99 = percentile(server_a + server_b, 99)
print(avg_of_p99) # 255.0
print(true_p99) # 500The averaged figure of 255 ms matches no real request. One in ten requests took 500 ms, so the true p99 is 500 ms. To combine data, merge the raw samples or add the bucket counts of identical histograms, then compute the percentile once on the merged data.
Too few samples
A p99 from 100 requests rests on one or two values. A p99.9 needs at least 1,000 requests to be defined at all, and many more to be stable. For short load tests, either run longer or report a lower percentile and say so.
Choosing the wrong window
A p99 over a day hides a ten-minute incident. A p99 over ten seconds jumps around on noise. Pick a window that matches how the target is judged (the SLO chapter covers this), and keep the window the same when you compare two periods.
Measuring only the fast path
Several measurement habits remove exactly the requests you care about:
- Dropping failures. Timeouts and errors often have the longest latencies. If you exclude them, the percentiles look better than reality. Record latency for failed requests, or track them with a separate error rate.
- Measuring at the wrong place. Server-side timers miss time spent in the network, the load balancer's queue and the client. Measure at the point that matches the target, usually as close to the user as practical.
- Coordinated omission. A load generator that waits for each response before sending the next one slows down when the server slows down, so it records fewer slow requests than a real arrival stream would. Use a tool that sends requests on a fixed schedule and counts the delay from the intended send time.
Mixing different kinds of request
A single percentile over a search endpoint, a login endpoint and a file upload blends unrelated distributions. Report percentiles per endpoint or per request class, and set a target for each.
Choosing which percentile to target
Use the following criteria when you pick one.
- Request volume. At 10 requests per second, p99.9 is one request every 100 seconds, which is hard to measure. At 10,000 requests per second it is practical.
- Number of calls per user action. If one user action triggers many calls, a higher percentile (p99 or p99.9) on each call protects the action.
- Cost of a slow response. Payments and checkout justify stricter percentiles than a background recommendation widget.
- What you can improve. A p99.9 target that forces expensive redesign may buy little. Ask whether users would notice the difference.
A common pattern is to set two targets on the same measurement, such as p50 under 80 ms and p99 under 400 ms. The first keeps the typical experience fast. The second bounds the tail. Neither is enough alone.
A checklist for a percentile target
- Name the request class, such as
GET /search, not "the service". - State the percentile and the threshold, for example p99 under 300 ms.
- State where the time is measured: client, load balancer or server.
- State the window, for example the last 30 days or a rolling 5 minutes.
- State what counts: all responses, or only successful ones.
- Check that your histogram buckets have a boundary at the threshold.
- Confirm the traffic volume gives enough samples in the window.
The later chapters on SLIs and SLOs turn this checklist into a formal definition.
Exercise
A service has two servers. Server A handled 900 requests with a p99 of 40 ms. Server B handled 100 requests with a p99 of 800 ms. A teammate reports the fleet p99 as (40 + 800) / 2 = 420 ms. Explain why this is wrong, say whether the true fleet p99 could be higher or lower than 420 ms, and name the correct way to get it.
Show answer
Percentiles cannot be averaged, because each one depends on the full set of requests behind it and the average ignores how many requests each server handled. Here Server B supplied only 10% of the traffic, and the slowest 1% of the 1,000 combined requests (10 requests) could all come from B. If all 100 of B's requests were close to 800 ms, the true fleet p99 would be near 800 ms, which is higher than 420 ms. If B's slow requests were fewer than 10, the fleet p99 could be far lower. The correct method is to merge the raw samples, or add the bucket counts of identical histograms from both servers, and compute the percentile once on the merged data.
Exercise
Using the bucket_percentile function and the buckets [(10, 700), (25, 250), (100, 40), (500, 9), (2000, 1)], what does it return for p99.9 with exact integer arithmetic, and why would a target of "p99.9 under 300 ms" be impossible to verify with these buckets?
Show answer
There are 1,000 requests, so the p99.9 rank is 999. The cumulative counts are 700, 950, 990, 999 and 1000, so rank 999 falls in the 500 ms bucket and the answer is 500 ms. (Floating-point arithmetic can push 99.9 × 1000 / 100 slightly above 999 and give 2000 instead, so for fractional percentiles compute the rank with integers or decimals.) The bucket boundaries are 100 and 500, so the only statement available is that the request at rank 999 took somewhere between 100 ms and 500 ms. You cannot tell whether it is under 300 ms. Adding a bucket boundary at 300 ms makes the target checkable.