5. Latency vs Throughput
5.8 How do you reduce latency?
Making it better
On the highway: Four ways to get there sooner. Don't make the trip (have it delivered, or keep one at home). Take fewer trips (buy everything in one go). Live closer. And avoid rush hour, when the road is jammed.
In the system: The same four ideas.
- Skip the work: caching (Chapter 12), precomputing results, serving static content from a CDN (Chapter 26).
- Fewer round trips, and in parallel: batch several small calls into one; make independent calls at the same time rather than one after another; reuse connections (Chapter 3); add the right database index so one query replaces a scan (Chapter 9).
- Move closer: servers or CDN edges near users; keep services that talk a lot in the same data centre.
- Keep servers out of rush hour: latency explodes as a server gets busy, because requests start queueing.
Figure: a server that needs 10 ms per request answers in 20 ms at 50% busy, 100 ms at 90% and 1,000 ms at 99%.
That last curve comes from basic queueing maths: for a simple server with random arrivals, average time in the system = 1 ÷ (service rate − arrival rate). With 10 ms of work per request (100 per second possible), 90 requests a second gives 1 ÷ (100 − 90) = 0.1 s = 100 ms, ten times the work itself. Real systems differ in detail, but the shape is always the same: flat, then a cliff. That's why teams keep servers well below full (Chapter 2, section 2.11).
Also: move slow work off the request path. Sending the order email, updating recommendations or resizing images can go on a queue and happen after the response (Chapter 22).
Memory code: "Skip it, batch it, move closer, avoid rush hour."