Histograms, percentiles and why you cannot average them
What p99 means to a user, why the mean and the average of percentiles both lie, and how buckets, native histograms and sketches trade memory for error
Three hosts serve the same API. Host A handles 90% of requests and reports p99 = 130 ms. Host B handles 9% and reports p99 = 128 ms. Host C handles 1% and reports p99 = 2,780 ms. A dashboard shows avg(p99) = 1,013 ms. What is the p99 across all requests?
Metrics 101 introduced the histogram as one of the four instrument types. This chapter is about what you do with one: how to read it, what it can and cannot tell you, and the mistakes that turn a correct histogram into a wrong dashboard.
Why the mean hides the tail
Latency distributions are not bell curves. They have a hard floor (the request cannot be faster than the network round trip plus the work) and a long right tail made of garbage-collection pauses, lock waits, retries, cold caches and the occasional disk that takes 400 ms. In the demo app with FAULT_SLOW_PAYMENTS_PCT=2, 98% of charges take about 20 ms and 2% take between 1.5 and 3 s. The mean is about 65 ms. No request takes 65 ms. The mean describes nobody.
The mean also moves the wrong way. If you fix the slow 2%, the mean drops by 45 ms and the team celebrates a 70% improvement that 98% of users did not notice. If a deploy makes every request 10 ms slower while removing a rare 3-second stall, the mean might go down while every single user got slower. The SRE book’s advice is blunt: collect request counts bucketed by latency, not averages, because a system designed around the mean is designed for nobody.
The mean is still worth having for one job: capacity. Mean latency multiplied by throughput is the average number of requests in flight (Little’s law), which tells you how many workers you need. From a Prometheus histogram it is exact, because _sum and _count are exact:
sum(rate(http_server_request_duration_seconds_sum{job="payments"}[5m]))
/
sum(rate(http_server_request_duration_seconds_count{job="payments"}[5m]))
For anything a user feels, use percentiles.
What p99 means to a user
The p99 is the value that 99% of requests are at or below. One request in a hundred is slower. That sounds like a rare event until you count how many requests a user makes.
A web page that calls 20 backend endpoints is slow if any of them is slow. The probability that all 20 land under the backend p99 is 0.99^20, about 0.82. So 18% of page loads see at least one p99-or-worse response. At 100 calls per page, typical for a single-page app on first load, it is 63%: the backend’s p99 is the median page experience. Jeff Dean and Luiz Barroso’s “The Tail at Scale” makes the same argument for fan-out inside a datacentre, and the tail-latency lesson lets you see it:
// wait for every shard
const parts = await Promise.all(shards.map((s) => s.query(q)));
// latency = the slowest of N callsasync function hedged(q, replicas, delayMs) {
let done = false;
const first = replicas[0].query(q).finally(() => { done = true; });
// send the backup only if the primary is still silent after delayMs
const backup = sleep(delayMs).then(() => (done ? first : replicas[1].query(q)));
return Promise.any([first, backup]); // first answer wins
}
const parts = await Promise.all(shards.map((s) => hedged(q, s.replicas, P95_MS))); Watch the parent p99 as you raise the fan-out. Each backend is unchanged; the parent’s tail grows because it waits for the slowest of many. That is why you alert on p99 or p99.9 at the edge and why a backend team that reports a good median has told you almost nothing.
Why you cannot average percentiles
A percentile is a rank within one population. Two populations’ p99s cannot be combined without knowing the populations, and averaging them throws that knowledge away. The Prometheus documentation’s own wording is that averaging quantiles yields statistically nonsensical values.
The Predict above is a real case from the lab. Host C served 1% of traffic, and its 2.8-second p99 dragged the average of p99s to over a second while the true p99 was 131 ms. Flip the mix and it lies in the other direction: if the slow host serves 40% of traffic and the fast hosts’ p99s are averaged in, the average understates the tail.
The same rule applies across time, and this is the one people break without noticing. A Grafana panel showing p99 over 24 hours at 1-minute resolution, with the legend’s “mean” calculation turned on, is averaging 1,440 p99s. A recording rule that stores job:latency:p99 every minute and a weekly report that averages it is the same mistake. A quiet minute with 10 requests counts the same as a busy minute with 10,000.
The fix is always the same: aggregate the histogram, then compute the quantile.
# Wrong: quantile per instance, then average
avg(histogram_quantile(0.99, sum by (instance, le) (rate(http_server_request_duration_seconds_bucket{job="payments"}[5m]))))
# Right: sum the bucket rates across instances, then one quantile
histogram_quantile(0.99, sum by (le) (rate(http_server_request_duration_seconds_bucket{job="payments"}[5m])))
# Right, over a day: widen the rate window instead of averaging minutes
histogram_quantile(0.99, sum by (le) (rate(http_server_request_duration_seconds_bucket{job="payments"}[1d])))
Buckets are counters, so they add. That is the property that makes histograms aggregatable and summaries not. A Prometheus summary computes quantiles in the client, per process, and no query can merge them. If you have summaries and need a fleet-wide p99, you need histograms.
If you record anything, record the summed bucket rates: sum by (job, le) (rate(..._bucket[1m])). Quantiles computed from that later are correct. Quantiles computed and then stored are a dead end.
Classic buckets and the error they introduce
A classic Prometheus histogram is a set of cumulative counters, one per upper bound le, plus +Inf, _sum and _count. The OTel HTTP semantic conventions recommend these boundaries for http.server.request.duration, in seconds:
0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5, 7.5, 10
histogram_quantile(φ, ...) finds the bucket that contains the rank φ × count and assumes observations are spread uniformly inside it, interpolating linearly between the bucket’s lower and upper bound. The true value is somewhere in that bucket. Nothing more is known.
So the error is the bucket width. With the default boundaries, a true p99 of 260 ms lands in the (0.25, 0.5] bucket and the estimate can be anywhere from 250 to 500 ms depending on how many observations sit in that bucket. A true p99 of 1.6 s lands in (1, 2.5], a bucket 1.5 seconds wide. The Prometheus histogram practices page gives a sharper example: with buckets around a 300 ms target, a latency spike at 220 ms is estimated at 295 ms, with the only guarantee being that the truth is between 200 and 300 ms.
Three edge cases from the histogram_quantile docs are worth knowing by heart:
- If the rank falls in the
+Infbucket, the function returns the upper bound of the highest finite bucket. A p99 that is really 30 seconds is reported as 10. A flat line at exactly your top boundary means “off the scale”, not “10 seconds”. - In the lowest bucket, the lower bound is taken as 0 and the estimate interpolates from there.
- If there were no observations in the window, the result is
NaN, which Grafana draws as a gap.
The rule that follows: put boundaries where decisions are made. If the SLO is “99% under 300 ms”, you want a boundary at exactly 0.3, because then the fraction of requests under 300 ms is an exact ratio of two counters and needs no interpolation at all. The default OTel boundaries do not have 0.3. Adding one is an SDK View in the service’s telemetry setup:
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.view import View, ExplicitBucketHistogramAggregation
latency_view = View(
instrument_name="http.server.request.duration",
aggregation=ExplicitBucketHistogramAggregation(
boundaries=[0.01, 0.025, 0.05, 0.1, 0.2, 0.3, 0.4, 0.5, 1, 2, 3, 5]),
)
provider = MeterProvider(metric_readers=[reader], views=[latency_view])
Every boundary is one more time series per label combination. Fifteen buckets times 5 status codes times 3 routes times 3 services is 675 series for one metric before you add a single label. That cost is why classic histograms are coarse, and why the next idea exists.
Native and exponential histograms
A native histogram in Prometheus is one series whose samples are whole histograms, with buckets whose boundaries are fixed by a formula rather than chosen by you. For schema n, each boundary is the previous one times 2^(2^-n). Schema 3, which is what the client libraries’ default bucket factor of 1.1 selects, gives a growth factor of 2^(1/8) ≈ 1.0905. Buckets are sparse: only buckets that received an observation are stored.
Two consequences follow. First, the relative error is the same at every magnitude. A value at a bucket’s midpoint is at most (base − 1) / (base + 1) away from either edge, which for schema 3 is 4.3%. A p99 of 2 ms is known to within about 0.09 ms; a p99 of 2 s to within about 90 ms. Classic buckets give you 1 ms precision where you did not need it and 1.5 s precision where you did. Second, you no longer choose boundaries, so you no longer get them wrong, and adding a new SLO threshold next quarter does not need a redeploy.
OpenTelemetry’s equivalent is the base-2 exponential bucket histogram. The data model uses the same formula, base = 2^(2^-scale), and a property called perfect subsetting: buckets at scale n merge exactly into buckets at scale n − 1, so two histograms recorded at different scales combine without error by downscaling one. The SDK aggregation defaults to max_size=160 buckets per sign and max_scale=20, and automatically lowers the scale until the observed range fits in 160 buckets. The OTel spec notes that 160 buckets cover 1 ms to 100 s at under 5% relative error. When Prometheus ingests an OTel exponential histogram, either through its OTLP receiver or through the Collector’s Prometheus exporter, it becomes a native histogram, with scales above 8 reduced to schema 8.
PromQL for native histograms drops the le label, because the buckets live inside the sample:
# p99, aggregated across instances: no "by (le)"
histogram_quantile(0.99, sum(rate(http_server_request_duration_seconds{job="payments"}[5m])))
# exact count and mean, and the fraction of requests under 300 ms
histogram_count(sum(rate(http_server_request_duration_seconds{job="payments"}[5m])))
histogram_avg(sum(rate(http_server_request_duration_seconds{job="payments"}[5m])))
histogram_fraction(0, 0.3, sum(rate(http_server_request_duration_seconds{job="payments"}[5m])))
Enabling them depends on the Prometheus version. From v2.40 to v3.7 they sit behind --enable-feature=native-histograms. From v3.8 they are stable and the flag is accepted but, from v3.9, does nothing; you turn ingestion on per scrape job with scrape_native_histograms: true, which defaults to false in v3. Scraping them also needs the protobuf exposition format, and always_scrape_classic_histograms: true keeps the classic _bucket series alongside during a migration. The Prometheus migration advice is to run both for long enough that every dashboard and alert has been ported, then drop the classic ones.
Sketches: DDSketch, t-digest, HdrHistogram
Native histograms are one member of a family of data structures that summarise a distribution in bounded memory. The others show up in vendors’ backends, load testers and languages’ standard libraries, and their error guarantees differ in ways that matter.
| Error guarantee | Mergeable | Memory | Where you meet it | |
|---|---|---|---|---|
| Classic buckets | absolute, one bucket width | yes, if boundaries match | one counter per boundary | Prometheus, OTel default |
| Native / exponential histogram | relative, ~4.3% at schema 3 | yes, by downscaling | sparse, ~160 buckets typical cap | Prometheus, OTel, Mimir |
| DDSketch | relative, α (often 1%) | yes, fully | logarithmic in range | Datadog, OTel collector contrib |
| t-digest | rank error, smallest near the tails | yes, approximately | a few hundred centroids | Elasticsearch percentiles, many databases |
| HdrHistogram | fixed significant digits | yes | fixed, e.g. ~185 KB for 1 µs to 1 h at 3 digits | load testers (wrk2), JVM libraries |
DDSketch (Masson, Rim and Lee, VLDB 2019) is the cleanest guarantee: any quantile it returns is within relative error α of the true value, and two sketches merge into exactly the sketch of the combined data. Its buckets grow by γ = (1 + α)/(1 − α), the same exponential idea as native histograms, and with α = 1% two thousand buckets cover a range of more than 10^17. The paper’s argument against older sketches is the important bit: a guarantee on rank error (the answer is somewhere between the 98.9th and the 99.1st percentile) can be a huge error in value on a long tail, because those two percentiles can be a second apart.
t-digest (Dunning and Ertl) clusters observations into centroids, keeping clusters small near the tails and large near the median, so p99.9 is very accurate and p50 is merely good. It merges well in practice but its bounds are on rank, not value.
HdrHistogram (Gil Tene) records values to a fixed number of significant decimal digits across a fixed range, in fixed memory. It is what you put inside a load generator, where you control the range and want exact-enough numbers with no tuning.
Coordinated omission
All of the above assumes the samples are honest. Gil Tene’s talk “How NOT to Measure Latency” is about the most common way they are not.
Suppose a load tester sends a request, waits for the response, then sends the next one, aiming at 100 requests per second. The server stalls for 1 second. The tester sends one request, waits a second, records one 1-second sample, then carries on. In that second, a real stream of users would have sent 100 requests, and they would have waited 1 s, 0.99 s, 0.98 s and so on down to 10 ms. The tester recorded one slow sample where there should have been 100. Its p99 over a minute (6,000 requests) shows the stall as a single outlier in the top 0.02%. The users’ p99 would have been close to half a second.
The tester coordinated with the server: it backed off exactly when the server was slow, and so omitted the samples that described the slowness. The fix is to measure from when the request should have been sent, not when it was sent. Open-loop generators (wrk2, k6 with constant-arrival-rate executors, Gatling’s open models) do this; HdrHistogram’s recordValueWithExpectedInterval back-fills the missing samples after the fact.
Server-side histograms like the demo app’s are measured from when the request arrived, which is better, but they cannot see requests that a stalled client never sent or a full accept queue never accepted. Two habits help: check the request rate during a latency spike (a dip in rate during a stall is the omission made visible), and keep one open-loop synthetic probe whose latency you trust because it never backs off.
Plant a tail first, so there is something to measure. The queries use http_server_request_duration_seconds, which exists only with the .env from the OpenTelemetry chapter’s lab (OTEL_SDK_DISABLED=false, LOG_FORMAT=json, OTEL_SEMCONV_STABILITY_OPT_IN=http/dup). From labs/observability:
FAULT_SLOW_PAYMENTS_PCT=5 docker compose --profile telemetry up -d paymentsWait five minutes so the 5-minute rate windows below fill with faulted traffic.
1. Compute p99 from the buckets yourself. Save this as p99.py anywhere:
import json, sys, urllib.parse, urllib.request
PROM = "http://localhost:9090/api/v1/query?query="
def q(expr):
with urllib.request.urlopen(PROM + urllib.parse.quote(expr)) as r:
return json.load(r)["data"]["result"]
job = sys.argv[1] if len(sys.argv) > 1 else "payments"
sel = f'http_server_request_duration_seconds_bucket{{job="{job}"}}'
rows = q(f"sum by (le) (rate({sel}[5m]))")
buckets = sorted((float(r["metric"]["le"]), float(r["value"][1])) for r in rows)
total = buckets[-1][1] # +Inf holds every observation
rank = 0.99 * total
prev_le, prev_c = 0.0, 0.0
for le, c in buckets:
print(f" le={le:<7} cumulative={c:8.4f}/s")
for le, c in buckets:
if c >= rank:
if le == float("inf"):
print(f"rank is in +Inf; histogram_quantile reports {prev_le}")
else:
est = prev_le + (le - prev_le) * (rank - prev_c) / (c - prev_c)
print(f"rank {rank:.4f} of {total:.4f} falls in ({prev_le}, {le}] -> p99 ~ {est*1000:.0f} ms")
break
prev_le, prev_c = le, c
print("histogram_quantile:", q(f"histogram_quantile(0.99, sum by (le) (rate({sel}[5m])))")[0]["value"][1])python3 p99.py paymentsle=1.0 and le=2.5 or le=2.5 and le=5.0, where the 5% slow charges land. Your hand-computed p99 and histogram_quantile agree to the millisecond, because you implemented the same linear interpolation. Note how wide the bucket is: the true value could be anywhere from 1 s to 2.5 s (or 2.5 to 5 s), and the slow charges are uniform between 1.5 and 3 s, which the buckets cannot see.2. Average across time and watch it lie. Turn the fault off, wait ten minutes, then compare a 15-minute p99 computed two ways in the Prometheus UI (Graph → Table, or a Grafana Stat panel):
FAULT_SLOW_PAYMENTS_PCT=0 docker compose --profile telemetry up -d payments# A: the average of fifteen 1-minute p99s
avg_over_time(histogram_quantile(0.99, sum by (le) (rate(http_server_request_duration_seconds_bucket{job="payments"}[1m])))[15m:1m])
# B: one p99 over the whole 15 minutes
histogram_quantile(0.99, sum by (le) (rate(http_server_request_duration_seconds_bucket{job="payments"}[15m])))3. Average across hosts. The demo app runs one replica per service, so reproduce the cross-instance case with a model of three hosts. Save as hosts.py:
import random
random.seed(7)
def host(n, slow_pct):
return [random.uniform(1.5, 3.0) if random.random() < slow_pct
else random.lognormvariate(-3.2, 0.5) for _ in range(n)]
def p99(xs): xs = sorted(xs); return xs[int(0.99 * len(xs)) - 1]
hosts = {"a": host(90_000, 0.0), "b": host(9_000, 0.0), "c": host(1_000, 0.08)}
for k, xs in hosts.items(): print(f"host {k}: {len(xs):>6} requests p99 {p99(xs)*1000:6.0f} ms")
print(f"average of p99s: {sum(map(p99, hosts.values()))/3*1000:6.0f} ms")
print(f"true p99: {p99([x for xs in hosts.values() for x in xs])*1000:6.0f} ms")python3 hosts.pyhost a: 90000 requests p99 130 ms, host b: 9000 ... 128 ms, host c: 1000 ... 2782 ms, average of p99s: 1013 ms, true p99: 131 ms: the numbers from the Predict. Change host c to 40,000 requests and re-run: now the average understates the truth. On a real fleet the wrong query is avg(histogram_quantile(0.99, sum by (instance, le) (...))) and the right one drops instance from the by; if you scale a service in your own deployment, run both and compare.4. Move the bucket boundaries. Buckets are cumulative, so dropping some le values from the query is the same as having been recorded with coarser boundaries. First list the le values Prometheus has (Prometheus 3 writes them as floats, 1.0 not 1):
curl -s 'http://localhost:9090/api/v1/label/le/values?match[]=http_server_request_duration_seconds_bucket' | jq -c .dataRe-plant the fault (FAULT_SLOW_PAYMENTS_PCT=5), wait five minutes, and compare three layouts:
# all 15 buckets
histogram_quantile(0.99, sum by (le) (rate(http_server_request_duration_seconds_bucket{job="payments"}[5m])))
# coarse: 0.1, 1, 10, +Inf
histogram_quantile(0.99, sum by (le) (rate(http_server_request_duration_seconds_bucket{job="payments", le=~"0.1|1.0|10.0|\\+Inf"}[5m])))
# coarser still: 1, +Inf
histogram_quantile(0.99, sum by (le) (rate(http_server_request_duration_seconds_bucket{job="payments", le=~"1.0|\\+Inf"}[5m])))1.0 and +Inf, the rank falls in +Inf and the function returns 1, the highest finite bound: it now under-reports. Same data, three answers, all legal. If your le values print as 1 rather than 1.0, adjust the regex.5. Turn on native histograms and compare. Check the Prometheus version:
curl -s http://localhost:9090/api/v1/status/buildinfo | jq -r .data.versionThe lab pins v3.2.1, where native histograms sit behind a feature flag. Add it to the Prometheus command: list in compose.yaml, below the existing --enable-feature=exemplar-storage line (the flag can repeat):
- --enable-feature=native-histogramsand in prometheus/prometheus.yml, under the otel-collector scrape job, keep the classic buckets alongside during the comparison:
always_scrape_classic_histograms: trueWith the flag on, Prometheus 3.2 asks for the protobuf exposition format first, which is what carries native histograms. On v3.8 or later you would instead leave the flag out and set scrape_native_histograms: true on the job; that key does not exist in 3.2 and would stop Prometheus loading its config. Then switch the payments SDK to exponential aggregation by adding to the payments service’s environment: in compose.yaml:
OTEL_EXPORTER_OTLP_METRICS_DEFAULT_HISTOGRAM_AGGREGATION: base2_exponential_bucket_histogramFAULT_SLOW_PAYMENTS_PCT=5 docker compose --profile telemetry up -d prometheus paymentsWait five minutes with the fault still at 5% (the prefix keeps it; without it the recreated payments would fall back to 0), then compare:
histogram_quantile(0.99, sum(rate(http_server_request_duration_seconds{job="payments"}[5m])))
histogram_quantile(0.99, sum by (le) (rate(http_server_request_duration_seconds_bucket{job="orders"}[5m])))
histogram_fraction(0, 0.3, sum(rate(http_server_request_duration_seconds{job="payments"}[5m])))le) returns a p99 inside the real 1.5 to 3 s range, typically within a few percent of the true value, which for uniform slow charges at a 5% fault is about 2.7 s. The orders p99, still classic, is a bucket-interpolated guess in (2.5, 5] or (1, 2.5]. histogram_fraction returns about 0.95, the share of charges under 300 ms, a question the classic buckets cannot answer without a 0.3 boundary. If the first query returns nothing, the payments SDK did not pick up the variable: the Python OTLP exporter reads it in recent versions, and on older ones you set preferred_aggregation on the exporter or a View with ExponentialBucketHistogramAggregation() in code.docker compose pause payments for 20 seconds, then docker compose unpause payments, and look at the gateway’s request rate panel from the RED chapter over that window. An open-loop loadgen keeps sending 5 requests per second into the stall, so the rate holds and 100 requests each show 0 to 20 seconds of latency (or time out). A closed-loop one stops sending, the rate dips, and the stall appears as a handful of slow samples: coordinated omission, on your own dashboard. The lab’s loadgen is open-loop with a cap: it keeps firing at its rate until 64 requests are in flight (LOADGEN_MAX_IN_FLIGHT), then waits, and orders gives up on payments after 10 s. Whichever you see, now you know how much to trust the lab’s p99s. Before the next chapter, undo step 5: remove the aggregation variable from payments, the flag from compose.yaml and the line from prometheus.yml, then run docker compose --profile telemetry up -d prometheus payments. The dashboards chapter assumes classic buckets on all three services.Your fleet's latency dashboard has a 'p99 by host' panel built from a recording rule that stores histogram_quantile(0.99, ...) per instance every minute, and a headline Stat panel showing avg() of that across 60 hosts. Prometheus is v3.9 and the services use the OTel SDK. Product leadership quotes the headline number. What do you change first?
- TALK How NOT to Measure Latency Gil Tene, 2016
The talk that named coordinated omission and showed how load testers and monitoring hide the tail. Watch it all; the first 20 minutes on percentiles and the section on coordinated omission are the parts every engineer should be able to explain.
- PAPER DDSketch: A fast and fully-mergeable quantile sketch with relative-error guarantees Charles Masson, Jee E. Rim, Homin K. Lee, 2019
Published in PVLDB vol. 12. The clearest argument for relative-error quantiles and the design that native histograms and OTel exponential histograms share. Read: the introduction, for why rank-error guarantees fail on long tails, and the description of the sketch and its merge; skip the proofs and the benchmarks on first read.
- DOC Prometheus native histograms specification
The schema formula, the scrape settings (scrape_native_histograms, always_scrape_classic_histograms), the PromQL changes, OTLP mapping, and the migration advice. Long; read the introduction, the schema section and the migration section.
- DOC Histograms and summaries
Prometheus's own guide to choosing between them, why summaries cannot be aggregated, how the bucket layout sets the quantile error, and the Apdex example. Short and exact.
- DOC OpenTelemetry metrics data model: ExponentialHistogram
The base = 2^(2^-scale) formula, the bucket index rule, the zero bucket and perfect subsetting. Read only the ExponentialHistogram section; the rest is the general metric model.
- PAPER Computing Extremely Accurate Quantiles Using t-Digests Ted Dunning, Otmar Ertl, 2019
How t-digest makes the tails accurate by keeping clusters small there, and why its guarantees are on rank rather than value. Read after DDSketch to see the contrast. Read: the introduction and the section describing the scale functions.
- CODE HdrHistogram Gil Tene
The README explains fixed significant-digit recording, the 185 KB footprint for 1 µs to 1 hour at 3 digits, and recordValueWithExpectedInterval, the coordinated-omission correction.
All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.