Skip to content
Coding · 8 min

Percentiles without lying

p99 is the number SREs quote most and compute wrong most often. This lesson covers the nearest-rank definition you should implement in an interview, why you cannot average percentiles, and the streaming sketches a Senior answer mentions.

Nearest rank

def pct(vals, q):
    # vals sorted ascending; nearest-rank percentile
    i = max(0, -(-q * len(vals) // 100) - 1)   # ceil(q·n/100) − 1
    return vals[i]

Nearest rank picks the smallest value such that at least q% of samples are at or below it. It needs no interpolation, works for one sample (p50 = p99 = that sample) and is what most monitoring systems mean. State the definition before you implement it; interviewers care that you chose one deliberately.

You cannot average percentiles

The p99 of two hosts is not the mean of their p99s, and the p99 of a day is not the mean of 1,440 one-minute p99s. To combine, you need the underlying samples or a mergeable sketch. If a design has per-host percentiles rolled up by averaging, say so: it is a common and real bug.

Linked exercise · needs a computer · 10 minParse and bucket latency logsRead it here, do it on a computer

Windows and late data

Fixed windows are floor(ts / w) × w. The boundary test (a sample at :59 and one at :00) catches off-by-one errors and is the one to write first. Late data is the follow-up: if lines can arrive 30 s late, a window cannot be finalised until 30 s after it closes, and you need a policy for anything later than that (drop and count, or reopen).

Sketches

Sorting every bucket is O(n log k) and holds every sample in memory. At 10⁶ lines that is fine; at 10⁹ it is not. t-digest and HDR histogram give bounded memory and mergeable results with a stated accuracy; mentioning one and its trade-off (relative error at the tails, fixed value range) is what separates a Solid from a Strong Complexity score.