One Postgres box answers about 4,000 reads a second. Put a CDN, an app cache and three replicas in front of it, and 500,000 reads a second leave only 2,000 for the database.
Add one layer at a time, then drag the traffic. Watch how many reads reach the database and how busy it gets. Then we build each layer, piece by piece: the queue, replicas, pools, the edge cache, the app cache, invalidation and precomputed feeds.
You need to know what a database query is and a little Python. We build the rest from zero.
An illustrative feed app. One box has 8 cores at 2 ms per read, so it finishes 4,000 reads a second. The 99% app-cache and 60% CDN hit rates are made-up numbers that the whole lesson uses. Latency comes from the queue model of Chapter 0.
Chapter 0
Count the reads that arrive, count what one box can finish, and see why the gap is a wall and not a slope
It is 2:14 in the afternoon. Feed pages that loaded in 12 ms now take 400 ms. Nothing crashed and nobody deployed. The database is up. It is slow.
You run the read path of a feed app, and every read goes to one Postgres server. How many reads arrive? The app has 12 million daily users. Each one makes about 18 reads a day, and the evening peak runs at about twice the daily average.
Now the box. It has 8 CPU cores, and a typical read uses 2 ms of CPU. One core finishes 1,000 / 2 = 500 reads a second, so 8 cores finish 4,000. Call the arrival rate λ (lambda) and the finishing rate μ (mu). Their ratio ρ (rho) is the busy share of the box, from 0 to 1.
How long does one read take as ρ grows? Picture each core as its own checkout line, with reads sent to a line at random. Call the CPU time of one read s, and the average time a read spends in the box, waiting plus working, W.
W equals s divided by one minus rho, where rho is lambda over mu.
Find the idle share of the box, one minus rho. Divide the work time s by it. Half idle doubles s. A tenth idle multiplies it by ten.
At 3,600 reads a second, ρ = 3,600 / 4,000 = 0.9. So W = 2 / 0.1 = 20 ms. At 3,960, ρ = 0.99 and W = 200 ms. Ten percent more traffic made each read ten times slower.
The curve is the time per read. Drag the traffic toward 4,000 and past it.
The model treats each core as its own line (M/M/1). One shared line for all 8 cores is faster below the wall, about 26 ms at ρ = 0.99, but it hits the same wall at ρ = 1.
Past 4,000, more reads arrive than leave. The line grows by λ − μ reads every second, without end. At 5,000 that is 1,000 more waiting reads each second.
The failure. Symptom: latency climbs for 20 minutes while the error rate stays near zero. Measure: graph ρ, the 99th percentile latency beside the median, and active connections. Fix now: shed load, such as prefetches and background refreshes, until ρ falls under 1.
A bigger box helps for a while: 32 cores finish 16,000 a second. Next year's goal is 500,000, which no single server reaches. Every later layer does one of three things: copy the box, send reads around it, or answer without it.
Chapter 1
Copy the box to multiply reads, then count how far behind each copy runs and route around it
The cheapest fix for one busy box is more boxes with the same data. A read replica is a second server that copies every change from the first and answers reads. The leader takes all writes. The replicas, also called followers, take reads.
Postgres does not resend your SQL. It streams the write-ahead log (WAL), the journal of changes the leader already keeps for crash recovery. Each follower replays it on its own copy. Say shipping takes 20 ms and replay 25 ms: about 50 ms of replication lag.
How many writes is a follower missing right now? Call the arrival rate λ, the time each item spends inside W, and the average number inside L.
L equals lambda times W.
Multiply how fast items arrive, lambda, by how long each one stays, W. The product L is how many are inside now. This is Little's law, and it holds for any stable line.
With made-up numbers: λ = 2,000 writes a second and W = 0.05 s, so L = 100 writes the follower has not replayed. In Chapter 0, 3,960 × 0.2 s = 792 reads sat inside the box.
Purple trails blue by the lag. Pick a routing rule, then press Save and reload. Push writes past 3,000 a second to see replay fall behind.
Illustrative: 50 ms base lag, a replay ceiling of 3,000 writes a second, and a reload 20 ms after the save.
Replay has its own wall. In core Postgres, one startup process replays the WAL on a standby. Say it replays at most 3,000 writes a second. A burst of 8,000 gives replay a ρ of 2.7, and the backlog grows by 5,000 writes a second.
Lag causes a classic bug. A user saves a new photo, the page reloads, and the read lands on a follower that has not replayed the save. The user needs read-your-writes: you always see your own changes.
| Rule | How | Cost |
|---|---|---|
| Pin to leader | After a write, send that user's reads to the leader for 2 s. | Extra leader load. |
| LSN check | After commit, keep pg_current_wal_lsn(). Read from a follower whose pg_last_wal_replay_lsn() has reached it, else the leader. | One check per read. |
| Synchronous | synchronous_commit = remote_apply: the commit waits until the standby applies it. | Every write waits for replay. |
Size the fleet: 5,000 / 4,000 = 1.25, so 2 replicas. If one fails, the survivor is back at the wall, so run 3: 12,000 a second, and 8,000 after any one fails.
The failure. Symptom: "I saved it, but it did not change." Measure: graph replay_lag from pg_stat_replication on the leader. Fix: route the user's next read by LSN.
Chapter 2
Count the queries that run at once, and hold thousands of clients on a small pool
Your app fleet holds 10,000 open connections to the database. Postgres runs one operating-system process for each connection. Say each one costs about 10 MB. That is 100 GB of memory before any query runs.
Most connections sit idle. Each client runs a 2 ms query, then spends about 500 ms on other work. How many queries run at one moment? Little's law answers again.
Forty queries do the real work. A connection pooler such as PgBouncer holds the 10,000 cheap client connections and a small pool of real server connections. It lends a server connection for one transaction, then takes it back.
Warm slots run a query. Pink dots wait for a slot. Change the clients, their think time and the pool size.
Illustrative: 2 ms per query and 10 MB per server connection. Real memory per connection depends on settings such as work_mem.
Leave room for bursts: 40 × 2.5 = 100 server connections, about 1 GB instead of 100 GB. If think time drops to 150 ms, about 132 queries run at once, so even 100 slots can queue for a moment.
The pool is a line too. A pool of 30 against 40 in flight gives ρ = 1.33, and requests wait for a free slot without end.
| PgBouncer mode | Server connection returns | Watch out for |
|---|---|---|
| session | when the client disconnects | one backend per client: the pool saves nothing |
| transaction | when a transaction ends | SET and advisory locks do not follow the client |
| statement | after each statement | no multi-statement transactions |
Transaction mode is the usual choice. Pass the tenant as a query parameter instead of SET search_path, because the next transaction can land on another backend.
The failure. Symptom: Postgres refuses connections with "too many clients" while CPU sits at 15%. Measure: SHOW POOLS in PgBouncer; a lasting nonzero cl_waiting means the pool is too small. Fix: a transaction pool sized by Little's law, plus a statement timeout.
Chapter 3
Answer the reads that are the same for everyone from a server near the reader
Some reads are the same for everyone: a post's thumbnail, the trending list, the JavaScript bundle. A CDN (content delivery network) keeps copies in many points of presence (PoPs) near users. A hit there never reaches your servers. Your origin says what the CDN may keep with HTTP headers.
| Header | What it tells the caches |
|---|---|
max-age=60 | fresh for 60 s |
s-maxage=3600 | shared caches (the CDN) keep it 3,600 s; browsers ignore it |
stale-while-revalidate=30 | serve the old copy up to 30 s more while fetching a new one |
private / no-store | only the browser may keep it / no cache may keep it |
Vary: Accept-Language | this request header joins the cache key |
The cache key decides which requests count as the same. Too narrow, and a Japanese reader gets the English page. Too wide, such as a key with the session cookie, and every request misses. Put every input the response depends on in the key, and nothing else.
A hit near the user also removes distance. Light in fiber travels about 200,000 km a second, and a round trip covers the distance twice. Call the distance to the server d, in km, and the shortest possible round trip RTTmin, in ms.
RTT-min equals d divided by one hundred.
Take the distance d in kilometres and divide by 100. No reply can come back faster, in milliseconds.
Tokyo to northern Virginia is about 10,900 km, so at least 109 ms. A new HTTPS connection needs about 3 round trips: TCP, TLS 1.3 and the request. That is at least 327 ms. A PoP 50 km away: 0.5 ms a trip.
Drag the distance, or pick a preset. The pulse makes one round trip at the speed of light in fiber.
Physics floor only. Real paths are longer than great circles and add routing and processing time on top.
Hundreds of PoPs can each miss on one popular item. An origin shield is one more cache layer between the PoPs and your origin. AWS documents that CloudFront Origin Shield consolidates requests for the same object, down to as few as one origin request.
The failure. Symptom: some readers see the trending page in the wrong language. Measure: log the CDN cache key for two requests that should differ. Fix: add the language to the key, or send Vary: Accept-Language.
Accept-Language. What breaks?Chapter 4
See one expired key turn into hundreds of identical queries, and let one request rebuild it for all
Many reads are costly to compute and shared for a short time, such as the trending list. They live in an app cache, usually Redis or Memcached, between the app servers and the database. The common pattern is cache-aside: read the cache; on a miss, query the database and write the result back.
pythondef get_trending(redis, db): cached = redis.get("trending:global") if cached is not None: return cached # hit: no database result = db.compute_trending() # miss: about 40 ms of real work redis.set("trending:global", result, ex=60) return result
The trouble comes when a hot key expires. Every request that arrives during the rebuild also finds the key empty, and each one queries the database. Call the read rate of the key r and the rebuild time t.
N-miss equals r times t.
Multiply how often the key is read, r, by how long the rebuild takes, t. That many requests miss, and each one runs the same query.
With made-up numbers: r = 8,000 a second and t = 0.040 s, so N-miss = 320 copies of the same 40 ms query at once. This is a thundering herd, also called a cache stampede.
Each dot is a request in the rebuild window. Warm dots query the database; pink dots wait. Press Expire, then turn on the lock.
Illustrative arrivals, evenly spaced. Above 160 dots the canvas draws a sample and the read-out gives the full count.
The fix is single-flight: one request rebuilds, the rest wait and reuse its result. Redis documents a simple lock: SET key token NX EX seconds sets the key only if it is absent. Delete it only if it still holds your token, so you never free another request's lock.
pythontoken = uuid4().hex if redis.set("lock:trending", token, nx=True, ex=1): # only one caller wins try: result = db.compute_trending() redis.set("trending:global", result, ex=60) finally: release(keys=["lock:trending"], args=[token]) # Lua: del only if value == token else: result = wait_for("trending:global", timeout=0.1) or db.compute_trending()
Facebook's memcache paper (NSDI 2013) does this with a lease. On a miss, a server hands out at most one token per key every 10 seconds. Other clients get told to wait briefly. On keys prone to herds, the peak database query rate fell from 17,000 to 1,300 a second.
The failure. Symptom: database CPU spikes every 60 seconds, in step with a TTL. Measure: misses per key per second around each expiry. Fix: single-flight, with a lock expiry above the slowest rebuild, not the average.
Chapter 5
Size the database from the reads the cache misses, and see why the last nines matter most
How big must the database tier be behind a cache? Call the total read traffic T, in reads a second. Call the hit rate h: the share of reads the cache answers. The misses go to the origin, the database behind the cache. Call that load O.
O equals T times one minus h.
Take the share of reads the cache misses, one minus h. Multiply it by all traffic T. That is the load O the database must carry.
T = 500,000. At h = 0.90, O = 50,000. At h = 0.99, O = 5,000. At h = 0.999, O = 500. Nine points of hit rate made a tenfold difference.
The curve is the origin load at 500,000 reads a second, on a log scale. The warm line is what 3 replicas carry.
The slider moves in steps of miss rate, so 90%, 99% and 99.9% sit equal distances apart.
Run it backwards to set a target. Three replicas carry 12,000 a second, so the cache must keep O under that: h ≥ 1 − 12,000 / 500,000 = 0.976. Below 97.6%, the database tier runs past its wall whatever else goes right.
Two caches in a row multiply their miss rates. A CDN that hits 60%, then an app cache that hits 99% of the rest, pass on 0.4 × 0.01 = 0.4% of all traffic.
Where does a hit rate come from? Human traffic is Zipf-shaped: a few keys take most reads. In an illustrative Zipf model with 10 million keys, the top 1,000 take 45% of reads and the top million take 86%. The rest repeat too rarely to hit, so h never reaches 1.
The failure. Symptom: the dashboard shows 97.8% hits, yet the database runs past its wall. Measure: hit rate per endpoint. Ordinary reads hit 99.8%, sending 950 a second; a new feature with 5% of traffic hits 60%, sending 10,000. Fix: alarm per endpoint, not on the blend.
Chapter 6
Measure how long a cache serves an old value, and tie the end of that window to the write
At 9:00:00 the pricing team fixes a price that was $5 too low. The product page sits in the cache with a 300-second TTL (time to live), filled at 8:58:00. A TTL counts from the fill, not from the change. So the old price stays until 9:03:00.
What does that cost? Call the time the entry expires texp, the time the data changed tchg, and the order rate q. Call the orders placed at the old price N.
N equals q times t-exp minus t-change.
Subtract t-change from t-exp: that is how long the cache serves the old value. Multiply by the order rate q. Each of those N orders used the old price.
With made-up numbers: t-exp = 9:03:00 and t-change = 9:00:00, a window of 180 s. At q = 3 orders a second, N = 540 orders, or $2,700 at $5 each.
The yellow band is the stale window after the 9:00:00 change. Pick a strategy and drag the TTL.
Illustrative: delete on write takes about 5 ms after commit; an event purge reaches every node in about 800 ms.
Facebook's memcache paper writes to the database, then deletes the cached key instead of updating it, because deletes are idempotent: doing one twice is harmless.
The order matters. Delete then write is wrong. A reader can miss between the two, read the old price and put it back until the next write. Write first, then delete. A slow reader can still set an old value after your delete, which is why that paper adds a lease token that the delete cancels.
The failure. Symptom: a corrected value stays wrong for minutes and no log shows an error. Measure: write a value, then poll the cache until it changes. Fix: delete on write where one write owns the value, plus a short backup TTL in case a delete is lost.
Chapter 7
Make the query itself cheap by doing the join once per post instead of once per read
Replicas and caches make a query run less often. Some queries are costly every time. A home feed shows the newest posts from the 300 accounts you follow. Postgres finds and merge-sorts them on every read: say 15 ms instead of 2. This is fan-out on read.
How many boxes does a query need? Call the read rate λ, the cores per box c, and the CPU time of one read s, in ms. Call the boxes needed B.
B equals the ceiling of lambda divided by c times one thousand over s.
Find what one box finishes: c times 1,000, divided by s. Divide the traffic lambda by it. Round up, because half a box does not exist.
At s = 15 ms, one box finishes 8 × 1,000 / 15 = 533 a second, and 5,000 / 533 = 9.4, so B = 10. At s = 2 ms, one box finishes 4,000, so B = 2.
Fan-out on write moves the work. When an author posts, a job inserts the post into a precomputed feed table for every follower. The read becomes one indexed lookup. This table is a denormalized read model: it stores copies of facts that a join of the posts and follows tables could rebuild.
sql-- on a new post: one row per follower INSERT INTO user_feed (user_id, post_id, created_at) SELECT follower_id, $post_id, now() FROM follows WHERE followed_id = $author_id; -- on a feed read: one indexed lookup, about 2 ms SELECT post_id FROM user_feed WHERE user_id = $1 ORDER BY created_at DESC LIMIT 50;
Warm squares are database boxes for 5,000 reads a second. Drag the accounts followed, then the author's follower count.
Illustrative: the live join costs 2 ms plus 13 ms per 300 accounts followed; the fan-out job inserts 50,000 rows a second.
The bill moves to writes. A post from an account with 300,000 followers takes 300,000 / 50,000 = 6 s to reach every feed: a staleness window like replica lag. Keeping 50 entries for 12 million users costs 12 million × 50 × 32 bytes = 19.2 GB.
The usual answer is a hybrid. Accounts under a follower threshold fan out on write. Posts from the few huge accounts load at read time and merge in. Designing Data-Intensive Applications describes social home timelines this way.
The failure. Symptom: one celebrity post makes the fan-out queue lag for minutes. Measure: inserts per post and the age of the oldest queued job. Fix: send accounts above a follower threshold to the read-time path.
Chapter 8
Fold 500,000 reads a second through every layer, size the database last, then break it
Now put every layer in the order a read meets it, at the goal of 500,000 reads a second. Each layer is cheaper to ask than the next, so each one answers what it can first.
Two caches cut the load 250 times before any replica works. Sizing from the raw 500,000 would have needed 125 boxes.
Each row shows the reads a second that reach a layer. Drag the hit rates, then kill a replica or flush the app cache.
Illustrative feed app: 3 replicas at 4,000 reads a second each. A flush sets the app hit rate to 0 until it warms again.
Kill a replica: 2 boxes carry 8,000 against 2,000. Nothing happens, which is the job of the spares.
Flush the app cache: the database load jumps from 2,000 toward 200,000 against 12,000 of capacity, a ρ of about 17. Every key misses at once, so single-flight is what keeps it to one query per key.
Both at once: ρ = 200,000 / 8,000 = 25. The line grows by 192,000 reads each second, 96,000 after half a second. Shed load first, then let the cache warm. Lift the shedding when the hit rate recovers, not when Redis answers again.
Chapter 9
Keep the terms, the numbers, the checks and the code in one place
Fold the traffic through each cache in the order a read meets it. Size the last layer from what reaches it. Make the query cheap where caching cannot help.
| Term | One line | Number in this lesson |
|---|---|---|
| Busy share ρ | arrivals over capacity | 5,000 / 4,000 = 1.25: the wall |
| Queue time W | s / (1 − ρ) | 20 ms at ρ = 0.9, 200 ms at 0.99 |
| Little's law | L = λ × W | 100 writes behind; 40 queries in flight |
| Replication lag | ship plus replay time | about 50 ms; grows past 3,000 writes a second |
| Pool size | in-flight count plus headroom | 40 × 2.5 = 100 |
| RTT floor | d / 100 ms | 109 ms Tokyo to Virginia |
| Herd size | r × t | 8,000 × 0.04 = 320 |
| Origin load | T × (1 − h) | 2,000 behind 60% and 99% |
| Stale orders | q × (texp − tchg) | 540 orders, $2,700 |
| Boxes | ⌈λ / (c × 1000 / s)⌉ | 10 at 15 ms, 2 at 2 ms |
pythondef read_feed(user_id, session): key = f"feed:{user_id}" hit = redis.get(key) # Ch 4-5: the app cache if hit is not None and not session.get("min_lsn"): return hit db = pick_replica(session.get("min_lsn")) # Ch 1: replayed past my write, else leader with pool.connection(db) as conn: # Ch 2: a pooled connection rows = conn.execute(FEED_SQL, (user_id,)) # Ch 7: one lookup in user_feed redis.set(key, rows, ex=30) # Ch 6: deleted on write, 30 s backup TTL return rows
Scaling Writes (the write-side twin: sharding and fan-out cost) · Realtime Updates · Long-Running Tasks · DDIA: Replication · DDIA: Nonfunctional Requirements (home timelines) · Eventual Consistency · Caching and CDNs · Load Balancing · Semantic Caching · Vector Databases
Sources: the PostgreSQL manual on pg_stat_replication, WAL functions and synchronous_commit; PgBouncer configuration; Redis SET; MDN Cache-Control; AWS CloudFront Origin Shield; Nishtala et al., Scaling Memcache at Facebook (NSDI 2013). For refreshing a hot key early, before it expires, see Vattani, Chierichetti and Lowenstein, "Optimal Probabilistic Cache Stampede Prevention" (VLDB 2015).
Now press Present or Teach and explain the read path from memory: the wall, the lag, the pool, the edge, the herd, the hit rate, the stale window and the feed table. Then go back to the hero, stack each layer at 500,000 reads a second, and name the chapter behind each number.