AlgoViz

Latency

easy 30 min

Latency is how long one request takes.

See it run

Where the milliseconds of one request go, how to describe many requests, and what makes the slow ones slow.

Operations

Follow one request

The same request there and back, with a running clock.

Step 1 of 6

Tap

Our system20 msPhone2 msLoad balancer1 msApp server15 msDatabase10 ms
Time so far, of 71 ms
2 ms

The phone needs 2 ms to build the request.

Step 1: Tap

way_in = 2 + 20 + 1work = 15 + 10way_back = 1 + 20 + 2total = way_in + work + way_back   # 71 ms
Answers
Where does the time go?
You leave with
A budget

Only the travel happens twice. The work happens once.

In the real world

The same latency doing real jobs. Pick one and step through it.

P50 is 40 ms and calm. P99 jumped to 2 seconds after Tuesday's release.

Step 1 of 4

Look at both

MondayTuesday
P5040 ms40 ms
P99180 ms2,000 ms
Average45 ms64 ms

The average hardly moved, so nobody noticed. P99 did.

Step 1: Look at both

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Reporting the average

    critical

    One request in ten can be 41 times slower and the average still looks good.

    Wrong
    print(sum(v) / len(v))      # 50 ms
    Right
    print(percentile(v, 50), percentile(v, 99))  # 10, 410
  • Calling in a row for no reason

    major

    Independent calls add up when they could overlap.

    Wrong
    p = await profile(u)     # 30 mso = await orders(u)      # 50 ms, 80 in all
    Right
    p, o = await gather(profile(u), orders(u))  # 50 ms
  • Averaging percentiles

    major

    Percentiles of parts do not give the percentile of the whole.

    Wrong
    p99 = mean(s.p99 for s in servers)
    Right
    total = add_buckets(s.histogram for s in servers)p99 = percentile_of(total, 99)
  • Waiting without a limit

    critical

    One stuck dependency holds threads and connections until everything waits.

    Wrong
    requests.get(url)
    Right
    requests.get(url, timeout=(0.5, 1))  # connect, read

Interview tips

  • How to explain it

    • How long one request takes.
    • Network, queue, work, disk.
    • Say it as P50, P95, P99.
  • Memory trick: LATENCY

    • Lower is better. Always measure. Tail matters.
    • Edge caching. Network is slow when long.
    • Cache what is read often. Your users feel it.
  • Cut it by

    • Fewer and shorter trips.
    • Parallel calls, kept connections.
    • Background work, indexes, caches.
  • Watch out

    • Doubling the work in a round trip.
    • Queues near 100%.
    • Tests that wait for answers.