Skip to content
LeetQuant
QD09 Testing, Profiling and Debugging

QD09 · Testing, Profiling and Debugging · Lesson 5 of 5

Latency Analysis

Report latency as percentiles, understand tail latency and fan-out, store distributions in HDR-style histograms, avoid coordinated omission, and timestamp a trading pipeline stage by stage.

17 min

Objective

In trading, the latency that loses money is in the tail: the order that went out 300 µs late during a burst is the one that got picked off. By the end of this lesson you should be able to compute and interpret percentiles, explain why the mean misleads, describe how latency histograms are stored and merged, and recognise coordinated omission in a load test.

Percentiles, not means

The p-th percentile is the value below which (about) p% of samples fall. The nearest-rank definition on nn sorted samples x(1)≤⋯≤x(n)x_{(1)} \le \dots \le x_{(n)} is

Pp=x(k),k=⌈p100 n⌉.\text{P}_p = x_{(k)}, \qquad k = \left\lceil \frac{p}{100}\, n \right\rceil .

Libraries differ (NumPy interpolates between ranks by default), which matters for small samples, so state the definition when you report numbers.

Latency distributions are right-skewed with rare large values (cache misses, page faults, GC pauses, context switches, retransmits). The mean mixes typical behaviour with the tail and describes neither. Report p50 (typical), p99 and p99.9 (tail) and the maximum, together with the sample count: a p99.9 from 2,000 samples rests on just two observations.

Why the tail dominates

If a task fans out to mm independent calls and waits for all of them, it is slow whenever any one of them is slow. The probability that at least one of 100 calls exceeds its own p99 is

1−0.99100≈0.634.1 - 0.99^{100} \approx 0.634 .

So for the parent task, the components' p99 is roughly the median experience. Similarly a strategy that sends 1,000 orders a day will see the p99.9 of its order path about once a day.

Percentiles also do not add: the p99 of a two-stage pipeline is not the sum of the stage p99s. For two independent exponential stages with mean 1, each stage has p99=ln⁡100≈4.61\text{p99} = \ln 100 \approx 4.61, but the sum has p99 ≈6.64\approx 6.64, not 9.219.21, because both stages are rarely slow together. Measure end to end; do not compose percentiles.

Storing distributions: HDR-style histograms

Storing every sample is too expensive at millions of events per second, and averaging percentiles across hosts or minutes is wrong (the mean of two p99s is not the p99 of the union). The standard answer is a histogram with logarithmically spaced buckets and bounded relative error, the idea behind HdrHistogram:

  • Buckets are linear within each power of two (or of ten), so every recorded value is within a fixed relative precision, for example 1%.
  • The size is small and fixed: covering 1 ns to 1 s at 1% relative precision needs about ln⁡(109)/ln⁡(1.01)≈2083\ln(10^{9}) / \ln(1.01) \approx 2083 geometric buckets, a few kilobytes of counters.
  • Recording is an index computation and an increment, cheap enough for the hot path (often into a per-thread histogram).
  • Histograms merge exactly by adding counts, so per-thread, per-host and per-minute histograms combine into correct global percentiles.

Coordinated omission

A load generator that sends the next request only after the previous reply (a closed loop) stops sending while the system is stalled. During a 200 ms stall it records one slow sample instead of the 200 requests that a real market (which keeps sending at its own pace) would have queued. The measurement system has "coordinated" with the system under test to omit exactly the bad samples. The correction is to measure each request from its intended send time, or to use an open-loop generator that sends on schedule regardless of replies.

Timestamping a pipeline

Tick-to-trade latency is split into stages, each bracketed by timestamps taken on the same clock:

PointTypical source
packet arrives at the NIChardware timestamp from the NIC, or a network capture appliance
feed message decodedsoftware timestamp (TSC read or clock_gettime)
book updated, signal computedsoftware timestamps
order handed to the NICsoftware timestamp; hardware TX timestamp if available
order on the wirecapture appliance on a tap or switch mirror

Practical points: use a monotonic clock (CLOCK_MONOTONIC, std::chrono::steady_clock, or the invariant TSC via rdtsc at a few nanoseconds per read) and never the wall clock, which can jump. Compare timestamps from different machines only if their clocks are synchronised (PTP gives sub-microsecond accuracy), otherwise differences carry the clock offset. Record timestamps into a preallocated buffer and write them out off the hot path; logging in the hot path changes the latency you are measuring. Then build a histogram per stage and one end to end.

Worked example

nearest-rank percentiles by hand

Twenty order round-trip times in microseconds, already sorted:

12, 13, 13, 14, 14, 14, 15, 15, 15, 16, 16, 17, 18, 18, 19, 21, 24, 30, 55, 410.

Compute the mean, p50, p90, p95 and p99 with the nearest-rank rule, and say which numbers belong in a report.

Show solution

Mean. The sum is 769, so the mean is 769/20=38.45769 / 20 = 38.45 µs. It is larger than 18 of the 20 samples: the single 410 µs outlier adds 410/20=20.5410/20 = 20.5 µs to it on its own.

Percentiles, with k=⌈pn/100⌉k = \lceil p n / 100 \rceil and n=20n = 20:

PercentilekkValue
p50⌈10⌉=10\lceil 10 \rceil = 1016 µs
p90⌈18⌉=18\lceil 18 \rceil = 1830 µs
p95⌈19⌉=19\lceil 19 \rceil = 1955 µs
p99⌈19.8⌉=20\lceil 19.8 \rceil = 20410 µs

Interpretation. The typical round trip is 16 µs; one in ten is at least 30 µs. With only 20 samples, p99 is simply the maximum, so it is not an estimate of the true p99 at all; quoting a p99 needs at least several hundred samples, and p99.9 several thousand. A report would give p50 and p90 here, the maximum, and n=20n = 20, and would investigate the 410 µs sample (a page fault, a retransmit, a GC pause in a downstream service?) rather than averaging it away.

Worked example

percentiles and coordinated omission in a simulation

A load generator intends to send one request per millisecond for 10 seconds. Service time is 0.05 ms plus an exponential with mean 0.1 ms, except for a single 200 ms stall halfway through. The generator is closed-loop: it cannot send while waiting for a reply. Compute mean, p50, p99, p99.9 and max of latency measured from the actual send time and from the intended send time.

Show solution
import math
import random
import statistics

def percentile(sorted_xs, p):
    """Nearest-rank percentile: smallest value with at least p% of samples at or below it."""
    k = max(1, math.ceil(p / 100 * len(sorted_xs)))
    return sorted_xs[k - 1]

def report(name, xs):
    xs = sorted(xs)
    print(f"{name:22s} n={len(xs):>6,}  mean {statistics.fmean(xs):7.3f}  "
          + "  ".join(f"p{p:g} {percentile(xs, p):7.3f}" for p in (50, 99, 99.9))
          + f"  max {xs[-1]:7.3f}  (ms)")

random.seed(7)
interval = 1.0                       # load generator intends one request per ms
service = [0.05 + random.expovariate(1 / 0.1) for _ in range(10_000)]
service[5_000] = 200.0               # one 200 ms stall (GC pause, page fault storm, ...)

naive, corrected = [], []
free_at = 0.0                        # when the server finishes its current request
for i, s in enumerate(service):
    intended = i * interval
    sent = max(intended, free_at)    # a closed-loop client cannot send while waiting
    free_at = sent + s
    naive.append(free_at - sent)          # timer starts when the request is actually sent
    corrected.append(free_at - intended)  # timer starts when it should have been sent

report("service time (naive)", naive)
report("from intended send", corrected)

Output:

service time (naive)   n=10,000  mean   0.170  p50   0.119  p99   0.513  p99.9   0.691  max 200.000  (ms)
from intended send     n=10,000  mean   2.523  p50   0.121  p99 116.356  p99.9 192.484  max 200.000  (ms)

Checking the numbers.

  • Naive mean. The average service time is 0.05+0.1=0.150.05 + 0.1 = 0.15 ms, and the stall adds 200/10,000=0.02200 / 10{,}000 = 0.02 ms: 0.17 ms, as printed.
  • Corrected mean. About 200 requests were scheduled during the stall and each waited for its remainder, roughly 200,199,…,1200, 199, \dots, 1 ms, which totals about 200×201/2≈20,100200 \times 201 / 2 \approx 20{,}100 ms. Spread over 10,000 requests that adds about 2.0 ms, giving the printed 2.52 ms.
  • Percentiles. The naive view says p99 = 0.51 ms: the stall is a single sample, below the p99.9 rank of 10, so it is invisible except in the maximum. Measured from the intended time, about 2% of requests were delayed, so p99 lands inside the stall at 116 ms and p99.9 at 192 ms.
  • p50 barely moves (0.119 versus 0.121 ms): the median says nothing about the tail.

The naive report is what a closed-loop benchmark would publish; the corrected one is what a client sending at the market's pace would experience.

Knowledge check

Two servers report p99 latencies of 1.0 ms and 3.0 ms over the same minute, with equal request counts. What is the p99 across both?

Knowledge check

A request fans out to 50 independent back-end calls and waits for all of them. Each call exceeds 2 ms with probability 1%. What fraction of requests exceed 2 ms?

Knowledge check

A benchmark client sends a request, waits for the reply, records the elapsed time, then sends the next. During a 1-second stall in the server, what goes wrong with the measured percentiles?

Key takeaways

  • Report p50, p99, p99.9 and max with the sample count; the mean hides the tail and the median ignores it.
  • Fan-out turns component tails into common experience: 1−0.99m1 - 0.99^{m} of requests hit at least one p99 call.
  • Percentiles neither average nor add; keep log-bucketed (HDR-style) histograms, which merge exactly.
  • Measure from the intended send time to avoid coordinated omission.
  • Timestamp each pipeline stage on a monotonic, synchronised clock into preallocated buffers, and build per-stage and end-to-end histograms.

Practice problems

Finished reading?

Answer the 3 knowledge checks to complete this lesson (0 done).