Part 01 · Thinking About Scale

Latency Numbers for Design

MemorySSDNetworkCross-region

The handful of latency numbers you need to judge a design, recapped from the OS and Networking courses.

⏱ 9 min · Station 7 of 93

The problem

Someone proposes moving the shop's database to a cheaper cloud region, "it's only a little farther away". Someone else wants to replace a Redis lookup with an in-memory map, "to save time". Is either change worth it? You can't answer without knowing roughly what each operation costs: a memory lookup, a network round trip, a database query, a disk sync, a trip across a continent.

You don't need exact numbers. You need the right order of magnitude, because the operations in a request differ by factors of a thousand or a million, and a design that ignores that is wrong by the same factor.

The idea

A few numbers every backend engineer carries in their head. We measured the first ones on the lab laptop; the last ones come from the speed of light.

OperationRoughlyOrder of magnitude
Read from memory (a map lookup)50 to 100 nsnanoseconds
Read a cached 4 KB page from the OSabout 1 µsmicrosecond
Network round trip inside one data center (Redis GET, SELECT 1)40 µs to 0.5 mstens to hundreds of µs
A simple indexed database query0.1 to 1 mssub-millisecond
Write + fsync to an SSD1 to 5 msmilliseconds
Round trip to another city in the region10 to 40 mstens of ms
Round trip to another continent100 to 250 mshundreds of ms

The OS course covers why memory and disk cost what they do; the Networking course covers why round trips cost what they do. For design, two rules come out of this table:

  1. Network round trips dominate. Inside a data center a round trip costs as much as hundreds of memory reads. Across a continent, millions.
  2. Round trips in sequence add up. A page that makes 3 database calls one after another pays the round trip 3 times. 50 calls (an N+1 query bug) pay it 50 times.

How it works

Light in optical fiber travels about 200,000 km per second, so every 1,000 km of distance adds at least 5 ms each way, 10 ms per round trip, before any router or server does anything. Dhaka to Singapore is about 2,900 km in a straight line: at least 29 ms per round trip. Dhaka to the US East coast, about 13,000 km: at least 130 ms. Real routes are longer than straight lines and add router hops, so real numbers are higher.

Now apply that to the product page. It runs three queries one after another, each one a round trip to PostgreSQL:

app ──► db  product          ◄── 1 round trip
app ──► db  rating           ◄── 1 round trip
app ──► db  also bought      ◄── 1 round trip
page time ≈ 3 × round trip + query work + app work

With the database next to the app, a round trip is about 0.05 ms and query work dominates: the page takes under 2 ms. Move the database 30 ms away, and the round trips dominate: about 3 × 30 = 90 ms of pure waiting, on every page, no matter how fast the queries are.

Predict first

The product page takes 1.7 ms. You add 30 ms of delay to every packet the database sends. How long does the page take now?

Visual

map lookup in memory57 nsread 4 KB, cached file0.6 µsRedis GET, same network42 µsPostgreSQL SELECT 144 µsfull product page1.7 mswrite 4 KB + fsync2.3 msDhaka - Singapore, at least≥ 29 msDhaka - US East, at least≥ 130 msmeasured on the labpage, db 30 ms awayproduct ~31 msrating ~31 msalso bought ~31 ms= 99 mseach step to the right is roughly 10 times slowerthree queries, one after another: the round trip is paid three times
Measured costs on the lab, on a log scale: each step right is about 10 times slower. Below: the product page with the database 30 ms away pays the round trip three times.

Common misconception

"Replacing Redis with an in-memory map will make the page much faster." The Redis lookup costs about 40 µs; the whole page costs about 1,700 µs. Removing the round trip saves 2%. Speed up the part that costs the most (here, one query), not the one that's easiest to change.

"It's only a little farther away." A database that's 30 ms away instead of 0.05 ms is 600 times farther in time. Any page that makes several queries in sequence pays that many times over. Keep the things that talk often close together, and when you can't, reduce the number of round trips (batch queries, one query instead of three).

Try it

Measured on the lab (Intel i3-10110U, 4 threads, 7 GB RAM, a SATA SSD; everything in Docker on one machine).

tools/latency/main.go times each operation many times from inside the lab network and prints p50 and p99:

// Command latency measures the operations a request is made of, on this machine, from inside the
// lab network. Each operation runs many times; we print the median (p50) and p99.
package main

import (
	"context"
	"crypto/rand"
	"fmt"
	"io"
	"net/http"
	"os"
	"sort"
	"time"

	"github.com/jackc/pgx/v5"
	"github.com/redis/go-redis/v9"
)

// human prints a duration with three significant digits: 55 ns, 38.7 µs, 2.22 ms.
func human(d time.Duration) string {
	switch {
	case d < time.Microsecond:
		return fmt.Sprintf("%d ns", d.Nanoseconds())
	case d < time.Millisecond:
		return fmt.Sprintf("%.1f µs", float64(d.Nanoseconds())/1e3)
	default:
		return fmt.Sprintf("%.2f ms", float64(d.Nanoseconds())/1e6)
	}
}

func measure(name string, n int, op func()) { measureEach(name, n, 1, op) }

// measureEach times op n times; each op does `per` operations, and we report time per operation.
func measureEach(name string, n, per int, op func()) {
	d := make([]time.Duration, n)
	for i := range d {
		t := time.Now()
		op()
		d[i] = time.Since(t)
	}
	sort.Slice(d, func(a, b int) bool { return d[a] < d[b] })
	p50, p99 := d[n/2]/time.Duration(per), d[n*99/100]/time.Duration(per)
	fmt.Printf("%-36s %10s %10s\n", name, human(p50), human(p99))
}

func main() {
	ctx := context.Background()
	fmt.Printf("%-36s %10s %10s\n", "operation", "p50", "p99")

	m := map[int]int{}
	for i := 0; i < 1_000_000; i++ {
		m[i] = i
	}
	k := 0
	measureEach("map lookup, in memory", 2000, 1000, func() {
		for i := 0; i < 1000; i++ {
			k += m[(k+i*7919)%1_000_000]
		}
	})

	buf := make([]byte, 1<<20)
	rand.Read(buf)
	os.WriteFile("/tmp/f", buf, 0o644)
	f, _ := os.Open("/tmp/f")
	page := make([]byte, 4096)
	measure("read 4 KB from a cached file", 2000, func() { f.ReadAt(page, 4096*int64(k%200)) })

	w, _ := os.OpenFile("/tmp/w", os.O_CREATE|os.O_WRONLY, 0o644)
	measure("write 4 KB + fsync (SSD)", 200, func() { w.WriteAt(page, 0); w.Sync() })

	rdb := redis.NewClient(&redis.Options{Addr: "redis:6379"})
	rdb.Set(ctx, "k", "v", 0)
	measure("Redis GET (network round trip)", 2000, func() { rdb.Get(ctx, "k") })

	db, err := pgx.Connect(ctx, "postgres://shop:shop@db:5432/shop")
	if err != nil {
		panic(err)
	}
	var one int
	measure("PostgreSQL SELECT 1", 2000, func() { db.QueryRow(ctx, "SELECT 1").Scan(&one) })
	var name string
	measure("PostgreSQL product by id", 2000, func() {
		db.QueryRow(ctx, "SELECT name FROM products WHERE id = $1", 1+k%20000).Scan(&name)
	})
	measure("PostgreSQL 'also bought' query", 500, func() {
		rows, _ := db.Query(ctx, "SELECT id FROM products WHERE category = $1 ORDER BY sold DESC LIMIT 8", k%50)
		for rows.Next() {
		}
		rows.Close()
	})

	get := func(url string) { r, err := http.Get(url); if err == nil { io.Copy(io.Discard, r.Body); r.Body.Close() } }
	measure("HTTP GET /health (shop)", 2000, func() { get("http://api:8080/health") })
	measure("HTTP GET /products/{id} (full page)", 1000, func() { get(fmt.Sprintf("http://api:8080/products/%d", 1+k%20000)); k++ })
}
operation                                   p50        p99
map lookup, in memory                     57 ns     136 ns
read 4 KB from a cached file             615 ns     858 ns
write 4 KB + fsync (SSD)                2.27 ms    4.39 ms
Redis GET (network round trip)          41.7 µs   192.9 µs
PostgreSQL SELECT 1                     43.5 µs    71.7 µs
PostgreSQL product by id                64.0 µs   107.3 µs
PostgreSQL 'also bought' query         950.5 µs    1.99 ms
HTTP GET /health (shop)                 57.2 µs   178.4 µs
HTTP GET /products/{id} (full page)     1.71 ms    3.98 ms

Reading it:

  • A memory read: 57 ns. A cached file read: 0.6 µs, ten times more.
  • Any network round trip, even to a container on the same machine: about 40 µs (Redis GET, SELECT 1). That's 700 memory reads.
  • The "also bought" query: 0.95 ms, mostly CPU inside PostgreSQL. That's the bottleneck from two lessons ago.
  • A full product page: 1.7 ms, three queries plus the app's work.
  • An fsync to the SSD: 2.3 ms, longer than the whole product page. Every committed write pays something like this, which is why databases group commits.

Now put the database "far away" with netem.sh, which adds a delay to every packet a container sends (it uses Linux tc netem; the Distributed Systems course uses it a lot):

#!/bin/sh
# Add network delay or loss to everything a container sends, or remove it.
#   ./netem.sh db delay 30ms        ./netem.sh db loss 5%        ./netem.sh db off
c=syslab-$1-1; shift
if [ "$1" = off ]; then
  docker run --rm --net container:$c --cap-add NET_ADMIN syslab-tc qdisc del dev eth0 root 2>/dev/null || true
else
  docker run --rm --net container:$c --cap-add NET_ADMIN syslab-tc qdisc replace dev eth0 root netem "$@"
fi
operation                                   p50        p99
PostgreSQL SELECT 1                    30.62 ms   32.33 ms
PostgreSQL product by id               30.87 ms   31.90 ms
PostgreSQL 'also bought' query         34.86 ms   40.14 ms
HTTP GET /products/{id} (full page)    99.08 ms  103.41 ms
  • Every query now costs about 30.6 ms regardless of what it does: SELECT 1 and the product lookup take the same time.
  • The product page: 99 ms, 58 times slower, without any change to code or queries. Three sequential round trips, each paying 30 ms.

Trade-offs

  • Co-locate chatty components. App servers and their database belong in the same data center (ideally the same zone). Cross-region is for disaster recovery and users far away, with designs that avoid many round trips.
  • Fewer round trips beat faster round trips. One query that joins three tables usually beats three simple queries; one batch request beats fifty single ones. You can't beat the speed of light, but you can stop paying it repeatedly.
  • Put the data near the users, not just the servers. For a user in Dhaka, a server in Singapore costs at least 29 ms per round trip and one in Virginia at least 130 ms. CDNs (Part 4) exist for this.
  • Numbers drift with hardware: NVMe disks sync faster than SATA, cloud networks add a little over a laptop's. Re-measure on the real thing before a big decision; the orders of magnitude stay the same.

Key takeaway

Memory is nanoseconds, a network round trip tens of microseconds in a data center and tens to hundreds of milliseconds across regions, a disk sync milliseconds. Round trips in sequence add up, so the number of round trips and the distance they cover usually matter more than how fast your code is.

Practice

Objective: estimate before measuring, using round trips.

Challenge: the page makes 3 queries. Suppose someone "optimizes" it into 8 smaller queries (one per related product instead of one query for all 8 related ones). Estimate the page time with the database next to the app (round trip ~0.05 ms) and 30 ms away. Then check your 30 ms estimate against the measured 99 ms for 3 queries.

Expected result: two estimates, and a sentence about which one makes the change unacceptable.

Hint 1

How many round trips does the new page make in total?

Hint 2

Page time ≈ round trips × round-trip time + work. The work is about 1.7 ms either way.

Hint 3

Use the measured 3-query case to check your model: (99 − 1.7) / 3 ≈ 32 ms per round trip.

Solution

The new page makes 2 + 8 = 10 round trips.

  • Database close (0.05 ms): 10 × 0.05 = 0.5 ms of round trips, plus about 1.7 ms of work: about 2.2 ms. Barely different from today.
  • Database 30 ms away: 10 × 32 ms ≈ 320 ms, plus the work. More than three times today's already slow 99 ms.

The same "harmless" change costs 0.5 ms in one setup and over 200 ms in another. That's why round trip counts belong in design reviews, and why an N+1 query that's invisible in a laptop test can wreck a page in production, where the database is a network hop away.

Interview check

Q: A page makes 40 database queries and takes 900 ms in production but 30 ms on a developer's laptop. What's your first guess?

Model answer

Round trips. On the laptop the database is local, so each query's round trip is microseconds. In production the database is a network hop away, maybe a few ms, maybe farther: 40 sequential round trips at ~20 ms each is 800 ms of waiting. I'd confirm with a trace or by counting queries per request, then cut the number of round trips: batch the queries, use a join or IN (...), or cache, rather than tuning each query.

Q: Users in Dhaka complain the app is slow. The servers are in US East. Where does the time go, at minimum?

Model answer

Physics first: about 13,000 km each way means at least 130 ms per round trip, more on real routes. A new HTTPS connection needs several round trips (TCP handshake, TLS) before the first byte, and a page often needs more requests after that, so a full page load can easily spend over a second just traveling. Fixes: serve static content from a CDN near the users, keep connections alive, reduce the number of sequential requests, and if it matters enough, run servers in a nearby region.

Station stamp

Finish the chapter

Done reading? Press Complete to save your progress. XP is Pro-only — on Pro this chapter is worth +10 XP.

Go Pro to earn XP →