TExcelTAD

Histograms & Quantiles

"The average latency is 40 ms" hides the users who wait 2 seconds. Latency is described with percentiles (quantiles): p50 is the median, p99 the value 99% of requests beat. Prometheus computes them from histogram buckets with histogram_quantile().

The standard queries

promql
# p99 latency of the whole service over the last 5 minutes
histogram_quantile(0.99, sum by (le) (rate(http_request_duration_seconds_bucket{job="linkly"}[5m])))

# p99 per route: keep `le` and the label you group by
histogram_quantile(0.99, sum by (route, le) (rate(http_request_duration_seconds_bucket{job="linkly"}[5m])))

# average latency
sum(rate(http_request_duration_seconds_sum[5m])) / sum(rate(http_request_duration_seconds_count[5m]))

# fraction of requests faster than 250 ms (an SLI: needs a bucket at exactly 0.25)
sum(rate(http_request_duration_seconds_bucket{le="0.25"}[5m])) / sum(rate(http_request_duration_seconds_count[5m]))

The pattern is always: rate() the buckets, sum by (le, …) (never drop le, it's what holds the distribution), then histogram_quantile.

On real data

The session backfills linkly's latency histogram: each second, 10 requests arrive; 7 finish within 50 ms, 2 more within 100 ms, and one is slow (between 0.25 and 0.5 s):

bash · try it yourself
python3 - > data.om <<'PY'
start = 1767225600
cumulative_per_sec = {"0.05": 7, "0.1": 9, "0.25": 9, "0.5": 10, "1": 10, "+Inf": 10}
print("# TYPE http_request_duration_seconds histogram")
for i in range(121):
    t = start + 15 * i
    for le, r in cumulative_per_sec.items():
        print(f'http_request_duration_seconds_bucket{{job="linkly",le="{le}"}} {r * 15 * i} {t}')
    print(f'http_request_duration_seconds_sum{{job="linkly"}} {0.62 * 15 * i:.2f} {t}')
    print(f'http_request_duration_seconds_count{{job="linkly"}} {10 * 15 * i} {t}')
print("# EOF")
PY
promtool tsdb create-blocks-from openmetrics data.om data >/dev/null
echo "global: {}" > prometheus.yml
prometheus --config.file=prometheus.yml --storage.tsdb.path=data --storage.tsdb.retention.time=100y \
  --web.listen-address=127.0.0.1:9090 >prom.log 2>&1 &
for i in $(seq 100); do curl -sf 127.0.0.1:9090/-/ready >/dev/null && break; sleep 0.2; done
q() { printf '%-6s ' "$1"; promtool query instant --time=2026-01-01T00:20:00Z http://127.0.0.1:9090 "$2" |
      sed 's/.*=> //; s/ @\[.*//' | awk '{ printf "%.4g\n", $1 }'; }
B='sum by (le) (rate(http_request_duration_seconds_bucket[5m]))'
q p50  "histogram_quantile(0.50, $B)"
q p90  "histogram_quantile(0.90, $B)"
q p95  "histogram_quantile(0.95, $B)"
q p99  "histogram_quantile(0.99, $B)"
q avg  'sum(rate(http_request_duration_seconds_sum[5m])) / sum(rate(http_request_duration_seconds_count[5m]))'
q fast 'sum(rate(http_request_duration_seconds_bucket{le="0.25"}[5m])) / sum(rate(http_request_duration_seconds_count[5m]))'
p50    0.03571
p90    0.1
p95    0.375
p99    0.475
avg    0.062
fast   0.9
  • p50 is about 36 ms: the median falls in the first bucket (0–50 ms), and Prometheus assumes observations are spread evenly inside a bucket, so it interpolates linearly.
  • p95 and p99 land in the 0.25–0.5 s bucket: the slow tenth of requests.
  • The average (62 ms) says nothing about that slow tenth. Graph p50, p90 and p99 together, or a heatmap of the buckets.
  • 90% of requests finish within 250 ms; as an SLI that number is exact, because 0.25 is a bucket boundary. Quantiles are estimates; "fraction under a threshold" is not.

How good is the estimate?

histogram_quantile finds the bucket containing the requested rank, then interpolates linearly between the bucket's lower and upper bound. The error depends entirely on where your bucket boundaries are. This model computes the true p99 of 10,000 simulated latencies and the estimate from two bucket layouts:

python · try it yourself
import random

random.seed(42)
# 96% fast requests around 30 ms, 4% slow ones around 250 ms (cache misses hitting PostgreSQL)
lat = [random.lognormvariate(-3.5, 0.4) if random.random() < 0.96 else random.lognormvariate(-1.4, 0.3)
       for _ in range(10000)]

def true_quantile(xs, q):
    s = sorted(xs)
    return s[int(q * (len(s) - 1))]

def histogram_quantile(q, bounds, xs):
    """Prometheus's algorithm on classic buckets (cumulative counts, +Inf last)."""
    counts = [sum(1 for x in xs if x <= b) for b in bounds] + [len(xs)]
    rank = q * counts[-1]
    for i, c in enumerate(counts):
        if c >= rank:
            break
    if i == len(bounds):                 # rank falls in +Inf: return the highest finite bound
        return bounds[-1]
    lower = 0.0 if i == 0 else bounds[i - 1]
    below = 0 if i == 0 else counts[i - 1]
    return lower + (bounds[i] - lower) * (rank - below) / (counts[i] - below)

default = [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10]   # client_golang's DefBuckets
tuned = [0.02, 0.03, 0.04, 0.05, 0.075, 0.1, 0.2, 0.3, 0.4, 0.5, 0.75, 1]
for q in (0.5, 0.9, 0.99):
    print(f"p{int(q * 100):<3} true {true_quantile(lat, q) * 1000:6.1f} ms   "
          f"default buckets {histogram_quantile(q, default, lat) * 1000:6.1f} ms   "
          f"tuned buckets {histogram_quantile(q, tuned, lat) * 1000:6.1f} ms")
print("observations above 1 s:", sum(x > 1 for x in lat))
p50  true   30.9 ms   default buckets   33.8 ms   tuned buckets   31.1 ms
p90  true   55.4 ms   default buckets   69.3 ms   tuned buckets   60.7 ms
p99  true  296.8 ms   default buckets  365.9 ms   tuned buckets  298.3 ms
observations above 1 s: 0

With the library defaults, the p99 lands in the wide 0.25–0.5 s bucket and the linear interpolation overestimates it by about 70 ms (23%); p90 is off by 25%. Buckets placed around the latencies you care about (and around your SLO threshold) get within a few milliseconds. Rules of thumb:

  • Put a boundary exactly at your SLO threshold (e.g. 0.3 s) so the SLI is exact.
  • 10–15 buckets cover most services; more buckets multiply series by every label combination (Labels & Cardinality).
  • If the rank lands in the +Inf bucket, histogram_quantile returns the highest finite boundary: a p99 that sits flat at "1 s" may really be 30 s. Keep a bucket well above your timeout.
  • Changing buckets changes series; keep them stable, or use native histograms.

Native histograms

Native histograms (stable in Prometheus 3, scraped with the protobuf format; enable with scrape_native_histograms: true on the job, and in client_golang with NativeHistogramBucketFactor) store exponential buckets automatically in one series with a few dozen populated buckets, at a configurable resolution. Queries get simpler, without _bucket and le:

promql
histogram_quantile(0.99, sum(rate(http_request_duration_seconds[5m])))
histogram_fraction(0, 0.25, sum(rate(http_request_duration_seconds[5m])))   # fraction under 250 ms
histogram_count(rate(http_request_duration_seconds[5m]))                   # requests per second

They fix most of the bucket-layout problems above. Check that every consumer (Grafana panels, remote storage, recording rules) supports them before switching a busy service.

Test yourself

Which label must survive the sum by (...) before histogram_quantile?

  1. instance
  2. le
  3. code
  4. job

Why is "fraction of requests under 250 ms" a better SLI than "p99 < 250 ms" with classic histograms?

  1. It is cheaper
  2. With a bucket boundary at 0.25 it is exact, while quantiles are interpolated estimates
  3. p99 cannot be alerted on
  4. It needs no buckets

A p99 graph sits perfectly flat at 10 s, your largest finite bucket. What does it mean?

  1. Latency is exactly 10 s
  2. The p99 rank falls in the +Inf bucket: real latency is above 10 s, by an unknown amount
  3. Prometheus is down
  4. The histogram has no data