Latency Numbers
Good designs come from a feel for how long things take. Reading from memory, reading from an SSD, calling another service in the same data centre and sending a packet across an ocean differ by factors of thousands. If you know the orders of magnitude, you can predict which part of a request dominates its latency before you measure anything.
The table every engineer should know
These are approximate figures for modern hardware. Exact values change every few years; the ratios are what matter.
| Operation | Approx. time | In nanoseconds |
|---|---|---|
| L1 cache reference | 1 ns | 1 |
| Branch mispredict | 3 ns | 3 |
| L2 cache reference | 4 ns | 4 |
| Mutex lock/unlock | 20 ns | 20 |
| Main memory reference | 100 ns | 100 |
| Compress 1 KB (fast codec) | 2 µs | 2,000 |
| Read 1 MB sequentially from memory | 10 µs | 10,000 |
| Random read from NVMe SSD (4 KB) | 20 µs | 20,000 |
| Round trip inside one data centre | 500 µs | 500,000 |
| Read 1 MB sequentially from SSD | 1 ms | 1,000,000 |
| Disk (HDD) seek | 10 ms | 10,000,000 |
| Read 1 MB sequentially from HDD | 5 ms | 5,000,000 |
| Round trip Europe ↔ US East | 80 ms | 80,000,000 |
| Round trip Europe ↔ Australia | 250 ms | 250,000,000 |
Making the numbers human
Nanoseconds are hard to feel. A classic trick is to scale everything up so that one L1 cache hit takes one second:
operations = [
("L1 cache reference", 1),
("main memory reference", 100),
("SSD 4 KB read", 20_000),
("same-datacentre round trip", 500_000),
("HDD seek", 10_000_000),
("Europe <-> US round trip", 80_000_000),
]
def humanize(seconds):
for unit, size in [("years", 31_536_000), ("days", 86_400), ("hours", 3_600), ("minutes", 60)]:
if seconds >= size:
return f"{seconds / size:.1f} {unit}"
return f"{seconds:.0f} second(s)"
for name, ns in operations:
print(f"{name:<28} {humanize(ns):>12}")L1 cache reference 1 second(s)
main memory reference 1.7 minutes
SSD 4 KB read 5.6 hours
same-datacentre round trip 5.8 days
HDD seek 115.7 days
Europe <-> US round trip 2.5 years
If a memory read is a coffee break of under two minutes, a trip across the Atlantic is more than two and a half years. That is why you avoid network round trips inside loops, and why caches sit as close to the user as possible.
Budgeting a request
A request's latency is the sum of the steps on its critical path. Writing it down as a budget shows where the time goes:
steps_ms = {
"TLS + HTTP from user (1 RTT, nearby CDN)": 20,
"load balancer": 0.5,
"auth service call": 2,
"cache lookup (hit)": 0.5,
"database query (cache miss)": 5,
"render response": 3,
}
total = sum(steps_ms.values())
for step, ms in sorted(steps_ms.items(), key=lambda kv: -kv[1]):
bar = "#" * round(ms / total * 40)
print(f"{step:<42} {ms:5.1f} ms {bar}")
print(f"{'total':<42} {total:5.1f} ms")TLS + HTTP from user (1 RTT, nearby CDN) 20.0 ms ##########################
database query (cache miss) 5.0 ms ######
render response 3.0 ms ####
auth service call 2.0 ms ###
load balancer 0.5 ms #
cache lookup (hit) 0.5 ms #
total 31.0 ms
The network hop from the user dominates, which is why CDNs and edge locations are so effective. The next biggest item is the database query, which is what caches remove.
Sequential vs parallel calls
When a request needs data from several services, calling them one after another adds up their latencies; calling them in parallel costs only the slowest one. The same applies to N calls inside a loop, the "N+1 query" problem.
calls_ms = {"profile": 12, "friends": 18, "recommendations": 35, "ads": 22}
sequential = sum(calls_ms.values())
parallel = max(calls_ms.values())
print(f"sequential: {sequential} ms")
print(f"parallel: {parallel} ms (limited by the slowest call)")
# N+1: one query for 50 posts, then one query per post for its author
round_trip_ms = 0.5
print(f"N+1 queries for 50 posts: {(1 + 50) * round_trip_ms:.1f} ms of round trips")
print(f"one batched query: {2 * round_trip_ms:.1f} ms of round trips")sequential: 87 ms
parallel: 35 ms (limited by the slowest call)
N+1 queries for 50 posts: 25.5 ms of round trips
one batched query: 1.0 ms of round trips
Throughput from latency
Latency also limits throughput when work is done one at a time. A single connection that waits for each 80 ms round trip can make at most 12.5 requests per second, no matter how fast the server is. More concurrent connections, batching or pipelining fix that (see Latency vs Throughput).
rtt_ms = 80
for in_flight in [1, 10, 100]:
print(f"{in_flight:3} request(s) in flight -> max {in_flight * 1000 / rtt_ms:7.1f} requests/s") 1 request(s) in flight -> max 12.5 requests/s
10 request(s) in flight -> max 125.0 requests/s
100 request(s) in flight -> max 1250.0 requests/s
Tip: The speed of light in fibre is about 200,000 km/s, so every 1,000 km of distance adds about 10 ms to a round trip. No amount of engineering beats physics: put data near users.
Test yourself
Which operation is slowest?
- Main memory reference
- SSD random read
- Round trip within one data centre
- Round trip between continents
Four independent service calls take 10, 20, 30 and 40 ms. How long do they take when issued in parallel?
- 10 ms
- 25 ms
- 40 ms
- 100 ms
What is the N+1 query problem?
- A database with N+1 replicas
- Making one query for a list and then one more query per item
- Running N+1 servers for redundancy
- An off-by-one error in pagination