Learning center

Why an average of per-host p99s is not the fleet's p99

A fleet p99 that looks fine while users report slow requests is either right, or an average of per-host p99s that hides one slow host. Count the share of all requests slower than the panel's p99: if the panel shows the fleet's p99, about 1% are slower. Then compute the quantile from merged histogram buckets with histogram_quantile over sum by (le), and compare.

The symptom and two explanations#

The example is fictional. The search-api service runs on eight hosts, and its latency objective is a p99 under 250 ms. On the dashboard, "fleet p99" reads 161 ms. Since 10:00 UTC, support has collected complaints about searches that take a third of a second or more, and the traces people pasted into the incident channel agree with them.

  • The fleet is fine. The p99 excludes the slowest 1% of requests by definition, and the complaints come from that 1%, or from somewhere outside the service.
  • The panel is wrong. Its query is avg(http_request_duration_seconds{quantile="0.99"}): the mean of eight per-host p99s from a summary metric. Host search-7 holds a hot shard, takes 30% of all requests, and is three times slower than the others. In the mean it counts as one host in eight.

Prometheus's own documentation calls averaging precomputed quantiles from summaries "statistically nonsensical", because a summary's quantiles cannot be aggregated, while a histogram's bucket counts can be summed across instances and the quantile computed afterward. Histograms and summaries Choose the observation where explanations disagree

What each explanation predicts#

ObservationThe fleet is fineThe average hides a slow host
Panel: mean of per-host p99sbelow 250 msbelow 250 ms
Share of all requests slower than the panel's valueabout 1%well above 1%
histogram_quantile over buckets summed across hostsclose to the panelwell above the panel
Per-host p99 beside per-host request ratesimilar across hostsone host slow, with a large share of requests

The panel separates nothing. The second row is a test of the panel itself: a p99 is the value 99% of requests stay under, so if the panel shows the fleet's p99, about 1% of the fleet's requests are slower than it. The third row reads the fleet's p99 directly, and the fourth names the host.

The lab: three fleets#

The script builds eight hosts' request latencies in three fleets: all hosts alike, one slow host with three times the traffic of each other host, and one slow host with very little traffic. For each fleet it prints the per-host p99s, their plain and request-weighted averages, the true p99 of all requests, the estimate histogram_quantile would make from summed buckets, and the share of requests slower than the averaged p99. It needs Python 3.8 or later.

import math, random, statistics, sys

seed = int(sys.argv[1]) if len(sys.argv) > 1 else 5
BUCKETS = [0.025, 0.05, 0.075, 0.1, 0.15, 0.2, 0.3, 0.4, 0.6, 1.0, 2.5, float("inf")]  # seconds

def p99(xs):
    return statistics.quantiles(xs, n=100, method="inclusive")[98]

def histogram_quantile(q, counts):          # Prometheus-style linear interpolation
    rank, lower, below = q * counts[-1], 0.0, 0
    for le, cum in zip(BUCKETS, counts):
        if cum >= rank:
            if math.isinf(le):
                return lower
            return lower + (le - lower) * (rank - below) / (cum - below)
        lower, below = le, cum

def fleet(name, hosts):                     # hosts: (requests, median seconds)
    rng = random.Random(seed)
    per_host = [[rng.lognormvariate(0, 0.5) * med for _ in range(n)] for n, med in hosts]
    every = [x for xs in per_host for x in xs]
    host_p99 = [p99(xs) for xs in per_host]
    merged = [sum(x <= le for x in every) for le in BUCKETS]   # sum by (le)
    avg = statistics.mean(host_p99)
    weighted = sum(v * len(xs) for v, xs in zip(host_p99, per_host)) / len(every)
    print(f"{name}: per-host p99 ms {[round(v * 1000) for v in host_p99]}")
    print(f"  average of p99s {avg * 1000:4.0f} ms   weighted by requests {weighted * 1000:4.0f} ms")
    print(f"  true fleet p99  {p99(every) * 1000:4.0f} ms   histogram_quantile   {histogram_quantile(0.99, merged) * 1000:4.0f} ms")
    print(f"  requests slower than the averaged p99: {sum(x > avg for x in every) / len(every):.1%}")

fleet("identical", [(3000, 0.040)] * 8)
fleet("one slow, busy", [(3000, 0.040)] * 7 + [(9000, 0.120)])
fleet("one slow, quiet", [(3000, 0.040)] * 7 + [(150, 0.400)])

Save it as pctl.py. Before running it, write down for each fleet whether the averaged p99 will be above, near or below the true fleet p99, and roughly what share of requests will be slower than it. Python 3.11 printed:

identical: per-host p99 ms [134, 120, 119, 136, 137, 131, 126, 128]
  average of p99s  129 ms   weighted by requests  129 ms
  true fleet p99   128 ms   histogram_quantile    139 ms
  requests slower than the averaged p99: 1.0%
one slow, busy: per-host p99 ms [134, 120, 119, 136, 137, 131, 126, 384]
  average of p99s  161 ms   weighted by requests  205 ms
  true fleet p99   294 ms   histogram_quantile    298 ms
  requests slower than the averaged p99: 8.3%
one slow, quiet: per-host p99 ms [134, 120, 119, 136, 137, 131, 126, 1529]
  average of p99s  304 ms   weighted by requests  139 ms
  true fleet p99   158 ms   histogram_quantile    161 ms
  requests slower than the averaged p99: 0.5%

When the hosts are alike, every method agrees within the histogram's bucket resolution, which is how the averaging can go unnoticed for a long time. With one busy slow host, the panel's 161 ms sat under the objective while the fleet's real p99 was 294 ms and 8.3% of requests were slower than the panel's value. Weighting by request count moved the average closer and still missed by 89 ms. With one quiet slow host, the error flipped direction: the plain average reported 304 ms for a fleet whose p99 was 158 ms. In every fleet, the quantile from summed buckets stayed within a bucket's width of the truth.

The prediction fails if the share slower than the averaged p99 stays near 1% in the busy fleet, or if histogram_quantile lands farther from the true p99 than the averages do. Run python3 pctl.py 9 to repeat with other draws, and change the busy host's 9000 or 0.120 to see how the gap depends on its share of traffic and its slowness.

Read it on a real system#

With classic Prometheus histograms, sum the bucket rates across instances, keeping le, and take the quantile of the sum. Then take it per instance, beside each instance's request rate. These queries only read. histogram_quantile

histogram_quantile(0.99,
  sum by (le) (rate(http_request_duration_seconds_bucket{job="search-api"}[5m])))

histogram_quantile(0.99,
  sum by (instance, le) (rate(http_request_duration_seconds_bucket{job="search-api"}[5m])))

sum by (instance) (rate(http_request_duration_seconds_count{job="search-api"}[5m]))

The share of requests slower than a threshold comes from one bucket boundary. With a bucket at 0.25 seconds, this is the fraction slower than the objective, and it needs no quantile estimate at all. The same document uses this form for objectives such as "95% of requests within 300 ms". Histograms and summaries

1 - sum(rate(http_request_duration_seconds_bucket{job="search-api", le="0.25"}[5m]))
  / sum(rate(http_request_duration_seconds_count{job="search-api"}[5m]))

With native histograms, histogram_quantile(0.99, sum(rate(http_request_duration_seconds{job="search-api"}[5m]))) aggregates without a by (le) clause, and histogram_fraction returns the share between two values. histogram_fraction

If the service exports only summaries, the fleet quantile cannot be recovered from them. Read each instance's quantile beside its _count rate to find the slow host, and use _sum divided by _count for a mean, which does aggregate. Load balancer latency metrics that are stored as distributions, such as Google Cloud's total_latencies, keep the distribution across backends, so their percentiles are computed over all requests. Cloud Load Balancing metrics

Limits#

histogram_quantile estimates. It assumes observations spread evenly within a classic bucket, so its answer can be off by up to a bucket's width; in the lab's alike fleet it read 139 ms against a true 128 ms. Buckets that are coarse around the objective give a coarse answer, and a quantile that falls in the +Inf bucket returns the upper bound of the second-highest bucket. histogram_quantile

A correct fleet p99 can still hide a slow host whose traffic is under 1% of the fleet's, as in the quiet fleet. Its users wait while every fleet-wide number looks normal; split by host, or by the tenant or shard the slow host serves, to find them. One customer slow, dashboards fine

The same mistake happens over time. A daily p99 computed as the average of 1,440 one-minute p99s weights a quiet minute the same as a busy one. Compute it from the day's summed buckets instead.

Questions#

Can I average p99s if every host gets the same traffic?

Only when the hosts also have similar latency distributions, which is the case where averaging was harmless anyway. Equal traffic does not fix a host that is slower than the rest. Change the busy host's 9000 to 3000 in the lab and the average reads 161 ms against a true fleet p99 of 242 ms, with 3.6% of requests slower than the average.

Is the maximum of per-host p99s the fleet's p99?

It is an upper bound on it, because every host keeps 99% of its requests under its own p99 and so under the largest one. It can be far above the fleet's value, though: in the quiet fleet the worst host's p99 was 1,529 ms against a fleet p99 of 158 ms, because that host served under 1% of the requests. Read it as the worst host, which is useful in its own right.

Should I use summaries or histograms for latency?

Use histograms when you need a quantile across instances, which is almost always for a replicated service. A summary computes accurate quantiles inside each process, but they cannot be combined afterward, and you cannot choose a different quantile or window later. Histograms and summaries

One month of free code review.

New organizations get one calendar month of hosted code review for private and public GitHub repositories. No card or cloud connection required. Eligibility and fair-use terms.

Start free with GitHub

Related reading