Report p50, p95 and p99 latency with the nearest-rank method
Service dashboards and SLOs quote tail latency, not averages: one slow request in a hundred is what users notice. Different tools compute percentiles differently, so a team picks one definition and sticks to it.
Write latency_percentiles(samples_ms, ps=(50, 95, 99)).
- Drop samples that are negative (failed requests are logged as -1).
- Nearest-rank percentile: sort the n remaining values; rank = ceil(p / 100 * n), at least 1; the answer is the rank-th smallest value (1-based).
- Return a dict like {"p50": ..., "p95": ..., "p99": ...} with one key per p (key "p" + str(p)), values as floats. If no valid samples remain, every value is 0.0.
def latency_percentiles(samples_ms, ps=(50, 95, 99))Example
[10, 20, 30, 40] gives p50 = 20 (rank 2), p95 = 40 (rank ceil(3.8) = 4), p99 = 40.
Understand the idea
Dashboards quote tail latency, such as p95 and p99, because the slow requests are what users notice. The nearest-rank method always returns a value that really appeared in the data, which makes it easy to explain in an incident review. Failed requests logged as -1 must be dropped first. Worked example: samples [5, 1, 9, 3, -1, 7]. Drop -1 and sort: [1, 3, 5, 7, 9], n = 5. p50: rank = ceil(0.5 * 5) = ceil(2.5) = 3, so the 3rd smallest = 5. p95: rank = ceil(4.75) = 5, value 9. p99: rank = ceil(4.95) = 5, value 9. p20 would give rank ceil(1.0) = 1, value 1. Rule: keep samples >= 0, sort, rank = ceil(p / 100 * n) with a minimum of 1, answer = sorted[rank - 1] as a float; key names are 'p' plus the number, such as 'p95'; if nothing is left, every value is 0.0. A default numpy percentile interpolates between neighbours, giving values no request ever had. Used in SLO reports for model serving APIs.