← Math
Math

Mean, median, variance, and percentiles

Did the canary meet its p95?

Choose a summary that answers the release gate’s latency question.

Outcome

Compute mean, median, spread and nearest-rank percentiles, merge requests before taking a percentile, and refuse to judge a window that is too small.

Terminology (6)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

Mean
The sum divided by the count. One very slow request can move it far from every typical request.
Median
The middle value once sorted, or the mean of the two middles for an even count. Half the values are at or below it.
Standard deviation Also σ
The square root of the average squared distance from the mean. Population form divides by n; sample form by n − 1.
Percentile Also p95, p99
A threshold with at least p percent of observations at or below it; ties may put more there. Nearest rank picks the sorted value at position ⌈p n / 100⌉.
Tail latency
The slow end of the distribution, described by high percentiles rather than the mean.
Minimum window
The minimum observation count a gate’s policy requires before issuing a verdict.

Why this matters

Latency, queue depth, payload size and job duration often have long tails: most values are small and a few are much larger. The few are what users notice and what timeouts hit. An average blends them into a number no request had, and percentiles computed the wrong way can make a good release look bad or a bad one look fine.

This lesson assumes sorting and averages.

Center, spread and rank

The mean divides total latency by the number of requests; the median describes the middle of the sorted observations. Variance measures squared distance from the mean, and its square root, standard deviation, returns to the original unit. These summaries describe different features of the same window.

A percentile identifies a position in sorted observations. This lesson uses nearest rank, which selects an observed value at a specified rank rather than interpolating between neighbors. Its meaning depends on the population, window and count being ranked. A per-host summary and a release-wide summary can answer different questions even when both are labeled p95.

01Mean, median, spread

Mean, median, spread

Two canary hosts report a p95 checkout latency of 400 ms and 30 ms. The dashboard averages them to 215 ms and blocks the release. Only 10 of the 1,100 requests took longer than 30 ms, so the p95 of the release is 30 ms.

Before changing the gate, the team checks what each summary says about individual requests. Ten checkout requests took 12, 15, 11, 13, 240, 14, 12, 16, 13 and 12 ms. Predict the three lines this program prints.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
const latencies = [12, 15, 11, 13, 240, 14, 12, 16, 13, 12]; // ms, one window
const sorted = [...latencies].sort((a, b) => a - b);

const mean = latencies.reduce((sum, x) => sum + x, 0) / latencies.length;

console.log(mean.toFixed(2));
console.log(((sorted[4]! + sorted[5]!) / 2).toFixed(2)); // median of 10 values
console.log(sorted[Math.ceil((95 * sorted.length) / 100) - 1]); // p95, nearest rank
Which number describes a typical request?

For this observed window, variance is the mean squared distance from 35.8 ms: Σ(x − 35.8)² / 10 = 4,635.16 ms². Taking its square root gives the population standard deviation, about 68.1 ms, larger than every request but one. Spread computed around a mean that the tail dragged upward says more about the tail than about typical behavior.

Array.prototype.sort with no comparator compares values as text: [240, 30, 5].sort() gives [240, 30, 5]. Pass (a, b) => a - b, and copy first, because sort reorders the array in place.

02Nearest rank

Nearest rank

The release gate needs to judge slow requests rather than the typical one. The p-th percentile by nearest rank is the value at position ⌈p × n / 100⌉ in sorted order. For the ten requests, p90 is rank 9, 16 ms, and p95 is rank ⌈9.5⌉ = 10, 240 ms. Compute the rank with whole numbers: in floating point 0.07 × 100 is 7.000000000000001, so ceil(p / 100 × n) gives rank 8 where the rule says 7.

A window has 60 requests. Which sorted position is p95?

03Never average percentiles

Never average percentiles

Two canary hosts, p95
Methodp95
Host A alone (100 requests)400 ms
Host B alone (1,000 requests)30 ms
Average of the two215 ms
Average weighted by requests64 ms
Merged requests30 ms

Host A served 90 requests at 20 ms and 10 at 400 ms; host B served 900 at 20 ms and 100 at 30 ms. After merging, ranks 1 through 990 are 20 ms, ranks 991 through 1,090 are 30 ms, and the last 10 are 400 ms. Rank ⌈0.95 × 1,100⌉ = 1,045 therefore lands at 30 ms. A host percentile loses those counts and positions. Merge raw samples for an exact nearest-rank result. Histograms with shared bucket boundaries can also be merged, but their percentile is an estimate at bucket resolution.

04Minimum window

Minimum window

05Name the convention

Name the convention

Nearest rank always returns a value that was observed. Other conventions interpolate between neighbours and can return a value no request had; monitoring systems that work from histograms estimate within a bucket. A gate is only reproducible if it names its population, window, unit and percentile convention.

06Gate the canary

Gate the canary

Repair the canary dashboard before letting its p95 decide a rollout. First summarize an individual window, then implement the stated rank convention, then combine hosts and enforce the minimum count. Fixing the rank alone will not fix an average of host percentiles.

In the frontend Sending raw timings from Next.js and Svelte Optional

The same aggregation rule applies to page dwell time, a different metric from request latency. These hooks measure a mounted route interval. A p95 computed in one tab cannot be merged with any other. Send each raw timing with sendBeacon and let the server rank the merged samples. The Svelte effect reads and captures the route before returning its cleanup, so a route change starts a new interval. Framework development checks may invoke extra setup/cleanup cycles; production telemetry needs its own deduplication and missing-sample policy.

Estimate.tsx
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
"use client";

import { useEffect } from "react";

// Send raw timings, not a percentile: the server merges samples from every page view.
export function useCheckoutTiming(route: string) {
  useEffect(() => {
    const started = performance.now();

    return () => {
      const body = JSON.stringify({
        route,
        ms: Math.round(performance.now() - started)
      });
      navigator.sendBeacon("/api/timings", body);
    };
  }, [route]);
}

Check this idea later
A gate needs 100 requests and the canary served 40, all fast. What should it report?
Each region reports its hourly p99. Can the global p99 be found from those numbers alone?
Sources

Values above were run in Node 22, Go 1.27, Rust 1.99 and Apple clang 17. The canary hosts are a worked model.

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.