← Learning guides

Worked tutorial · about 35 minutes

Calculate latency percentiles and combine windows correctly

Work out p50, p90 and p95 from twenty invented response durations, name the interpolation convention, and check why averaging percentiles gives the wrong pooled answer.

Original editorial exercise · fictional practice data · checked 25 October 2026

Your task is to produce a reproducible latency summary from two small windows. The durations are invented, in milliseconds, and represent completed responses. There are no timeouts, omitted responses or live benchmark runs. You can calculate on paper and use the offline Python checker afterward.

1. Download and sort the observations

Raw invented durations, before sorting
WindowCountMilliseconds
A8140, 100, 900, 120, 160, 110, 150, 130
B12170, 110, 190, 140, 210, 100, 160, 120, 200, 130, 180, 150

Sort each window from smallest to largest, keeping repeated observations. Then make a separate pooled list containing every observation from both windows. A repeated duration represents another response and stays in the list.

2. Fix the percentile convention

This exercise uses Type 7 linear interpolation. For sorted observations with zero-based indices, calculate h = (n − 1) × p, where p is 0.50, 0.90 or 0.95. Let j be floor(h) and g be h − j. Interpolate between observations j and j + 1; at the last observation, use that observation for both endpoints.

h = (n - 1) * p
j = floor(h)
g = h - j
Q(p) = x[j] + g * (x[min(j + 1, n - 1)] - x[j])

The official R quantile reference documents multiple conventions, including Type 7's interpolation positions. A percentile report needs its convention because another valid method can give another value on this small dataset.

  1. Calculate each window's count, mean, p50, p90 and p95. Keep intermediate positions exact.
  2. For window A's p95, show h, the two neighboring durations and the interpolation weight.
  3. Calculate the same statistics from the pooled raw list. Then compare pooled p95 with both the ordinary and count-weighted mean of the two window p95 values.

3. Compare the worked calculations

Show the results and the pooled p95 calculation
Type 7 results, all durations in milliseconds
ObservationsnMeanp50p90p95Maximum
A8226.25135.00382.00641.00900
B12155.00155.00199.00204.50210
Pooled20183.50145.00201.00244.50900

Window A: h = 7 × 0.95 = 6.65. At zero-based indices 6 and 7, the durations are 160 and 900. Its p95 is 160 + 0.65 × (900 − 160) = 641.00 ms.

Pooled: h = 19 × 0.95 = 18.05. The durations at indices 18 and 19 are 210 and 900. Its p95 is 210 + 0.05 × 690 = 244.50 ms. The interpolated value need not be an observed duration.

The ordinary mean of window p95 values is (641 + 204.5) ÷ 2 = 422.75 ms. Weighting by counts gives (8 × 641 + 12 × 204.5) ÷ 20 = 379.10 ms. Neither reconstructs pooled p95. Percentiles retain a position in each distribution, so these two summaries do not preserve the combined ordering.

4. Run the checker and test sensitivity

Save all four downloads in one folder. Use Python 3.10 or later, with no packages:

python calculate_percentiles.py latencies.json
python calculate_percentiles.py latencies.json --check answer_key.json

The checker sorts the raw lists and computes the declared formula using decimal arithmetic. It prints its results and exits with status 0 when the supplied answer key matches. It does not time your computer or contact a server.

Show the complete checker
"""Type-7 quantiles for invented durations. Python 3.10+, standard library only."""
import argparse
import json
from decimal import Decimal, ROUND_FLOOR, ROUND_HALF_UP
from pathlib import Path

D = Decimal


def display(value):
    return str(value.quantize(D("0.01"), rounding=ROUND_HALF_UP))


def percentile(sorted_values, p):
    if not sorted_values or not D(0) <= p <= D(1):
        raise ValueError("Require nonempty observations and a probability in [0, 1]")
    h = D(len(sorted_values) - 1) * p
    j = int(h.to_integral_value(rounding=ROUND_FLOOR))
    g = h - j
    low, high = D(sorted_values[j]), D(sorted_values[min(j + 1, len(sorted_values) - 1)])
    return low + g * (high - low)


def summarize(values):
    if not values or any(type(value) is not int or value < 0 for value in values):
        raise ValueError("This exercise requires nonempty, nonnegative integer durations")
    ordered = sorted(values)
    return {"n": len(ordered), "sorted_ms": ordered, "mean_ms": display(D(sum(ordered)) / len(ordered)),
            "p50_ms": display(percentile(ordered, D("0.50"))),
            "p90_ms": display(percentile(ordered, D("0.90"))),
            "p95_ms": display(percentile(ordered, D("0.95"))), "max_ms": ordered[-1]}


def calculate(data):
    windows, all_values, p95_values = [], [], []
    for window in data["windows"]:
        values = window["durations_ms"]
        summary = summarize(values)
        windows.append({"name": window["name"], **summary})
        all_values.extend(values)
        p95_values.append((len(values), percentile(sorted(values), D("0.95"))))
    if not windows:
        raise ValueError("At least one window is required")
    unweighted = sum(value for _, value in p95_values) / len(p95_values)
    weighted = sum(D(count) * value for count, value in p95_values) / len(all_values)
    return {"convention": "Type 7", "unit": "milliseconds", "windows": windows,
            "pooled": summarize(all_values), "unweighted_mean_of_window_p95_ms": display(unweighted),
            "count_weighted_mean_of_window_p95_ms": display(weighted)}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("input", type=Path)
    parser.add_argument("--check", type=Path)
    args = parser.parse_args()
    result = calculate(json.loads(args.input.read_text(encoding="utf-8")))
    print(json.dumps(result, indent=2))
    if args.check and result != json.loads(args.check.read_text(encoding="utf-8")):
        parser.exit(1, "Answer mismatch: compare the printed values with your answer.\n")


if __name__ == "__main__":
    main()

In a copy, replace the single 900-ms observation with 220, then predict the new pooled p50, p95 and maximum. Run the checker without --check answer_key.json, because the original answer key describes the unchanged dataset.

Show the sensitivity answer

Pooled p50 stays 145.00 ms. Pooled p95 becomes 210 + 0.05 × (220 − 210) = 210.50 ms, and the maximum becomes 220 ms. One observation moved the upper-tail summary substantially while leaving the middle unchanged.

5. Write a report with its denominator

A complete report is: “Across these 20 invented completed responses, Type 7 p95 is 244.50 ms and the maximum is 900 ms.” The result describes this list. It provides no measured reliability, timeout rate or future service guarantee. If real requests time out or disappear from a log, account for them explicitly before using a completed-response summary to describe all requests.

For a different calculation involving a resource limit, try the fictional token budget. To practice bounded attempts, continue to the retry-budget simulation.

Sources and scope

The observations, tasks and answer key are original fictional practice material. The R reference supports the Type 7 convention and the existence of alternative definitions. Source checked 25 October 2026.