▚ The AI Engineer's Field Manual
Appendix A2 · Companion to Module 17

Distributed Systems Refresher — The Classic Design Round

"You have run these systems for nine years. The interview doesn't score the running — it scores whether you can name the tradeoffs and put numbers on them."

~8 hours For: 9-YOE engineers whose recent work was narrow Refresher, not a first course — DDIA is the deep track

01 · The hookThe Round You Forgot to Practice

The classic design round, and the vocabulary underneath it: how a system scales, what breaks when it does, and what each answer costs.

Field report · Loop debrief

"Round two was the GenAI design round and I owned it — eval-gated RAG, cost ledger, semantic cache, the interviewer nodding before I finished sentences. Round three, different interviewer, one sentence: 'Design a rate limiter for our public API.' I have built rate limiters.

I've been paged by one at 3 a.m. And what came out of me was vibes — 'we'd track requests in Redis and, you know, block people who go over.' She asked whether my counter was atomic across gateway instances.

She asked what happens when the Redis node dies, and I said 'it depends' with nothing after the comma. The debrief line, verbatim: 'strong AI, inconsistent fundamentals.' Nine years of running these exact systems, and I couldn't name what I know."

— "Anand S.", Senior GenAI Engineer candidate, debrief shared with his study group

Module 17 told you the 2026 loop at top companies runs three flavors of system design: traditional, ML, and GenAI. Seventeen modules armed you for the last two. This appendix exists for the first — still standard in the loop, graded harder at senior levels, and exactly where an engineer whose last few years ran deep-but-narrow gets marked down for things they've actually done.

Anand's problem was not knowledge. It was legibility — the interviewer can't see your nine years, only what crosses the whiteboard in 45 minutes. Experience that comes out as "we usually just…" scores as junior; the same experience, spoken in the field's shared vocabulary with numbers attached, scores as staff. The entire job of this refresher is that conversion.

You already know this

Every concept below is an incident you have lived through, wearing its textbook name.

  • Replica lag is the 2019 bug where a user's edit "disappeared" for four seconds.
  • Thundering herd is the outage after the deploy that cold-started the cache.
  • Split-brain is the night two "primaries" both accepted writes.

You are not learning this material. You are re-labelling it. And interviews are scored in labels, trade-offs and numbers — not in scars.

The deep track is Kleppmann's Designing Data-Intensive Applications. This appendix is the exam-cram track.

Hold onto this: behind every "design X at scale" prompt, the interviewer is asking the same three-question rubric, and your answer earns points only when it addresses them explicitly:

02 · The mapThe Anatomy of Every Answer

Anand had forty-five minutes and never finished a single drawing. Before any one topic can help him, he needs one picture he can put on a whiteboard in ninety seconds and then talk over, hop by hop. That picture is below, and the eight refreshers that follow are each one box on it. Learn the map first; the boxes come one at a time after it.

Nearly every classic design answer decorates one canonical picture: a request born on a phone, terminated as close to the user as possible, load-balanced across a stateless app tier, absorbed by a cache, and only then allowed to touch the database — with anything slow pushed onto a queue so the user never waits for it. Learn to draw this in ninety seconds; every worked example here and in Module 17 is a variation of it.

The figure and the table below use every term this appendix teaches, before it teaches them: least-connections, replication lag, dead-letter queue, consistent hashing. That is on purpose. Read them now as a map, and do not expect to explain any cell yet. Sections 03 to 10 take the hops one at a time, and each cell becomes a sentence you can say in the room.

DNS 0 · resolve client 1 · GET CDN / edge hit → served at edge 2 · miss load balancer 3 · least-conn app ×N stateless 4 · read · hit ≈1 ms cache — Redis 5 · miss / write DB primary async repl · lag replicas ×2 6 · async queue pull workers ×M write results
Fig. A2.1 — The canonical request path. Everything left of the app tier exists to answer without computing; everything right of it exists to remember without losing data; the queue exists so the user never waits for slow work.
  1. GET — the client and the edge. Arrow 1. Before it, arrow 0 is DNS turning your name into an IP address, which the client then trusts for as long as the record's TTL says. The request lands at the nearest edge point of presence. If the response is cacheable and already there, the journey ends here and none of your servers ever hear about it.
  2. miss — inward to your own estate. Arrow 2. Anything personal, fresh or written cannot be served at the edge, so it travels on to the load balancer. Everything to the left of this arrow is someone else's hardware; everything to the right is yours to scale and to wake up for.
  3. least-conn — spreading the work. Arrow 3. The balancer picks a healthy app instance, here by fewest open connections, which naturally routes around a slow box. It also ejects instances that fail their health check, which is what makes one app instance dying a non-event.
  4. read — answer without computing. Arrow 4. The app asks the cache first, and a hit comes back in about a millisecond. This arrow exists to keep load off the box on the far right, and roughly nine reads in ten should never get past it.
  5. miss or write — the source of truth. Arrow 5. Only what the cache could not answer, plus every write, reaches the database primary. Replicas hang below it on an asynchronous stream, which is why they are a few milliseconds to a few minutes behind and why reading your own write from one can surprise you.
  6. async — everything the user should not wait for. Arrow 6. Slow work — mail, analytics, thumbnails, click counts — goes onto a queue and is done by workers later. The user's response is not waiting for any of it, which is the entire reason the arrow points downward and not through the reply.

In the room, you narrate each hop with three facts — what it's for, how it fails, and which lever scales it. That narration is the three-question rubric, applied hop by hop:

The request path, hop by hop — purpose, classic failure, scaling lever
HopWhat it's forClassic failureScaling lever
DNSName → IP, cached client-sideStale records during failoverLow TTLs + health-checked routing
CDN / edgeServe static & cacheable responses near usersStale content; wrong cache key leaks user A's page to user BTTLs and cache keys — the PoPs are the vendor's problem
Load balancerSpread traffic, hide instance churnBecomes a SPOF itself; sticky sessions smuggle state back inRedundant pair + health checks; L4 for throughput, L7 for routing
App tier ×NBusiness logic, kept statelessState on the box → can't scale, can't deploy, can't fail overAdd replicas; autoscale on load
CacheAbsorb repeated reads at ~1 msStampede on expiry; stale readsMore nodes via consistent hashing
DB primarySource of truth; all writesFailover, split-brainVertical first, then shard
ReplicasScale reads; survive primary lossReplication lag → stale readsAdd replicas; loosen consistency knowingly
Queue + workersAbsorb spikes; do slow work off-pathBacklog growth; poison messagesMore partitions and consumers; DLQ

Now the same picture a second time, with this appendix's real names in the boxes. Every row below is either a file you will run in sections 13 and 16, or a line from the URL shortener you will design in section 12. If a box in Fig. A2.1 feels abstract, find its row here and read what actually flows out of it.

Fig. A2.1 again, concretely: each hop as it exists in this appendix's code and worked examples
StageIn the one-box version (day one)In the production version (§12 shortener, §13 limiter, §16 lab)What flows out
DNSOne A record pointing at one machineShort-TTL records in front of health-checked balancers, so a failover repoints clients once the TTL expiresAn IP address the client trusts for a short time
CDN / edgeNone; every request reaches the appStatic assets, plus the top-100 hottest short codes pushed to the edge (§12, step ⑦)A response served without touching your servers, or a miss passed inward
Load balancerNone; one process on one portA redundant pair of L7 least-connections balancers with health checks (§03)A request routed to a healthy instance that holds no state for that user
Rate limiternaive_bucket.py: read the bucket, then write it back, which over-admits under loadredis_token_bucket.py: the read-modify-write runs inside Redis as one Lua script (§13)200 and one fewer token, or 429 with a Retry-After the bucket computed itself
App tier ×NOne process that also keeps sessions in memoryapp ×8, stateless; sessions in Redis; ID ranges leased 100,000 at a time (§12, step ⑥)GET /x7Kp2a becomes a cache lookup; POST /api/links becomes one indexed insert
CacheNone; every redirect queries the databaseRedis holding the hot codes, about 10 GB, cache-aside with a jittered 24-hour TTL; the HashRing in ratelimit.py decides which node owns each keyA 302 in about 1 ms on a hit; a database read on a miss
DB primaryThe same single Postgres, taking every read and writePostgres primary with links(code PK, long_url, owner_id, created_at, expires_at); quorum election and fencing on failover (§05)The acknowledged write, and a replication stream to the replica
ReplicasNoneOne asynchronous read replica absorbing cache misses; reads of codes younger than 60 s go to the primary instead (§06)A row that may be a few seconds stale, which the design has decided is acceptable
Queue + workersA click counter incremented inline, on the redirect pathA Kafka topic of click events with an analytics consumer group; a bug fix replays the log to rebuild counts (§07)Per-code click counts, computed off the critical path
🧠 Brain power

Before reading on: a teammate "fixes" a login bug by turning on sticky sessions at the load balancer — each user is pinned to one app instance. The bug disappears. What did the system just silently lose?

Reveal the answer

Statelessness — and with it, three properties at once. Sticky sessions cost you all three:

  • Elasticity. A new instance gets only new users, so scaling out no longer relieves the loaded boxes.
  • Deployability. Restarting an instance logs out everyone pinned to it.
  • Fault tolerance. An instance death becomes a user-visible incident rather than an invisible retry.

The real fix is externalising the session — Redis, or a signed token — so that any instance can serve any user.

"Sticky sessions are how state sneaks back into a 'stateless' tier" is a line interviewers reward.

03 · Refresher 1Scaling & Statelessness

The map is drawn, so the first box gets its turn: the app tier. Anand's interviewer will ask what happens at ten times today's traffic, and the honest answer is "add more app boxes". That answer only works if any box can serve any user, and nine years of running app servers taught Anand that without ever making him say it out loud. The round scores the saying. This section is that precondition, with a picture of exactly what sticky sessions cost when you break it.

Vertical scaling (a bigger box) is underrated and should be your stated first move — no coordination, no rearchitecture, and 2026 cloud instances go to terabytes of RAM. Its limits: a ceiling, a price curve that bends the wrong way, zero fault tolerance.

Horizontal scaling (more boxes) has no ceiling but one precondition interviewers probe relentlessly: the tier must be stateless. Any request must be servable by any instance, so sessions, uploads, and in-process caches move out to shared services (Redis, object storage).

State is gravity — it makes copies of a service unequal, and unequal copies can't be load-balanced.

Draw the two worlds side by side before you argue for either. Fig. A2.1b puts 1,000 requests a second through four app boxes twice: once where any box may serve any user, and once where the load balancer has pinned each user to one box.

1 STATELESS — ANY BOX SERVES ANY USER load balancer app 1 250 req/s app 2 250 req/s app 3 dies app 4 250 req/s 2 WHEN APP 3 DIES 1,000 req/s ÷ 4 boxes = 250 each health check fails → 1,000 ÷ 3 = 333 each nobody is logged out; nobody notices 3 STICKY — EACH USER PINNED TO ONE BOX load balancer user U → app 2, always app 1 250 users app 2 restarts app 3 250 users app 4 250 users 4 WHEN APP 2 RESTARTS its 250 users are logged out a new app 5 gets 0 of the 1,000 the four copies are no longer equal
Fig. A2.1b — Statelessness, priced. Left: four equal boxes, so a death is arithmetic (250 each becomes 333 each). Right: the same boxes made unequal by pinning, so a restart is an incident and a new box relieves nobody. Numbers chosen round — 1,000 requests a second over four instances — to keep the arithmetic sayable out loud.
  1. Equal copies, marker 1. Every box holds the same nothing: no sessions, no uploads, no in-process cache. The balancer can therefore send request seven to any of them. That is the one precondition horizontal scaling has, and it is the sentence interviewers listen for.
  2. A death is arithmetic, marker 2. App 3 fails its health check and the balancer ejects it. The other three now carry 333 requests a second each instead of 250. No user session died with the box, because no user session was on the box.
  3. The pin, marker 3. Sticky sessions tell the balancer to send user U to app 2 for as long as the cookie lives. The login bug disappears because the session now always finds itself. State has moved back onto the box, and the four copies stopped being interchangeable.
  4. The bill, marker 4. Restarting app 2 logs out its 250 users, so deploys become user-visible. A fifth box receives only brand-new users, so scaling out no longer relieves the loaded four. Both losses come from the same pin.

The load balancer's algorithm is a one-sentence decision, and there are three answers.

Choosing a load-balancing algorithm.
AlgorithmUse it when
Round-robinRequests are uniform.
Least-connectionsRequest cost varies. It naturally routes around a slow instance.
Consistent-hashYou want the same key on the same instance — cache affinity — without re-introducing stickiness for everything.

Health checks are what make any of it real. The balancer ejects an instance that fails its check, which is precisely why node death in a stateless tier is a non-event.

One distinction to draw unprompted: L4 is TCP — fast and blind. L7 is HTTP-aware, so it can do path routing, retries and header-based canarying.

Say it in the room: "Stateless app tier behind a least-connections L7 balancer with health checks; sessions externalized to Redis. Scaling is now 'add replicas' — which is why my next bottleneck is the database, and my next box is a cache."

"We run one Postgres on one big box. It has never gone down. Why do I need any of this?"

— a nine-year engineer, reading the word "replicas" for the third time

For a great many systems, one Postgres is the right answer, and this appendix says so in §05: "Postgres until it hurts" is a defensible default. Vertical scaling is listed as the first move for a reason. If your working set fits in memory and your write rate is modest, a single well-run database with tested backups beats a badly-run cluster every day of the year.

Two things apply anyway. First, "never gone down" means "never gone down while you were watching". The day the disk fills, the host is retired, or the box reboots for a kernel patch, every question in §05 gets asked in the incident channel. Second, the interview is not asking whether your system needs replicas. It asks what breaks at ten times the load, and which lever you would pull first.

The honest downside of everything that follows: every box you add is a new way to fail. Marker 2 of Fig. A2.1b is the good version of that trade — a dead app instance becomes arithmetic, 250 requests a second each becoming 333 — and marker 4 is the bad version, where one pinned box takes 250 users down with it. A replica adds a lag window. A cache adds a staleness window and a stampede. A queue adds duplicate deliveries. The senior answer is not "add all of it". It is "I know what each one costs, so I add it when the cost is lower than the outage it prevents".

04 · Refresher 2Caching — Speed You Pay For Later

Adding app boxes moves the bottleneck one hop to the right, onto the database. The cheapest way to keep reads off it is a cache, which turns a 10 ms database read into a 1 ms memory read and takes nine reads in ten off the primary. It also hands you the two failures every interviewer probes: data that is quietly out of date, and a stampede the moment a popular key expires. Both are drawn here with numbers before either is named.

A cache converts a ~10 ms database read into a ~1 ms memory read and, more importantly, absorbs the read traffic that would otherwise melt the primary. The price is the second of the two famously hard things: invalidation. Every caching answer must name its write strategy and its staleness window — an interviewer who hears "we'd add Redis" with no invalidation story marks the rubric's cost question unanswered.

1 WITHOUT A CACHE 100 reads/s every read goes to disk database · 10 ms 100 queries a second reach the primary average read latency: 10 ms 2 CACHE-ASIDE, 90% HIT RATE 100 reads/s 90 hits · 1 ms cache — Redis 10 misses · 10 ms database 3 (90 × 1 ms + 10 × 10 ms) ÷ 100 = 1.9 ms average the database now sees 10 queries a second, not 100 the 10 misses still pay the full 10 ms each
Fig. A2.1c — What a cache actually buys, at a 90% hit rate on 100 reads a second: the average read falls from 10 ms to 1.9 ms, and nine reads in ten never reach the primary. The second number is the one that saves you; the first is the one people quote.
  1. The unprotected read, marker 1. Every read is a database read. The primary does 100 queries a second here, and 10,000 a second in a real system, and each one costs about 10 ms of somebody's time. This is the load the cache exists to remove.
  2. The split, marker 2. Cache-aside means the app asks Redis first. Ninety reads in a hundred are answered there in about 1 ms. The other ten go to the database and are written back into the cache on the way out, which is why the hit rate stays high.
  3. The arithmetic, marker 3. Average latency is (90 × 1 + 10 × 10) ÷ 100 = 1.9 ms, a bit over five times faster. Database load falls by 90%, from 100 queries a second to 10. In an interview, say the load number: latency is what the user feels, but load is what keeps the primary alive.
Decision table: cache write strategies
StrategyHow writes flowStalenessRiskChoose when
Cache-aside (lazy)App writes DB, deletes the cache key; next read refillsSmall window between write and deleteA racing read can refill the old value — add short TTLs as backstopDefault for read-heavy traffic; caches only what's actually read
Write-throughWrite cache and DB synchronouslyNone (for cached keys)Write latency up; caches keys never readRead-after-write matters and the hot set is small
Write-behindWrite cache now, flush to DB asyncDB lags the truthCache dies before flush → data lossWrite-heavy counters/metrics where loss is tolerable

Be honest about TTL vs explicit invalidation: invalidation is precise but every write path must remember to do it; TTLs are blunt but bound staleness by construction. Production answer: both — invalidation for correctness, TTLs as the safety net, jittered so a cohort of keys doesn't expire in the same second. Then name the layers: CDN for anonymous/static responses, app-tier Redis for hot objects and sessions, and the database's own buffer pool — why a cold-cache incident hurts twice.

🧠 Brain power

Before reading on: one hot key serves 10,000 requests/second. Its TTL expires. What happens in the next 100 ms?

Reveal the answer

Every one of those requests misses simultaneously and stampedes the database with the same query. That is the thundering herd.

Three mitigations, in the order interviewers like to hear them:

  • Request coalescing. The first miss takes a lock and fetches; the rest wait for its result. Go's singleflight, or a Redis SET NX lock.
  • Stale-while-revalidate. Serve the expired value while one worker refreshes it.
  • Jittered TTLs, so the herds never synchronise in the first place.
1 THE HERD — ONE HOT KEY EXPIRES AT t = 0 hot key 10,000 req/s 10,000 identical SELECTs inside the same 100 ms database every request missed, because they all read one key one key's worth of data, fetched 10,000 times 2 COALESCED — ONE FETCH, THE REST WAIT hot key 10,000 req/s 1 takes the lock SET NX lock 1 SELECT database 9,999 wait about 10 ms and share the one answer 3 jittered TTLs are the earlier fix: they stop a cohort of keys expiring in the same second at all
Fig. A2.1d — The thundering herd and its cure, at the brain-power question's own numbers: one key, 10,000 requests a second, one expiry. Coalescing turns 10,000 database queries into one plus 9,999 short waits.
  1. Why they arrive together, marker 1. A hot key is hot because everyone reads it. When its TTL runs out, every in-flight request misses at the same instant, and each one independently decides to go and fetch the value. The database receives 10,000 copies of one query in about 100 ms and falls over, which is how a cache becomes an outage.
  2. The lock, marker 2. Request coalescing lets exactly one miss proceed. It takes a short lock — SET NX in Redis, singleflight in Go — fetches once, writes the value back, and releases. The other 9,999 wait roughly the one query's 10 ms and are then served from the cache.
  3. The earlier fix, marker 3. Coalescing handles one key at a time. Jitter handles the fleet: give each TTL a random few minutes on top so a batch of keys written in the same deploy does not expire in the same second. Do both; they solve different halves.

When the cache outgrows one node, the question becomes: which node holds key k? Naive answer: hash(k) mod N. The trap: change N and almost every key changes owner — one node dies and the whole cache goes effectively cold at once. Consistent hashing is the fix, and it's a picture worth drawing on any whiteboard:

node A node B node C — dies node D key k A key hashes to a point on the ring, then walks clockwise to the first node. Highlighted arc = keys owned by C. C dies → exactly that arc re-homes to D: ≈1/N of keys move; every other node's cache stays warm. (hash mod N would move (N−1)/N of keys — a fleet-wide cold start from one node loss)
Fig. A2.2 — The consistent-hash ring. Losing a node reassigns only that node's arc — about 1/N of keys — to its clockwise successor. Virtual nodes (each server hashed onto the ring ~100+ times) keep the arcs statistically even; you'll build this in the lab.

Fig. A2.2 is the idea; Fig. A2.2b is the measurement, taken from the output of ratelimit.py in section 16, where 20,000 keys are hashed onto a four-node ring and one node is then removed.

1 20,000 KEYS, 4 NODES, 128 VIRTUAL NODES EACH even share 25% 24.1% n0 24.0% n1 27.0% n2 24.9% n3 2 REMOVE n2 — HOW MANY KEYS MOVE? 5,400 keys · 27% the ring 15,000 keys · 75% hash mod N 3 every key that was not on n2 stays exactly where it was — the test checks that key by key n2 held 27.0%, not 25.0%: 128 virtual nodes land unevenly, and more of them flatten the shares with hash mod N, three keys in four change owner and the whole fleet starts cold
Fig. A2.2b — The ring, measured. Numbers are the printed output of ratelimit.py: shares of 24.1%, 24.0%, 27.0% and 24.9%, and 27.0% of the 20,000 keys moving when n2 leaves — against 75% under hash(k) mod N.
  1. The shares, marker 1. Four nodes, 128 virtual positions each, 20,000 keys. The shares land near a quarter but not on it, because hashing spreads by chance rather than by fairness. Raising the virtual-node count narrows the spread; lowering it to one per node produces wildly uneven arcs, which is the bug behind most "consistent hashing didn't work" stories.
  2. The move, marker 2. Removing n2 re-homes exactly n2's keys: 5,400 of 20,000. Under hash(k) mod N the divisor changes from 4 to 3 and 15,000 keys change owner, so the cache is effectively empty and the database takes the whole read load at once.
  3. The exact claim, marker 3. The interesting half is not the 27%. It is that every key not owned by n2 stayed put, which test_node_loss_moves_about_one_nth_and_nothing_else asserts for each of the 20,000 keys. That is a guarantee, not a statistic, and it is why the surviving nodes keep serving hits through a node loss.

Say it in the room: "Cache-aside with explicit invalidation and jittered TTLs as backstop, request coalescing for herd control, and consistent hashing across the cache fleet — so losing a node remaps 1/N of the keyspace instead of going cold."

05 · Refresher 3Databases — Replication, Failover, Sharding

The cache absorbs the reads, so what is left on the database is the writes and the truth. Anand was asked what happens when the Redis node dies and had nothing after "it depends"; the same question about the database primary is the oldest one in the round. This section is the answer with numbers: when the primary says yes to a write, what sits in the lag window, and what stops two primaries from writing at once. You will play the cluster yourself in a five-node trace and then see your own trace drawn.

Replication answers two needs at once — read scale and surviving the loss of a machine — and its single design decision is when the primary acknowledges a write.

Synchronous: the commit waits for a replica — every write pays a replica round trip, and failover loses nothing.

Asynchronous: the primary acknowledges immediately and ships the change later — writes are fast, and there is now a lag window of acknowledged-but-unreplicated writes that dies with the primary.

Nearly every real deployment is async (or semi-sync: wait for one of k replicas), which is why replica-lag questions are so common — it's the tradeoff everybody actually lives with.

synchronous asynchronous client primary replica 1 · write 2 · replicate 3 · ack 4 · OK — durable ×2 commit waits for the slowest replica: every write pays +1 replica round trip client primary replica 1 · write 2 · OK — durable ×1 3 · replicate later lag: ms → minutes commit is fast; if the primary dies now, writes in the lag window are gone
Fig. A2.3 — The replication tradeoff in one picture: sync buys durability with write latency; async buys latency with a lag window you must design around (stale reads now, possible loss on failover).

Failover is the async story's second act: detect the dead primary via missed heartbeats, promote the most-caught-up replica, repoint clients. The nightmare word is split-brain — the "dead" primary was only partitioned, and now two nodes accept unmergeable writes. Real systems prevent it with quorum-based leader election (odd number of voters; only a majority elects) and fencing — the old leader's writes are rejected once a new epoch begins. "Quorum election and a fencing token" is usually the exact phrase the interviewer is fishing for.

BE the quorum

Your turn to play the cluster. Five database nodes, A to E, replicate one log. A leads in term 1; a term is an election number, and every vote and every write carries it. Two majority rules apply. A node becomes leader only with votes from more than half the cluster. A write commits only once more than half the nodes have stored it. Work through the six events below with a pencil.

  1. A network switch fails. The cluster splits into {A, B} and {C, D, E}. Nothing crosses the split.
  2. C stops hearing A's heartbeat, waits out its election timer, moves to term 2, votes for itself, and asks everyone for a vote.
  3. D and E receive the request. Neither has voted in term 2, and C's log is as complete as theirs, so both grant their vote. A and B never receive the request.
  4. Client X, still connected to A, writes x = 7. A appends it and asks the others to store it. Only B answers.
  5. Client Y, connected to C, writes y = 3. C appends it; D and E store it and answer.
  6. The switch is repaired. A and B hear C's heartbeat, which carries term 2.

Who is the leader after event 3, and with how many votes? Does x = 7 commit? Does y = 3 commit? What happens to A, and to x = 7, at event 6? Then one more: if the cluster had four nodes and split 2 against 2, who would be leader?

Check your answer

After event 3, C is the leader of term 2 with three votes: its own, D's and E's. Three of five is a majority. A still believes it is the leader of term 1, and nothing on its side of the split can tell it otherwise. Two nodes both think they lead, which is the split-brain moment. What follows is why it does no damage.

The write x = 7 never commits. A and B have stored it: two of five, not a majority. A keeps waiting for a third acknowledgement that cannot arrive, and client X waits or times out. A leader cut off from the majority can accept a write but never commit one. The write y = 3 commits at event 5: stored on C, D and E, three of five, and client Y is acknowledged.

At event 6, A hears a heartbeat carrying term 2, which is higher than its own term 1. A steps down to follower on the spot, and B does the same. A's uncommitted x = 7 sits at a log position where C's log has something else, so A truncates it and copies C's entries.

The term number is the fencing token: any write stamped with an old term is refused by every node that has seen a newer one. Client X, if it is still waiting, is told to try again against C. Nothing it was told had committed was lost, because nothing was ever committed.

Four nodes split 2 against 2: nobody. A majority of four is three, and neither side has three. Both halves refuse writes until the split heals. That is safe and completely unavailable. It is why voters come in odd numbers: five nodes tolerate two losses, four tolerate only one, so the fourth node bought nothing.

The lesson underneath all of it: two majorities of the same cluster must share at least one node, and that node votes once per term. That overlap is the whole reason two leaders of the same term cannot exist, and it is the same pigeonhole argument as the quorum figure in §06.

Now compare your pencil with the picture. Fig. A2.3b is that exact trace: the same five nodes, the same split, the same two writes, and the fence that comes down at event 6.

1 MINORITY SIDE {A, B} A · leader, term 1 appends x = 7 B stores x = 7 stored on 2 of the 5 nodes 2 is not a majority → x = 7 never commits client X waits, then times out a cut-off leader can accept, never commit 3 no message crosses this line 2 MAJORITY SIDE {C, D, E} C · leader, term 2 3 votes of 5 D vote · term 2 E vote · term 2 C has 3 votes of 5 → leader of term 2 y = 3 stored on C, D and E = 3 of 5 3 is a majority → y = 3 commits, client Y is told OK two leaders exist at once; only this one can commit anything 4 EVENT 6 · THE SWITCH IS REPAIRED A hears a heartbeat: term 2 term 2 > term 1 → A steps down A truncates x = 7 and copies C's log
Fig. A2.3b — Your trace, drawn. Two nodes believe they lead, and that is harmless: the minority leader can append but never reach three of five, so nothing it accepted was ever promised to a client. The term number is the fence that ends it.
  1. The minority side, marker 1. A is still leader of term 1 and has no way to learn otherwise. It appends x = 7 and B stores it, which is two nodes of five. Two is not more than half, so A waits for a third acknowledgement that cannot arrive, and client X is never told the write succeeded.
  2. The majority side, marker 2. C times out, moves to term 2, votes for itself and collects D's and E's votes. Three of five elects it. The write y = 3 then reaches C, D and E — three of five again — so it commits and client Y gets an answer. Both majorities here contain at least one node in common, and that node votes once per term, which is why a second leader of term 2 is impossible.
  3. The line itself, marker 3. Nothing crosses. Each side sees silence and cannot tell a dead peer from an unreachable one. That indistinguishability is the whole problem; the majority rule is the answer, because only one side of any split can hold more than half the nodes.
  4. The fence, marker 4. When the switch comes back, A hears a heartbeat stamped term 2. Any node that has seen term 2 refuses anything stamped term 1, so A steps down at once and rewinds the log entry nobody ever committed. Nothing a client was promised is lost, because nothing was promised.

Sharding is what happens when writes or data outgrow one primary: partition the data across independent databases by a shard key. Everything about sharding is choosing that key well:

Decision table: partitioning schemes
SchemeHowWinsLoses
RangeContiguous key ranges per shardRange scans are natural; splits are simpleSequential keys (timestamps!) hammer the newest shard
Hashhash(key) → shard, ideally via consistent hashingEven spread by constructionRange queries scatter to all shards; resharding needs care
DirectoryA lookup service maps key → shardTotal control; rebalance by editing the mapOne more hop; the directory is now critical infrastructure

Then volunteer the classic trap before it's sprung on you: "shard by user_id" is right until a hot key shows up — the celebrity whose single ID out-writes a whole shard.

Mitigations: salt the hot key across sub-shards (fan writes out, merge on read), give outliers a dedicated path, cache in front of hot reads.

1 SHARD BY user_id — AND THEN A CELEBRITY SIGNS UP one shard handles 5,000 writes/s 1,000/s shard 1 1,000/s shard 2 7,000/s shard 3 1,000/s shard 4 2 SALT THE HOT KEY ACROSS FOUR SUB-KEYS 2,500/s shard 1 2,500/s shard 2 2,500/s shard 3 2,500/s shard 4 3 the celebrity's 6,000 writes/s become celeb#0 … celeb#3, so 1,500 land on each shard the bill: every read of that account must now ask all four sub-keys and merge the answers
Fig. A2.3c — The hot key, priced. Numbers chosen round to keep the arithmetic sayable: four shards at 1,000 writes a second each, one account adding 6,000, and a shard that tops out at 5,000. Salting spreads that one account over four sub-keys and every shard lands at 2,500.
  1. The even day, marker 1. Hashing user_id spreads accounts evenly, so each shard carries about a quarter of the writes. This is the state everyone designs for, and it is true right up to the moment one row becomes far busier than the rest.
  2. The celebrity, marker 1 again. A single account adding 6,000 writes a second lands entirely on shard 3, because one key hashes to one shard by definition. Shard 3 now sees 7,000 against a capacity of 5,000 and starts timing out, while the other three run at a fifth of their capacity. Adding shards does not help: the hot key still lands on exactly one of them.
  3. The salt, marker 2. Write the hot account as four keys, celeb#0 to celeb#3, chosen at random per write. Each shard now takes 1,000 of its own plus 1,500 of the celebrity, which is 2,500 and comfortably under the line.
  4. What it costs, marker 3. Reads of that account must query all four sub-keys and merge, so the read path gets slower and more complex for one row. That is the trade, and saying it out loud — "salting moves the cost from the write path to the read path" — is what makes the answer senior.

On indexes, two paragraphs of depth suffice: a B-tree is a sorted structure giving O(log n) lookups and ordered scans, and every additional index taxes every write while competing for buffer-pool memory — a read-path purchase paid on the write path.

Composite indexes serve their leftmost prefix; a covering index answers without touching the table. That's 90% of interview index questions.

Decision table: SQL vs NoSQL, without tribalism
NeedReach forBecause
Transactions across rows, ad-hoc queries, <~10 TBPostgreSQLACID, joins, mature planner — "Postgres until it hurts" is a defensible default
Sub-ms key-value, counters, sessionsRedisIn-memory data structures; also your cache and rate-limit store
Massive write throughput, known query patternsCassandra-class wide-columnLSM storage, linear horizontal scale, tunable N/R/W consistency
Flexible documents, mid-scaleMongoDB or Postgres JSONBSchema evolves with the product; JSONB keeps SQL's tooling
Relationship-heavy traversalsGraph DBFriend-of-friend queries that would be join explosions

Say it in the room: "Async replication for read scale, so I'll handle lag explicitly — read-your-writes by pinning an author's reads to the primary briefly. Failover via quorum election with fencing to prevent split-brain. If writes outgrow one primary, hash-shard on user_id and I'll tell you my hot-key plan before you ask."

06 · Refresher 4Consistency — CAP Without the Folklore

The trace showed a cluster that refused to lose data by refusing to answer. That trade has a name interviewers use as a screen, and they use the folklore version on purpose: CAP, "pick two of three". Anand needs the true version in one breath, plus the dial that goes with it. This section states it the way it works and puts the dial on a picture: which data class buys consistency, which buys availability, and what R + W > N actually guarantees.

State CAP the way it actually works, because interviewers use the folklore version as a trap. It is not "pick two of three." Partitions are not optional — switches fail, AZ links flap — so partition tolerance is a fact, not a choice.

The real theorem: when a partition happens, you choose between consistency (refuse to answer rather than answer wrong — availability suffers) and availability (keep answering — some answers are stale, reconcile later).

And the choice is per data class: the ledger is CP, the view counter is AP. PACELC completes it in one sentence: during a Partition it's A vs C; Else — healthy operation, most of the time — you're still trading Latency vs Consistency (exactly Fig. A2.3: waiting for replicas buys C with L).

Consistency levels, weakest guarantee last — each with what a user actually sees
LevelThe promiseUser-visible example
Strong (linearizable)Every read sees the latest write, as if one copyAfter a transfer, both accounts show correct balances on any device, instantly
Read-your-writesYou always see your own updatesYour new profile photo appears to you immediately; a friend may see the old one for seconds
Monotonic readsA reader never goes backwards in timeRefreshing never resurrects the comment you just watched get deleted
EventualReplicas converge, eventually, absent new writesYour follower count differs across devices for a few seconds — nobody is harmed
1 ONE WRITE, ONE ASYNCHRONOUS REPLICA primary write: the new photo, at t = 0 lag window: 4 seconds replica applies it at t = 4 s a read here returns the OLD photo 0 s 1 s 2 s 3 s 4 s 5 s 6 s 2 READ-YOUR-WRITES: PIN THE AUTHOR TO THE PRIMARY primary the author's own read at t = 1 s is routed here → the NEW photo 3 everyone else still reads the replica and sees the old photo until t = 4 s, and nobody is harmed
Fig. A2.3d — Replica lag, and the cheapest consistency you can buy. The four seconds are the appendix's own 2019 bug, where a user's edit "disappeared". Read-your-writes spends strong consistency on exactly one reader, for about a minute, and leaves everybody else on the fast path.
  1. The lag window, marker 1. An asynchronous primary answers the writer immediately and ships the change afterwards. For four seconds the replica holds the old row and answers reads with it. Nothing is broken; the system is doing exactly what it was configured to do.
  2. The pin, marker 2. Read-your-writes is a routing rule, not a new database: for a short window after someone writes, send that person's reads to the primary. The author sees their own photo at once. This is the level almost every product actually needs.
  3. Who still pays, marker 3. Everyone else keeps reading the replica, so a friend may see the old photo for up to four seconds. That is a deliberate choice, and it costs one extra primary read per author rather than making every read strongly consistent.

Leaderless systems (Dynamo lineage: Cassandra, Riak) make the dial explicit with quorums: N replicas hold each key, writes wait for W acknowledgements, reads consult R replicas and take the newest version. The whole trick is one inequality:

write quorum W = 2 node 1 node 2 the overlap node 3 read quorum R = 2 N=3, W=2, R=2 → R+W = 4 > 3 any read set must intersect any write set — the overlap node carries the newest write
Fig. A2.4 — Quorum overlap. If R+W > N, every read set shares at least one node with every write set (pigeonhole), so some replica in the read always has the latest value. R+W ≤ N is faster and more available — and may read entirely stale nodes.
🧠 Brain power

Before reading on: N=3, and you configure R=1, W=1. What did you just buy, and with what?

Reveal the answer

You bought speed and availability — any single live node can serve a read or take a write. You paid with the overlap guarantee: R+W = 2 ≤ 3, so a read may consult only nodes the last write never touched → stale reads with no bound. And durability: the one node that took your write can die before replicating it. That's a legitimate configuration for like-counts. It's malpractice for balances. Saying which data gets which setting is the senior move.

Questions you might be asking now

Fig. A2.4 and the brain-power answer above pack three ideas into a few lines: why the overlap always holds, how often a quorum can act at all, and what "consistency" means. Each answer below slows one of them down. All three use the same key: user 42's profile photo, kept on three replicas.

The one key every answer below uses. It is the profile photo from Fig. A2.3d, now kept by a leaderless store with N = 3 replicas, as in Fig. A2.4. The owner has just replaced photo-A (version 1) with photo-B (version 2), and the write has reached two replicas so far.
ReplicaHolds before the changeHolds after the W = 2 writeUp on its own
node 1v1 · photo-Av2 · photo-B99.9% of the time
node 2v1 · photo-Av2 · photo-B99.9% of the time
node 3v1 · photo-Av1 · photo-A (not copied yet)99.9% of the time
Why does R + W > N mean a read always finds the newest write? Show me every possible read and write for three replicas.

Because any two of three replicas and any other two of the same three must share at least one. List all 3 possible write groups against all 3 possible read groups, and all 9 pairs share a replica. With R = 1 and W = 1, only 3 of the 9 pairs do.

First the three letters, in plain words:

  • N, the copies. How many replicas keep the key. Here N = 3: nodes 1, 2 and 3.
  • W, the write quorum. How many replicas must store a write before the client is told "OK". Here W = 2.
  • R, the read quorum. How many replicas a read asks. Each answer carries its version number, and the read returns the highest. Here R = 2.

The claim: when R + W is bigger than N, every read group shares a replica with every write group, and that replica's newer version wins. With three replicas you can check every case, because there are only nine.

  1. List every write group. A write that stops at 2 of the replicas {1, 2, 3} lands on {1, 2}, {1, 3} or {2, 3}. Three groups.
  2. List every read group. A read that asks 2 replicas asks one of the same three pairs: {1, 2}, {1, 3} or {2, 3}.
  3. Pair them up. Three write groups × three read groups = 9 pairs.
  4. Check each pair for a shared replica. Write {1, 2} and read {2, 3} share node 2. Write {1, 3} and read {2, 3} share node 3. All 9 pairs share at least one (marker 1 in Fig. A2.4i).
  5. See why it cannot fail. Two groups with nothing in common would need 2 + 2 = 4 different replicas, and only 3 exist. That is R + W > N with the numbers in: 4 > 3. It is the pigeonhole proof in the hood block: four places to fill from three replicas, so one replica is used twice.

Now use the table at the top of this block, where photo-B has reached nodes 1 and 2 and node 3 still holds photo-A. Every possible R = 2 read finds photo-B:

Every R = 2 read of user 42's photo after the W = 2 write, from quorum_by_hand.py
The read asksAnswers it getsReturnsAfterwards
nodes 1 and 2v2, v2photo-Bnothing to fix
nodes 1 and 3v2, v1photo-Bread repair copies v2 to node 3
nodes 2 and 3v2, v1photo-Bread repair copies v2 to node 3

Read repair is the read noticing that one replica answered with an older version, and writing the newer one back to it. It is how node 3 catches up even if the original copy sent to it was lost.

The same counting works for every setting of three replicas. The table compares them, because the choice of R and W is a real design decision:

Every setting for N = 3, counted pair by pair by quorum_by_hand.py
SettingR + WPairs that share a replicaWhat a read can return
W = 2, R = 249 of 9Always the newest confirmed write
W = 1, R = 123 of 9An older photo, with nothing to warn it
W = 2, R = 136 of 9An older photo, if it asks the one replica the write skipped
W = 1, R = 236 of 9An older photo, if it asks the two replicas the write skipped
W = 3, R = 143 of 3Always the newest, but every write needs all three replicas up
W = 1, R = 343 of 3Always the newest, but every read needs all three replicas up
1 W = 2, R = 2 · ALL 9 PAIRS MEET read group write group {1, 2} {1, 3} {2, 3} {1, 2} {1, 3} {2, 3} 1, 2 1 2 1 1, 3 3 2 3 2, 3 each cell: the replicas both groups share 9 of 9 pairs share at least one replica 2 W = 1, R = 1 · 6 OF 9 PAIRS MISS read group write group {1} {2} {3} {1} {2} {3} 1 miss miss miss 2 miss miss miss 3 a read of one replica, a write to one other 6 of 9 pairs miss: the read returns photo-A 3 THE LIMIT · A WRITE STILL ON ITS WAY, SENT AT t = 0 node 1 node 2 node 3 v2 from 10 ms v2 from 60 ms v1 until 400 ms OK at 60 ms A at 20 ms: photo-B B at 40 ms: photo-A C at 100 ms: photo-B 0 ms 50 ms 100 ms dashed line: the replica still holds photo-A (v1) · solid line: it holds photo-B (v2) before the OK, 100 of 180 possible reads saw photo-B; after it, 1,320 of 1,320 did
Fig. A2.4i — The overlap, checked case by case. Top: every write group against every read group for three replicas, with W = 2, R = 2 on the left and W = 1, R = 1 on the right. Bottom: the one case the rule does not cover, a read that runs while the write is still arriving. Values from rerunning quorum_by_hand.py.
  1. Every pair meets. Rows are the three places a W = 2 write can land, and columns are the three pairs an R = 2 read can ask. Every cell names at least one shared replica, and the diagonal shares two. That shared replica holds photo-B with version 2, and the read keeps the highest version.
  2. One and one can miss. With W = 1 and R = 1, the write lands on one replica and the read asks one. They meet only on the diagonal: 3 cells of 9. In the other 6 the read returns photo-A and cannot know a newer photo exists. That is the "stale reads with no bound" of the brain-power answer.
  3. A write still on its way. Photo-B reaches node 1 at 10 ms and node 2 at 60 ms, when the client is told OK. Reader A, at 20 ms, sees it through node 1. Reader B, at 40 ms, asks nodes 2 and 3 and sees photo-A: a later reader saw an older photo. From 60 ms on, every read group contains node 1 or node 2.

What the rule does not promise

Markers 1 and 2 of Fig. A2.4i count groups that a finished write landed on. Marker 3 traces a write still travelling. Reader B asks at 40 ms, after reader A, and sees an older photo, because neither of its replicas has version 2 yet. Before the client's OK, 100 of 180 possible reads saw photo-B; after it, all 1,320 did. So the promise covers confirmed writes only.

The "strong" row of the consistency table in section 06 forbids exactly that backwards step, so a Dynamo-style quorum is not automatically strongly consistent. Two more gaps exist. A write reported as failed is not undone on the replica it reached. And a sloppy quorum, which borrows stand-in replicas during an outage, can put a write outside the three home replicas, so the groups no longer have to meet.

R + W > N forces every read group to meet every write group, so a read always finds the newest confirmed write. It promises nothing about a write that is still on its way.

If each replica is up 99.9% of the time, how often can a W = 2 write actually succeed, compared with W = 3? Work it out by hand.

W = 2 can act 99.9997% of the time, which is about 8 seconds of refusals a month. W = 3 can act only 99.70% of the time: 131 minutes a month, the same number as the three-link chain in section 10. One spare replica is the whole difference.

Each of the three replicas is either up or down at any moment, so there are 2 × 2 × 2 = 8 possible moments. The method has two parts. Work out how likely each moment is. Then add up the moments in which enough replicas are up. Below, U means up and D means down, in the order node 1, node 2, node 3.

  1. One replica. Up with probability 0.999, down with probability 0.001. That 0.001 is 43.83 minutes of the 43,830-minute month from section 10.
  2. All three up (UUU). 0.999 × 0.999 × 0.999 = 0.997002999. Multiplying is allowed only if the replicas fail independently: one crashing makes another no more likely to crash.
  3. Exactly one down. UUD is 0.999 × 0.999 × 0.001 = 0.000998001. The down replica can be any of the three (UUD, UDU or DUU), so the total is 3 × 0.000998001 = 0.002994003.
  4. Exactly two down. UDD is 0.999 × 0.001 × 0.001 = 0.000000999. Three arrangements again, so 3 × 0.000000999 = 0.000002997.
  5. All three down (DDD). 0.001 × 0.001 × 0.001 = 0.000000001. Check the work: 0.997002999 + 0.002994003 + 0.000002997 + 0.000000001 = 1, so no moment was missed.
  6. Add up what each setting needs. W = 3 can act only in moment B: 0.997002999. W = 2 can act in B or C: 0.997002999 + 0.002994003 = 0.999997002. W = 1 can act in every moment except E: 0.999999999.
  7. Turn the rest into time. Multiply the share it cannot act by 43,830 minutes. W = 3: 0.002997001 × 43,830 = 131.36 minutes. W = 2: 0.000002998 × 43,830 = 0.1314 minutes, which is 7.88 seconds. W = 1: 2.63 milliseconds.
Three settings for one key on three replicas, each replica up 99.9% of the time, from quorum_by_hand.py
SettingCan act inShare of time it can actRefuses per month
W = 3: all three replicasUUU only0.997003 (99.70%)131.36 minutes, about 2 h 11 min
W = 2 or R = 2: any twoUUU, or any one down0.999997 (99.9997%)7.88 seconds
W = 1: any oneanything but DDD0.9999999992.63 milliseconds

A read with R = 2 needs the same "any two" as a W = 2 write, so the middle row is the read path too. That is why W = 2, R = 2 is the balanced default in the hood block: it keeps both reads and writes working with one replica down.

The W = 3 row is not a coincidence either. Waiting for all three replicas is a chain in series, where every link must be up. So it gives the 131.36 minutes of the three-link chain in section 10, and the "about 26 hours a year" of the W = N arithmetic (26.27 hours, measured).

Fig. A2.4j draws the eight moments on the left and what each setting refuses on the right, on a log scale.

EIGHT MOMENTS OF THREE REPLICAS, EACH UP 99.9% OF THE TIME 1 HOW LIKELY EACH MOMENT IS 3 up 0.997002999 2 up 3 × 0.000998001 = 0.002994003 1 up 3 × 0.000000999 = 0.000002997 0 up 0.000000001 the four rows add up to exactly 1: no moment is missing up down 2 REFUSED PER MONTH · LOG SCALE 131.36 minutes · up 99.70% W = 3 · all 3 7.88 seconds · up 99.9997% W = 2 · any 2 2.63 milliseconds · up 99.9999999% W = 1 · any 1 1 ms 1 s 1 min 1 h 3 W = 3 is a chain: every replica must be up all of it assumes independent failures
Fig. A2.4j — Quorum uptime, added up by hand. Left: the eight moments of three replicas, grouped by how many are up. Right: how long each setting refuses to act in a 43,830-minute month, on a log scale so that seconds and hours fit on one line. Values from rerunning quorum_by_hand.py.
  1. The eight moments. Each row groups the moments with the same number of replicas up; a filled dot is up and a hollow red dot is down. "One down" happens three ways, so its probability is counted three times. The four rows add up to exactly 1, which is how you know no moment was missed.
  2. What each setting needs. W = 3 can act only in the top row, so it refuses 131.36 minutes a month. W = 2 can act in the top two rows and refuses 7.88 seconds. W = 1 refuses only when all three are down: 2.63 milliseconds. The scale is logarithmic, so a bar about twice as long means a thousand times more refusal.
  3. The chain in disguise. Requiring all three replicas is the three-link chain of section 10: 0.999 × 0.999 × 0.999 = 0.9970. Every number here assumes the replicas fail independently. A shared rack, a shared deploy or a network partition breaks that assumption.

The honest limit is that word "independently". Replicas that share a rack, a power feed or a deploy pipeline go down together, so "one down" can really be "all three down". Marker 4 of Fig. A2.5b makes the same point about redundant pairs.

And a network partition is not a replica failure at all. Every replica is up, but a client that can reach only one of them sees "one up" for as long as the split lasts. W = 2 refuses that client every time. The next question walks one write through exactly that.

A quorum of two out of three needs only the moments with at most one replica down, so it keeps almost none of each replica's downtime. Requiring all three turns the replicas into a chain and multiplies their downtimes.

Is "consistency" in CAP the same thing as the C in ACID, or as "eventual consistency"? And what does choosing C or A actually do to one write?

No. Three different ideas share one word, as the first table shows. During a partition, choosing C refuses user 42's phone outright; choosing A accepts both of their photos, then silently erases one when the network heals.

The word "consistency" is used for three unrelated promises. Interviewers notice when a candidate blends them, so separate them first.

Three different things called consistency, each shown with user 42's photo
NameThe promise, in plain wordsWho keeps itWith the photo
CAP's C: linearizable, the "strong" row of the consistency table in section 06Every read acts as if there were one copy. Once a write is confirmed, no later read anywhere returns something older.The storage system, across all its replicasOnce photo-B is confirmed, no friend sees photo-A again
ACID's CA transaction takes the data from one valid state to another. "Valid" means your own rules, such as a balance that never goes below zero.Your application, with the database's constraints helpingA photo row can never point at an upload that failed
Eventual consistencyIf writes stop, all replicas end up holding the same value. It says nothing about which value, or how soon.Background repair between replicasAfter the network heals, all three replicas hold one photo, though maybe not the one you set last

CAP's A needs its plain meaning too: every request that reaches a working replica gets an answer that is not an error. The CAP choice is between that A and the first row's C, and it only has to be made while the network is split.

One write, walked through a partition

Here is the trace from partition_one_write.py. At t = 500 ms a switch fails. Node 1 is cut off on its own, while nodes 2 and 3 can still reach each other. User 42's phone can reach only node 1. Their laptop, on another network, reaches nodes 2 and 3.

Disagreements are settled by last-write-wins: when two versions differ, keep the one with the larger timestamp and discard the other. Cassandra uses this rule. Each write is stamped by the clock of the replica the client talked to.

The same five events under two settings, from partition_one_write.py
TimeEventRefuse on the small side (W = 2, R = 2)Answer on both sides (W = 1, R = 1)
1,000 msPhone sets photo-BRefused: reaches 1 replica, needs 2. Nothing stored.OK: stored on node 1, timestamp 1,000
1,200 msLaptop sets photo-COK: stored on nodes 2 and 3, timestamp 1,200OK: stored on nodes 2 and 3, timestamp 1,200
1,500 msA friend reads through node 1Refused: reaches 1 replica, needs 2Answers photo-B
1,500 msA friend reads through node 2Answers photo-CAnswers photo-C
5,000 msSwitch repaired; last-write-winsAll three hold photo-CAll three hold photo-C
Result1 write and 1 read refused; no confirmed write lostNothing refused; photo-B was confirmed, then erased

The left column is the consistency side: the phone gets an error, and nothing it was told is ever taken back. The right column is the availability side: everyone gets an answer, two friends see different photos at the same moment, and the confirmed photo-B vanishes at the repair.

The right column hides one more trap. Rerun it with node 1's clock 300 ms fast, and photo-B is stamped 1,300 instead of 1,000. Last-write-wins now keeps photo-B and erases photo-C, the write that really came last. Nobody is told.

Fig. A2.4k puts both columns on one picture of the split.

1 REFUSE ON THE SMALL SIDE · W = 2, R = 2 node 1 photo-A node 2 photo-C node 3 photo-C phone laptop sets photo-B, 1.0 s sets photo-C, 1.2 s phone's write: REFUSED, nothing stored laptop's write: OK on nodes 2 and 3 read through node 1: REFUSED read through node 2: photo-C 2 ANSWER ON BOTH SIDES · W = 1, R = 1 node 1 photo-B node 2 photo-C node 3 photo-C phone laptop sets photo-B, 1.0 s sets photo-C, 1.2 s phone's write: OK on node 1, stamped 1,000 laptop's write: OK on nodes 2 and 3, stamped 1,200 read through node 1: photo-B read through node 2: photo-C 3 AFTER THE SWITCH IS REPAIRED · LAST-WRITE-WINS all three hold photo-C confirmed writes lost: 0 the price: 1 write and 1 read refused all three hold photo-C photo-B was confirmed, and is now gone node 1's clock 300 ms fast: photo-C is erased instead
Fig. A2.4k — One partition, two settings. The dashed line is the failed switch: nothing crosses it. Left: a strict quorum refuses whoever cannot reach two replicas. Right: any single replica answers, so the two sides drift apart until the repair. Values from rerunning partition_one_write.py.
  1. Refuse on the small side. The phone's replica, node 1, can reach one replica and needs two, so it refuses before storing anything. A friend reading through node 1 is refused too. Nodes 2 and 3 are a majority and keep working, so the laptop's photo-C is stored and confirmed.
  2. Answer on both sides. Every write needs only one replica, so node 1 accepts photo-B and nodes 2 and 3 accept photo-C. Both devices are told OK. For the rest of the split, the photo a friend sees depends on which replica they happen to reach.
  3. The repair. Last-write-wins keeps the larger timestamp. On the right that erases photo-B, which the phone was told had been saved. With node 1's clock 300 ms fast the stamps swap, and the later photo-C is erased instead. On the left there is nothing to erase, because the refused write was never stored.

Two honest limits come with the left column:

  • It is the consistency side, not full CAP consistency. The write-in-flight trace in the first question of this block shows a quorum read going backwards in time.
  • The clean refusal needs node 1 to know it is cut off. If the split has not been detected yet, the phone's write times out instead, and it may stay on node 1 without being undone.

Not every available store settles conflicts by erasing one version. Amazon's Dynamo kept both and asked the application to merge them: the shopping cart in marker 3 of Fig. A2.6c, with its resurrected items.

CAP's C means reads never go back in time across copies; ACID's C means your own data rules hold. During a partition, C refuses whoever cannot reach a majority, and A answers everyone and pays later, sometimes by erasing a write it confirmed.

Say it in the room: "Partition tolerance isn't optional — the real question is what we do during a partition, and I'd answer it per data class: CP for the money path, AP with reconciliation for engagement counters. In healthy operation the same dial is latency vs consistency — PACELC."

07 · Refresher 5Queues & Streams — Async Is a Contract

Reads are cached, writes are replicated, and the redirect path is fast. What is left is the slow work — click counts, emails, analytics — and none of it belongs between the user and their answer. A queue moves it off the path and charges you three new failure modes in exchange. Anand needs all three named, because "we'd use a queue" with no delivery semantics is the same half-answer that lost him round three.

A queue between two services buys three things:

IN 1,000 A SECOND · OUT 800 A SECOND · THE DIFFERENCE PILES UP IN THE MIDDLE 1 the API 1,000 msgs/s in: 1,000/s 2 the queue backlog 720,000 out: 800/s 3 the workers 800 msgs/s 4 1,000 in − 800 out = the backlog grows by 200 messages every second an hour of that is 720,000 messages waiting — and not one caller saw an error workers all die → out = 0, the queue still takes 1,000/s, the API still answers
Fig. A2.4b — What a queue actually does with the difference between two rates. Producer 1,000 a second, consumers 800 a second: the gap does not become an error, it becomes a backlog, and consumer lag is the number you alarm on.
  1. The producer, marker 1. The API writes a message and returns to the user immediately. Its latency no longer depends on how slow the work is, which is the whole point. This is also where "accepted" stops meaning "done".
  2. The buffer, marker 2. The queue holds whatever the consumers have not taken yet. It is memory or disk, and it is finite: at 200 messages a second of growth, an hour is 720,000 messages. The shaded part is the backlog, and its size in time — "we are 14 minutes behind" — is the number people understand.
  3. The consumer, marker 3. Workers pull at whatever rate they can manage. Add workers and the drain rate rises; at 1,200 a second the same backlog clears at 400 a second, so 720,000 messages take about 30 minutes to work off. That is the lever an on-call engineer actually pulls.
  4. Why it is worth it, marker 4. If the consumers die completely, the queue keeps accepting and the user-facing API stays up. Without the queue, the API would have to do the work inline and would fall over instead. You are buying uptime for the caller with delay for the work.

"Isn't a message queue just a slower function call with worse stack traces?"

— the same engineer, who has debugged a Celery task at 2 a.m.

On the happy path, yes. A message goes in, a worker does the work, the result appears later. If that were the whole story, a function call would win. It is faster, it returns a value, and an exception lands in the caller's hands with a stack trace attached. The difference is entirely in the unhappy path, and the unhappy path is what this appendix is about.

A function call has one failure mode: the callee throws, and the caller knows immediately. A queue keeps working when the worker is dead. Marker 2 of Fig. A2.4b is that difference drawn: 720,000 messages parked in the middle after an hour, and not one caller told about it. Marker 4 is the same picture with the consumers at zero — the API still answers. Those are the three properties above; no function call has any of them. The email service being down for ten minutes is invisible only because the queue exists.

The downside you are sensing is real, and marker 1 of Fig. A2.4b is where it starts: the API returns before the work is done. A queue turns a synchronous error into an eventual one, so the user sees "accepted" and the failure surfaces in a dead-letter queue twenty minutes later. Debugging now crosses a process boundary and a broker. You also own delivery semantics now: an idempotency table, a lag alarm, and a poison-message policy. When the caller needs the answer to continue, a function call is still the right tool.

The price is delivery semantics — which is where interviews separate people who have used queues from people who have been burned by them:

Delivery guarantees — and what they demand of the consumer
GuaranteeMeaningDemandsUse for
At-most-onceFire and forget; crashes drop messagesNothingMetrics, telemetry — loss is cheaper than dedup
At-least-onceRedeliver until acknowledged; crashes duplicate messagesIdempotent consumersThe default for anything that matters
"Exactly-once"A myth at the transport level — some failure timing always forces a choiceAt-least-once + idempotency, end to endWhat you claim after building the row above correctly

So the load-bearing skill is idempotency: design every consumer so processing a message twice equals processing it once. The tool is an idempotency key — a unique ID per logical operation (Stripe-style Idempotency-Key header, an order UUID); the consumer records handled keys and skips repeats.

1 AT-LEAST-ONCE DELIVERY, NO IDEMPOTENCY KEY delivery 1 delivery 2 (retry) consumer INSERT order · $38 INSERT order · $38 2 rows in the orders table the customer was charged $76 and every line of that code is correct 2 SAME TWO DELIVERIES, ONE IDEMPOTENCY KEY delivery 1 delivery 2 (retry) consumer keys seen: ord-8f3a new key → charge $38 key seen → do nothing 1 row in the orders table the customer was charged $38 delivery 2 returns delivery 1's answer
Fig. A2.4c — Idempotency in one picture. The redelivery is not a bug you can remove; at-least-once guarantees it will happen. The key is what makes the second arrival harmless, and the order value is the $38 average order from this appendix's boardroom arithmetic.
  1. Why there are two deliveries, marker 1. The worker processed the message and then crashed before acknowledging it, or its acknowledgement was lost. The broker has no way to tell "done but unacknowledged" from "never done", so it redelivers. Both outcomes look the same from outside.
  2. What it costs without a key, marker 1. The consumer has no memory, so the second delivery repeats the whole side effect: another row, another $38. Nothing in that code is wrong; the fault is that the operation was never defined as "happens once".
  3. The key, marker 2. A unique id per logical operation — the order's UUID, or Stripe's Idempotency-Key header — travels with the message. The consumer records the keys it has completed, inside the same transaction as the work. Delivery 2 finds the key already there and returns the stored answer instead of repeating anything.
  4. The honest limit. The keys table is a real table: it needs an index, a retention policy, and it must be written in the same transaction as the effect it guards. Write the key in a separate step and you have rebuilt the dual-write bug that the next figure is about.

Its sibling is the outbox pattern, which fixes the dual-write bug: "write the DB, then publish the event" can crash in between, leaving the two stores disagreeing forever.

Instead, write the business row and the event into an outbox table in one local transaction; a relay tails the outbox and publishes. The transaction makes write-plus-publish atomic, the relay makes delivery at-least-once, your idempotent consumer absorbs the duplicates. That trio is the whole answer.

1 DUAL WRITE — TWO STORES, NO SHARED TRANSACTION the app 1 · INSERT database order row committed 2 · publish message broker event never arrives the process dies between step 1 and step 2 the order exists and its event does not nothing will ever notice or repair the gap 2 OUTBOX — ONE TRANSACTION, THEN A RELAY the app one transaction order row + outbox row tail the relay publish message broker 3 a crash now leaves the outbox row waiting, so the relay publishes it later — possibly twice
Fig. A2.4d — The outbox. The dual write has a window between two stores that no amount of care removes; the outbox closes it by making the event part of the same transaction as the row, and hands the delivery problem to a relay that can retry forever.
  1. The window, marker 1. Writing the database and then publishing the event are two operations on two systems. A crash, a network blip or a broker timeout in between leaves the order saved and the event lost, and no retry can fix it afterwards because the app has forgotten what it was doing.
  2. One transaction, marker 2. The app writes the business row and an outbox row together. Either both are committed or neither is, because they are rows in the same database. The event is now as durable as the order itself.
  3. The relay, marker 3. A separate process reads unpublished outbox rows, publishes them, and marks them sent. If it dies mid-flight, the row is still unmarked and it publishes again on restart. That is at-least-once delivery, which is exactly what the idempotency key in the previous figure is there to absorb.

Distinguish the two queue species. Task queues (SQS, RabbitMQ, Celery) distribute jobs: a message is consumed, acknowledged, gone.

Log-based streams (Kafka) are different physics: an append-only log per partition; consumers just advance an offset, so data outlives consumption — multiple consumer groups read the same stream independently, and replay is "rewind the offset": reprocess last week after a bug fix, or bootstrap a new service from history.

Ordering holds only within a partition, so the partition key is an ordering decision.

Finally, say backpressure: producers outrunning consumers shows up as consumer lag — the metric to alarm on — and poison messages go to a dead-letter queue after bounded attempts, so one bad message can't wedge the pipeline.

Say it in the room: "At-least-once delivery with idempotent consumers keyed on an idempotency key; DB-write-plus-publish goes through an outbox so they're atomic; Kafka if multiple readers or replay matter, a task queue if it's just work distribution; lag alarms and a DLQ so poison messages can't wedge the pipeline."

08 · Refresher 6Resilience — Designing for the Bad Day

Anand's debrief line was "strong AI, inconsistent fundamentals", and this is the section where the fundamentals are most often recited wrong. Every box on the map calls another box, and every one of those calls can hang instead of failing. Five tools answer that: a timeout, a retry with backoff and jitter, a budget, a breaker, and a degraded mode chosen in advance. You built all five once already, as Module 12's LLM gateway; here they are in their general form, drawn with numbers.

You have already built this section once in this course: Module 12's LLM gateway — timeouts, retry budget, per-provider circuit breakers, fallback, graceful degradation — is this section, applied to model providers. Here's the general form, which the classic round expects you to recite about any dependency.

Timeouts everywhere. A call without a timeout is a thread donated to a dead dependency; enough of them and a slow downstream has taken you down without "failing" once.

Every hop gets a deadline, and deadlines propagate — if the user gave you 2 s and 1.4 s are spent, the downstream call gets 600 ms, not its default.

1 ONE CALL, ONE RETRY — WHAT THE USER ACTUALLY WAITS attempt 1 · hangs · timeout fires at 500 ms backoff + jitter attempt 2 · succeeds in 40 ms 0 200 ms 400 ms 600 ms 800 ms the user waited 640 ms for a call that normally answers in 40 ms retries do not make the average worse; they make the slowest 1% much worse 2 DEADLINE PROPAGATION — THE USER GAVE YOU 2 SECONDS spent: gateway 200 + auth 300 + search 900 = 1,400 ms 600 ms left so the next call gets a 600 ms timeout, not the client library's default of 30 seconds
Fig. A2.4e — A timeout and its retry, drawn on the clock. The retry rescues this request and costs it 600 extra milliseconds, which is where slow-percentile latency comes from. Below it, the 2-second budget the user granted, minus what has already been spent, is the only correct timeout for the next hop.
  1. The cut, marker 1. The dependency has not failed; it is hanging. Without a timeout this request holds a thread until the dependency comes back, and a few thousand of those take your service down without a single error being logged. The 500 ms timeout converts "hung" into "failed", which is the only state a retry can act on.
  2. The gap, marker 1. Backoff waits before retrying, and jitter randomises the wait so a thousand clients do not all retry in the same millisecond. Here it costs 100 ms. That gap is what stops the retry from arriving while the dependency is still on the floor.
  3. The bill, marker 1. Total 640 ms against a normal 40 ms. The average is barely affected because most requests never retry, but the slow 1% is now sixteen times slower, which is why retries and percentile latency targets have to be designed together.
  4. The budget, marker 2. A deadline is not a per-call setting, it is a shrinking quantity that travels with the request. Every hop subtracts what it used and passes the remainder down. Skip this and a downstream call happily waits 30 seconds for a request whose caller gave up 28 seconds ago, doing work nobody will read.

Retries with exponential backoff + jitter. Retry only idempotent operations; back off exponentially; add jitter, because a thousand clients retrying on the same schedule is a synchronized battering ram — the classic retry storm that turns a 10-second blip into an hour-long outage.

Cap it with a retry budget (retries ≤ 10% of traffic) so retries can't multiply load exactly when load is the problem.

Sharpen your pencil

Put numbers on the battering ram once and the phrase "retry budget" stops sounding like paperwork. Suppose 1,000 clients each send one request per second to a dependency that can serve 1,500 requests per second. The dependency stalls for ten seconds. Every client runs the same code: on failure, retry immediately, up to three times. Fill in the blanks.

Normal load: 1,000 clients × 1 request/s1,000 requests/s, which is 67% of the 1,500 capacity
Requests one client sends per second during the stall (the original plus its retries)
Load arriving at the dependency during the stall
That load as a multiple of capacity, at the instant the dependency comes back
Worst-case load if retries are capped at 10% of traffic (the retry budget)
What exponential backoff with jitter buys, if there is no budget
Check your answers
Requests per client per second4: one original and three immediate retries, every second, because every one of them fails
Load during the stall1,000 × 4 = 4,000 requests/s, against a service that is not answering
Multiple of capacity on recovery4,000 ÷ 1,500 = 2.67×. The dependency wakes up already drowning, times out, and every timeout is counted as a failure and retried. The ten-second stall now has no end date. That is a retry storm
With a 10% retry budget1,000 + 100 = 1,100 requests/s, which is 73% of capacity. The dependency recovers on its first try
What backoff and jitter buyShape, not height. Retries at 1 s, 2 s and 4 s spread the load so a short blip is over before most retries fire, and jitter stops 1,000 clients retrying in the same millisecond. But if the stall outlasts the schedule, a client that keeps sending new requests still reaches 4 per second. Only the budget caps the multiplier

The three tools do three different jobs, and the interviewer wants all three named. Backoff and jitter shape the wave. The budget caps its height. Idempotency makes retries safe to send at all: a retried payment without an idempotency key is a second payment. One caveat: the arithmetic assumes clients keep producing new work at the same rate while they retry. A caller that blocks until its retry resolves multiplies less.

Fig. A2.4f is that table as a picture: the same three numbers you just worked out, drawn against the capacity line they have to stay under.

1 1,000 CLIENTS · A DEPENDENCY THAT SERVES 1,500 A SECOND capacity 1,500 req/s 1,000 req/s normal 67% of capacity 2 4,000 req/s storm: 1 try + 3 retries 2.67× capacity 3 1,100 req/s 10% retry budget 73% of capacity 4 backoff and jitter change the shape of the wave; only the budget changes its height
Fig. A2.4f — The retry storm, to scale, with the pencil exercise's own numbers: 1,000 clients × 4 attempts = 4,000 requests a second against a dependency that serves 1,500. A 10% retry budget keeps the same failure at 1,100, which the dependency can answer on its first try back.
  1. The healthy day, marker 1. A thousand clients at one request a second is 1,000 a second, comfortably inside the 1,500 the dependency can serve. Everything about this system is fine until something stalls for ten seconds.
  2. The storm, marker 2. Every failure turns one request into four, so the offered load quadruples to 4,000 a second — 2.67 times capacity — precisely while the dependency is least able to cope. When it recovers it is instantly overwhelmed, times out again, and every timeout is retried. The stall now has no end date, and you did it to yourself.
  3. The budget, marker 3. A retry budget caps retries at a fraction of real traffic, here 10%. Offered load during the same stall is 1,100 a second, still under the line, so the dependency recovers on its first attempt. It is one number in a client library and it is the difference between a blip and an outage.
  4. What backoff is for, marker 4. Spreading retries over 1 s, 2 s and 4 s means most of them never fire at all if the stall is short, and jitter stops a thousand clients retrying in the same millisecond. Neither caps the total. Backoff shapes the wave; the budget sets its height; idempotency is what makes sending any retry safe.

Questions you might be asking now

The pencil exercise and Fig. A2.4f name three tools with three jobs: idempotency makes a retry safe, backoff and jitter shape the wave, and the budget caps its height. The answers below slow each claim down, and add the latency cost behind Fig. A2.4e. All of them use the same retry policy and the same $38 order.

The retry policy every answer below uses. Every number except the jitter rule is one this page has already used.
SettingValueWhere it comes from
The requestCharge $38 for order ord-8f3a, sent with the idempotency key ord-8f3aFig. A2.4c
One attemptA normal reply takes 40 ms; the client gives up after 500 msFig. A2.4e
RetriesUp to 3, after waits of 100, 200 and 400 ms: each wait doublesFig. A2.4e's 100 ms gap, doubled
JitterFull jitter: wait a random time between 0 and that number insteadNew in these answers
The fleet1,000 clients; a dependency that serves 1,500 requests a second; retries capped at 10%The pencil exercise and Fig. A2.4f
Is a retry safe? Walk one $38 payment through a timeout, a retry and an idempotency key.

Only if the server can tell that the retry is the same payment. In the run below the card is charged but the reply is lost; the retry carries the same key, gets the stored answer, and the customer pays $38 once. Without a key, or with a new key on each try, the same retry charges $76.

A timeout tells the client exactly one thing: no answer arrived within 500 ms. It does not say which of these happened on the server:

  • The request never arrived, so nothing was charged.
  • The server charged the card, and the reply was lost on the way back.
  • The server is still working, and will charge the card after the client has given up.

From the client's side all three look the same, so a retry has to be safe in all three. Here is the second case, step by step, as payment_retry_trace.py prints it.

  1. t = 0 ms: send the charge. The client sends POST /charge with the header Idempotency-Key: ord-8f3a. The server records the key and charges the card in one transaction, which commits at t = 180 ms as charge ch_1.
  2. The reply is lost. A network hop drops it. The server believes it answered.
  3. t = 500 ms: the timeout fires. The client knows nothing about ch_1. It only knows it has no answer.
  4. Wait a jittered backoff. The first backoff is 100 ms, so the client draws a random wait between 0 and 100 ms. This run drew 63.9 ms.
  5. t = 563.9 ms: retry with the same key. The server finds ord-8f3a already completed, so it does not charge again. It replays the answer it stored: ch_1.
  6. t = 603.9 ms: done. One charge, $38. The customer waited 603.9 ms instead of the normal 40.

The table runs all three failure cases three ways, with the same random waits, so the only difference between columns is the key.

Charges made for one $38 order, measured by payment_retry_trace.py
What went wrong with attempt 1Same key on every tryNo keyA new key on each try
Reply lost; the card was charged at 180 ms1 charge, $38; answer at 603.9 ms2 charges, $762 charges, $76
Server slow; the card is charged at 700 ms1 charge, $38; two 409s, answer at 1,059.5 ms2 charges, $762 charges, $76
Request never arrived1 charge, $381 charge, $381 charge, $38

The last column is the bug that ships most often. The code has a key, but creates it inside the retry loop, so every attempt looks like a new payment. The key belongs to the order: created once, before the first attempt, and sent unchanged on every retry.

The slow row needs one more rule. The retry arrives at 563.9 ms, while ch_1 is still being charged. The key is there but marked "in progress", so the server must not start a second charge. It answers 409 Conflict, as Stripe does. The client backs off, gets a second 409 at 729.8 ms, and receives the stored ch_1 on its last retry.

ONE $38 ORDER · THE SAME 500 ms TIMEOUT · WHAT THE SERVER DOES WITH THE RETRY 1 same key reply lost card charged: ch_1 at 180 ms attempt 1 · no reply wait 63.9 retry, same key → stored ch_1 1 charge · $38 2 no key reply lost card charged: ch_1 at 180 ms attempt 1 · no reply wait 63.9 retry, no key → new charge ch_2 2 charges · $76 3 same key server slow card charged: ch_1 at 700 ms attempt 1 · no reply 409 409 stored ch_1 1 charge · $38 at 1,059.5 ms 0 ms 250 500 750 1,000 ms 4 the client sees the same 500 ms of silence in every row; only the key tells the server it has seen this order
Fig. A2.4l — One payment, three runs, on one clock. The grey gaps are jittered waits, the same random draws in every row. The dots above each row mark the moment the card is really charged, which the client never sees. Values from rerunning payment_retry_trace.py.
  1. Same key, reply lost. The card is charged at 180 ms and the reply is lost. After the 500 ms timeout and a 63.9 ms wait, the retry carries ord-8f3a, and the server replays ch_1. One charge.
  2. No key. The client does exactly the same, down to the 63.9 ms wait. The server cannot connect the retry to ch_1, so it charges again: ch_2, $76 in total. A new key on each try gives this row too.
  3. Same key, server still working. Retries at 563.9 and 689.8 ms find the key "in progress" and get 409s; the charge commits at 700 ms. The last retry allowed gets the stored ch_1. One charge.
  4. What the client cannot see. The 500 ms of silence looks identical in every row, so the client's one action, the retry, must be harmless in every row. The key is what makes it harmless.

Marker 3 of Fig. A2.4l also shows the honest limit: the retry that worked was the last one allowed. With a slightly slower charge, the client would have reported a failure for a payment that went through. Running out of retries should mean "outcome unknown, check the order later", not "failed".

The key also protects only while the server remembers it. Stripe may delete a key once it is 24 hours old, and a retry after that is a new payment. And, as the last key under Fig. A2.4c says, the key must be written in the same transaction as the charge.

A timeout means "I don't know", not "it failed". Retry only with the key the first attempt carried, so the server can recognise a payment it has already made.

What does exponential backoff with jitter actually do when 1,000 clients fail at the same moment? Show me.

It changes when the retries arrive, and hardly how many. After a 250 ms outage, lockstep backoff gets 30 of 1,000 requests served; full jitter gets 497 served with almost the same number of retries. After a 10-second outage, every schedule serves nobody.

Two terms first. Exponential backoff means each wait before a retry is double the last one: 100, then 200, then 400 ms. Full jitter means the client does not wait exactly that long. It picks a random wait between 0 and that number, so no two clients are likely to pick the same moment.

The simulation in backoff_jitter_sim.py keeps the setup small enough to check:

  • At t = 0 a dependency stops answering, and 1,000 requests in flight fail together. The failures are fast, like a refused connection, so only the waits decide when retries fire.
  • At 250 ms it is back. It then serves at most 15 requests in any 10 ms, which is the pencil exercise's 1,500 a second. The rest of those 10 ms fail and are retried.
  • Each request may retry up to 3 times.

The lockstep schedule, backoff with no jitter, can be done by hand:

  1. t = 0 ms. All 1,000 requests fail. Every one of them waits exactly 100 ms.
  2. t = 100 ms. 1,000 retries arrive together. The dependency is still down, so all fail. All wait 200 ms.
  3. t = 300 ms. 1,000 retries arrive inside the same 10 ms. The dependency is up: it serves 15 and fails 985. Those wait 400 ms.
  4. t = 700 ms. 985 retries arrive together. 15 are served. The other 970 have used all three retries, so they give up.
  5. Count. Served: 15 + 15 = 30. Attempts: 1,000 + 1,000 + 1,000 + 985 = 3,985.

Full jitter cannot be done by hand, because every wait is random. The simulation runs it with a fixed seed, so the numbers repeat. Here are all three schedules side by side.

1,000 requests that fail together, three retry schedules, measured by backoff_jitter_sim.py
ScheduleAttempts (of which retries)Most retries inside one 10 msServedGave upThe same, after a 10 s outage
Retry at once, 1 ms apart4,000 (3,000)3,00001,0004,000 attempts, 0 served
Backoff: 100, 200, 400 ms3,985 (2,985)1,000309704,000 attempts, 0 served
Full jitter: random 0–100, 0–200, 0–400 ms3,970 (2,970)1664975034,000 attempts, 0 served
1,000 REQUESTS FAIL AT t = 0 · THE DEPENDENCY IS BACK AT 250 ms · RETRIES PER 50 ms 1 at once dependency down 3,000 retries in 3 ms (bar cut off) most it can serve after 250 ms: 75 per 50 ms 4,000 attempts · most retries in one 10 ms: 3,000 · served 0 · gave up 1,000 2 backoff lockstep 1,000 all fail 1,000 15 served 985 15 served 3,985 attempts · most retries in one 10 ms: 1,000 · served 30 · gave up 970 3 full jitter random waits 519 746 served at full capacity from 250 to 450 ms 0 ms 250 500 750 ms 3,970 attempts · most retries in one 10 ms: 166 · served 497 · gave up 503 4 after a 10-second outage all three send 4,000 attempts and serve 0: the shape changed, the height did not
Fig. A2.4m — The same 1,000 failures retried on three schedules, drawn as retries per 50 ms. The shaded strip is the outage and the dashed line is what the recovered dependency can serve; the green fill in the bottom panel is what it did serve. The bars share one scale except the cut-off bar in panel 1. Values from rerunning backoff_jitter_sim.py.
  1. Retry at once. All 3,000 retries fire in the first 3 ms, while the dependency is still down, so every one fails. By the time it recovers at 250 ms, nobody is left to serve. This is the pencil exercise's storm, squeezed into one instant.
  2. Lockstep backoff. The retries now come as three waves of about 1,000, at 100, 300 and 700 ms, each inside a single 10 ms. The first wave hits the outage. The other two hit a working server that can take 15 of them each. Backoff moved the waves in time but kept them as waves.
  3. Full jitter. The same retries, each at a random moment. No 10 ms holds more than 166. From 250 to 450 ms the server works at its full 75 per 50 ms, and in the last buckets every retry that arrives is served. 497 served, from the same outage.
  4. What did not change. Total attempts stayed near 4,000 in every panel. Stretch the outage to 10 seconds and all three schedules fire every retry into it and serve nobody. Shaping the wave does not shrink it.

Read the table and the picture as this page's own phrase, "shape, not height". Height: the three attempt counts differ by 30 out of about 4,000. Shape: the biggest pile of retries inside one 10 ms falls from 1,000 to 166. So from 250 to 450 ms the recovered dependency serves its full 75 every 50 ms (marker 3 in Fig. A2.4m), instead of 15 once and then nothing.

The honest limits of this run:

  • The 497 depends on the random draws. Ten different seeds gave between 481 and 509 served.
  • Jitter creates no capacity. 503 requests still ran out of retries; the last retry fired at 666 ms.
  • Real servers degrade when flooded. This model fails the extra requests cleanly. A real server slows down instead, so real lockstep waves do more harm than shown here.

The table's last column is the cue for the next question. A 10-second outage outlasts every schedule, so each fires all 3,000 retries into a dead dependency. Only a cap on the number of retries changes that.

Backoff spaces the waves out; jitter breaks each wave into a trickle the recovered server can actually serve. Neither sends fewer retries into a long outage. That is the budget's job.

How does "retries ≤ 10% of traffic" actually work in code? Where does the 10% get counted?

It is a token counter inside the client library. Every request earns a tenth of a token and every retry must spend a whole one, so retries cannot run ahead of a tenth of real traffic for long. In a 10-second stall it turns 4,000 attempts a second into 1,100, after a first second of 1,199.

It is the token bucket from section 09, pointed at your own retries instead of at a customer's requests. Three rules make it:

  • Earn. Every request the service sends adds 0.1 token. 1,000 requests a second earn 100 tokens a second.
  • Spend. A retry may go out only if a whole token is there to spend. With no token, the error goes straight back to the caller.
  • Cap. At most 100 tokens can be saved, one second of earnings, so a quiet hour cannot fund a storm later.

Finagle, the RPC library that came out of Twitter, ships a RetryBudget built this way. Its setting percentCanRetry = 0.1 means one retry for every ten requests.

Now one stalled second by hand. The calling service sends 1,000 requests, every attempt fails, and without a budget each request would be tried 4 times.

  1. Tokens at the start: 100. In the healthy seconds before, the service earned 100 a second and spent only 10, because 1 request in 100 failed once. So the counter sat at its cap.
  2. Tokens earned this second: 1,000 × 0.1 = 100. The very first deposit is wasted, because the counter is already full. So 99.9 tokens are actually added.
  3. Retries it can pay for: 199. 100 saved + 99.9 earned = 199.9 tokens, which is 199 whole tokens.
  4. Attempts this second: 1,199. 1,000 first tries + 199 retries. That is 0.80 of the 1,500 the dependency can serve.
  5. Every later stalled second: 1,100. Nothing is saved any more, so 100 tokens earned pay for 100 retries: 0.73 of capacity. The counter hovers just under one token.
  6. Without the counter: 4,000. 1,000 × 4 attempts a second, 2.67 times capacity, for all ten seconds.
The stall second by second, measured by retry_budget.py (seconds 16 to 19 repeat second 17's healthy row)
SecondWhat is happeningAttempts, no budgetAttempts, with the budgetRetries sentRetries refusedTokens at the start
0Healthy; the counter starts empty1,0101,009910.0
1Healthy; 1 request in 100 fails once1,0101,01010091.0
2–4Healthy; the counter is full1,0101,010100100.0
5The stall begins4,0001,199199966100.0
6–14Still stalled4,0001,1001001,0000.9
15Healthy again1,0101,009910.9
1,000 REQUESTS A SECOND · ATTEMPTS PER SECOND · THE DEPENDENCY STALLS IN SECONDS 5 TO 14 1 NO BUDGET · EVERY FAILURE RETRIED 3 TIMES 1,010 a second 4,000 a second: 2.67× capacity capacity 1,500 a second 2 WITH A 10% RETRY BUDGET · SAME STALL, SAME RETRY POLICY capacity 1,500 a second 1,199: the 100 saved tokens 1,100 a second for the other nine second 0 5 10 15 19 shaded: the stall, seconds 5 to 14 3 over the stall: 40,000 attempts without the budget, 11,099 with it; retries were 11.0% of requests, not 10.0%
Fig. A2.4n — The retry budget, second by second. Both panels use the same scale and the same 1,500-a-second capacity line. Only the counter differs: every request earns 0.1 token, every retry spends 1, and at most 100 tokens are saved. Values from rerunning retry_budget.py.
  1. No budget. Every failure is retried three times, so 1,000 requests become 4,000 attempts a second: 40,000 over the stall, and 2.67 times what the dependency can serve even once it recovers.
  2. With the budget. The first stalled second spends the 100 saved tokens plus that second's earnings: 1,199 attempts. Every later second can spend only what it earns, so it settles at 1,100, under the capacity line. When the stall ends, traffic drops straight back to about 1,010.
  3. The overshoot. The first second's extra 99 retries are why retries came to 11.0% of requests rather than 10%. The size of that first spike is set by the cap on savings, which makes the cap a real design number.

Two details in the table are worth a second look:

  • On a healthy day the budget is invisible. 10 retries a second against 100 tokens earned, and nothing refused once the counter has filled.
  • A brand-new client cannot retry at all. In second 0 the counter is empty, so the first failure is refused. That is why Finagle's budget also has a small floor of retries a second, minRetriesPerSec, that are always allowed.

The honest limit is savings, marker 3 in Fig. A2.4n. With the cap raised from 100 to 1,000 tokens, the counter had saved 451 by the time the stall began. The first stalled second then carried 1,551 attempts: 1.03 times capacity, over the line for that one second.

And the budget does one job only. It does not make a retry safe; the idempotency key does that. It does not spread retries out; jitter does that. It caps how many retries there can be, which is the one number the storm in Fig. A2.4f needed. The rule itself is one sentence; this counter is how the sentence is enforced.

A retry budget earns a tenth of a token per request and charges a whole token per retry. Retries then cannot outgrow a tenth of real traffic for longer than the saved tokens last.

What is "the slowest 1%", or p99? Why does a retry wreck it while the average barely moves?

p99 is the latency that 99 requests in 100 beat: sort the requests from fastest to slowest and read the 99th. If 2 of 100 charges need the retry of Fig. A2.4e, the average rises from 40 to 52 ms, but p99 jumps from 40 to 640 ms. Whether p99 moves at all depends on whether more than 1 request in 100 retries.

A percentile answers a line-up question. Put every request in a queue from fastest to slowest. The 50th percentile, called p50 or the median, is how slow the request halfway along is. The 99th percentile, p99, is how slow the request 99% of the way along is. Only 1 request in 100 is slower than it.

Take 100 charges under this block's policy. 98 answer in the normal 40 ms. 2 hang, are cut off at 500 ms, wait the full 100 ms of backoff drawn in Fig. A2.4e, and answer in 40 ms on the retry: 500 + 100 + 40 = 640 ms.

  1. Sort the latencies. 98 values of 40 ms, then 2 values of 640 ms.
  2. Work out the average. Add everything and divide by the count: (98 × 40 + 2 × 640) ÷ 100 = (3,920 + 1,280) ÷ 100 = 5,200 ÷ 100 = 52 ms.
  3. Find the rank for p99. 99% of 100 requests is 99, so p99 is the 99th value in the sorted list. When the count does not divide evenly, round the rank up.
  4. Count along the line. Values 1 to 98 are 40 ms. Value 99 is 640 ms. So p99 = 640 ms.
  5. Find the median for comparison. The 50th value is 40 ms. Half of all charges noticed nothing.

The average spreads the two retries' extra 1,200 ms over all 100 requests, so it rises by only 12 ms. p99 does no spreading. It reports the 99th request exactly as slow as it was. That is why section 10 says latency targets are written against p95 or p99, never the mean.

Fig. A2.4o draws that line-up, then repeats the same retry at four shares of traffic.

1 100 CHARGES, SORTED FROM FASTEST TO SLOWEST 640 ms 40 ms 2 average 52 ms: the dashed line p50, the 50th charge: 40 ms 3 p99, the 99th charge: 640 ms 1st 50th 100th the 2 retried charges add 1,200 ms in total; spread over 100 charges, that is +12 ms on the average 4 THE SAME RETRY, MORE OFTEN · 100,000 REQUESTS average p99 43.0 ms 40 ms 46.0 ms 40 ms 52.0 ms 640 ms 70.0 ms 640 ms 0.5% retried 1% retried 2% retried 5% retried
Fig. A2.4o — The average against p99. Top: the 100 charges of the worked example, each drawn as one bar, fastest first. Bottom: the same 640 ms retry at four shares of 100,000 requests, with both numbers on one millisecond scale. Values from rerunning tail_latency.py.
  1. The line-up. 100 charges sorted from fastest to slowest. 98 took 40 ms, so their bars are short and equal. The last two were cut off at 500 ms, waited 100 ms, and answered on the retry: 640 ms each.
  2. The average. 52 ms, the dashed line sitting just above the short bars. It is the two retried charges' extra 1,200 ms spread over all 100. Read on its own, it says nothing unusual happened.
  3. p99. The 99th charge in the line-up is the first tall bar: 640 ms, sixteen times the normal 40. The 50th charge, p50, is still 40 ms, so half of all customers noticed nothing.
  4. The share decides which number moves. Over 100,000 requests the average climbs gently, from 43.0 to 70.0 ms, as the retried share grows from 0.5% to 5%. p99 stays at 40 ms until more than 1 request in 100 retries, then jumps straight to 640 ms.
The same 640 ms retry at different shares of traffic, measured by tail_latency.py on 100,000 requests
Share of requests retriedAveragep50p99p99.9
None40 ms40 ms40 ms40 ms
0.5%43.0 ms40 ms40 ms640 ms
1%46.0 ms40 ms40 ms by rank; 46.0 ms interpolated640 ms
2%52.0 ms40 ms640 ms640 ms
5%70.0 ms40 ms640 ms640 ms

Read down the p99 column. It ignores the retries completely until they are more than 1 request in 100, then shows their full cost at once. So the sentence under Fig. A2.4e holds with a condition: the slowest 1% is sixteen times slower once more than 1% of requests retry, and at 5% the average is 75% worse too.

The honest limits of p99:

  • The edge depends on the tool. At exactly 1 request in 100, the rank rule above gives 40 ms, while numpy's default, which interpolates between neighbours, gives 46.0 ms. Compare p99 values only when they come from the same tool.
  • Few samples make it jumpy. A p99 over 100 requests is decided by the slowest one or two. Monitoring systems compute it over thousands of requests a minute.
  • The timeout matters more than the retry. With no timeout, the 2 hung charges wait out a 30-second library default before retrying. The same script then gives an average of 642 ms and a p99 of 30,140 ms.

p99 is the 99th value in the sorted line-up. It ignores slow requests until they pass 1 in 100, then shows their full cost, while the average spreads that cost thin.

Circuit breakers add memory: after k consecutive failures stop calling (open); after a cooldown, probe once (half-open); close on success — fail in 5 ms instead of timing out in 5 s, and give the dependency room to recover.

Bulkheads give each dependency its own pool, so the slow one exhausts its pool, not your process. And graceful degradation is the product half, decided before the incident: recommendations down → show bestsellers; personalization down → generic page.

The phrasing that lands: "invisible to the user, visible on my dashboard."

A DEPENDENCY IS DOWN: THE BREAKER TURNS A 5-SECOND TIMEOUT INTO A 5-MILLISECOND FAILURE 1 CLOSED every call goes through 5 failures in a row 2 OPEN fail in 5 ms, no call made 30 s cooldown 3 HALF-OPEN let exactly one probe through the probe succeeds → closed again the probe fails → open again the bulkhead is the other half: give each dependency its own pool, so the slow one exhausts its pool and not your process
Fig. A2.4g — The circuit breaker as three states and four transitions. Its value is not politeness towards the dependency; it is that your own threads stop being donated to something that is not answering.
  1. Closed, marker 1. Normal life. Calls go through and the breaker only counts outcomes. It needs a threshold — five consecutive failures here — and that number is a judgement about how twitchy you want it to be.
  2. Open, marker 2. The breaker stops calling at all and fails immediately, in about 5 ms instead of the 5 s a timeout would cost. Your threads come back, your latency stops climbing, and the dependency gets room to recover instead of being hammered by everyone's retries.
  3. Half-open, marker 3. After a cooldown, exactly one probe is allowed through. If it succeeds the breaker closes and normal traffic resumes; if it fails the breaker opens again for another cooldown. One probe, not a thousand, is what keeps the recovery from re-killing the dependency.
  4. What it needs alongside it. An open breaker is only useful if you have decided what to serve instead — bestsellers when recommendations are down, a generic page when personalisation is down. That decision belongs in a design document, not in the middle of an incident.

Assume the network fails.

Time out every call.

Retry only what is idempotent, with jitter.

Open the breaker before the pool is gone.

Degrade on purpose, never by surprise.

Assume the network fails: every arrow in Fig. A2.1 can hang instead of answering. Time out every call: the 500 ms cut at marker 1 of Fig. A2.4e is what turns a hang into a failure you can act on. Retry only what is idempotent, with jitter: Fig. A2.4c is the reason — a redelivered charge with no key is a second charge — and marker 4 of Fig. A2.4f is what jitter does and does not buy. Open the breaker before the pool is gone: marker 2 of Fig. A2.4g fails in 5 ms instead of 5 s, so your threads come back. Degrade on purpose: the last key under that same picture, decided before the incident rather than during it.

Say it in the room: "Timeouts on every hop with deadline propagation; retries only on idempotent calls, exponential backoff with full jitter, under a retry budget; a breaker per dependency; bulkheaded pools; and a named degraded mode per feature. I built exactly this as an LLM gateway — same patterns, different upstream."

09 · Refresher 7Rate Limiting — The Question Anand Got

This is the question Anand was actually asked: design a rate limiter for a public API. He had built them, he had been paged by one at 3 a.m., and what came out of him was vibes. Here is the vocabulary that turns those nine years into a score: four algorithms, one default, and the two numbers a token bucket is made of. The counting problem the interviewer probed next — one bucket shared by N gateway instances — gets its own worked example in section 13.

Rate limiting protects your service from overload, abuse, and your own retry bugs — and it's a favorite prompt precisely because a complete answer tours algorithms, distributed state, and API design in fifteen minutes. Algorithm first:

Decision table: rate-limiting algorithms
AlgorithmBehaviorMemory / keyWatch out
Fixed windowCounter per minute-bucketO(1)2× burst at the window boundary (59th + 61st second)
Sliding windowWeighted blend of adjacent windows (or a log of timestamps)O(1) approx / O(reqs) exactApproximation is fine; the log is exact but expensive
Token bucketSteady refill rate r, burst capacity BO(1): two floatsThe industry default — bursts are allowed by policy, not by accident
Leaky bucketQueue drained at a constant rateO(queue)Smooths perfectly but adds queueing delay
1 FIXED WINDOW · LIMIT 100 A MINUTE · AND THE BOUNDARY window 10:00:00 – 10:00:59 window 10:01:00 – 10:01:59 100 at 10:00:59 100 at 10:01:00 both windows say the client obeyed the limit; the client sent 200 inside two seconds 2 TOKEN BUCKET · B = 100 · r = 1.67 A SECOND a full bucket holds B = 100 tokens it then earns r = 1.67 tokens a second so two seconds can buy 103, never 200 worst two seconds: 200 fixed window 103 token bucket
Fig. A2.4h — Why the token bucket is the default. A fixed window resets its counter on the minute, so a client who waits for the boundary gets two full allowances back to back: 200 requests in two seconds against a limit of 100 a minute. The bucket's burst is capacity, and it is deliberate.
  1. The boundary, marker 1. A fixed window is one counter per minute-bucket, and it forgets everything at the top of the minute. A client sending 100 at 10:00:59 and 100 at 10:01:00 breaks no rule either window can see, yet your service took twice the intended rate in one second. This is the most common rate-limiter bug, and it is a favourite interview follow-up.
  2. The bucket, marker 2. A token bucket has no boundary to wait for. Capacity B is the largest burst you are willing to permit and r is the sustained rate. Starting full, the worst two seconds are B + 2r = 100 + 3.34, so 103 requests. The burst still exists — it is a policy choice, sized from how real clients behave, rather than an accident of when the clock ticks.
refill r tokens/s — accumulates up to capacity B capacity B requests each spends 1 token token available → 200 OK empty → 429 + Retry-After a full bucket absorbs a burst of B at once; sustained rate is capped at r/s Retry-After = (cost − tokens) / r — the bucket can compute its own apology
Fig. A2.5 — The token bucket: two numbers (rate r, burst B) express the policy "sustained r/s, bursts up to B tolerated" — which is how real clients actually behave.

Where it lives. Rate limiting belongs in two places: at the edge, in the API gateway, for blunt per-key protection before traffic touches your compute; and again inside services, guarding expensive resources such as per-tenant model-token budgets — your Module 12 gateway again.

The genuinely distributed part is counting. The gateway runs on N instances, and N independent buckets equals N× the limit you meant to set.

There are two honest designs:

Counting requests across N gateway instances.
DesignAccuracyCost
Central store — Redis, with the read-modify-write done atomically in a Lua script.Exact.About 1 ms per request.
Local buckets, each granted quota/N.Approximately correct — and wrong exactly when load is unbalanced.Zero added latency.

Real systems use both: Redis plus Lua for public APIs, and local buckets as internal belt-and-braces. Worked example #2 builds the race and the fix.

What the client sees is part of the design, not an afterthought: 429 Too Many Requests, a Retry-After header (the bucket computes it: tokens missing ÷ refill rate), and X-RateLimit-Limit / -Remaining / -Reset so well-behaved clients can pace themselves instead of guessing.

Say it in the room: "Token bucket per API key, enforced at the edge; counters in Redis with the check-and-decrement in a Lua script so it's atomic across gateway instances; 429 with Retry-After and X-RateLimit headers so clients can behave."

10 · Refresher 8Observability & SLOs — Numbers or It Didn't Happen

A design nobody can measure is a design nobody can defend, and the last question in the round is always what it costs. Anand needs three words for watching a system — metrics, logs, traces — and three for promising something about it: SLI, SLO, error budget. Then one number he can produce on demand: 99.9% of a month is 43 minutes and 49 seconds of allowed failure. This section also shows what happens when three such parts are chained in series, which is worse than almost anyone guesses.

The three pillars, one paragraph each. Metrics: cheap pre-aggregated numbers over time (Prometheus-style counters and histograms) — they tell you that something is wrong and power every alert; the golden signals are latency, traffic, errors, saturation.

Logs: per-event records — structured JSON, please — that tell you what happened once metrics said when.

Traces: one request followed across services via a propagated trace ID, turning "checkout is slow" into "the inventory call inside checkout is slow" — the only tool that answers where.

You met all three wearing LLM costumes in Module 12 (Langfuse traces, token-cost metrics); the classic round expects the general vocabulary.

The management layer on top: an SLI is a measurement (fraction of requests under 300 ms, fraction non-5xx); an SLO is the target you commit to; the error budget is the complement — the failure you are allowed.

At 99.9% monthly: a month averages 30.44 days = 43,830 minutes, and 0.1% of that is 43 m 49 s of total failure per month. That number turns reliability into a currency: budget left → ship faster; budget burned → freeze features and pay down reliability.

Sharpen your pencil

Compose some nines by hand once and you will never again promise "99.9%" for a system built from 99.9% parts. A redirect through the §12 shortener passes through three components in series: the load balancer, the app tier, and the database. Suppose each is up 99.9% of the time on its own. A chain is up only when every link is up, so the availabilities multiply. Work to four decimal places.

Availability of one link0.999, which allows 43,830 × 0.001 = 43.83 minutes of downtime per month
Three links in series: 0.999 × 0.999 × 0.999 =
Monthly downtime of the chain: 43,830 minutes × (1 − that number) =
Replace the single database with a redundant pair. The pair is down only when both are down: 1 − (1 − 0.999)² =1 − 0.001² = 1 − 0.000001 = 0.999999
The chain with the redundant pair: 0.999 × 0.999 × 0.999999 =
Monthly downtime now =
Which link should be made redundant next, and what does the chain reach if all three are pairs?
Check your answers
0.999 × 0.999 × 0.9990.9970 (0.997003). Three three-nines parts in series make a system with barely two nines and a half
Monthly downtime of the chain43,830 × 0.002997 = 131.36 minutes, about 2 h 11 min. Three times what any single part was allowed, because each part fails on its own schedule
Chain with the redundant database pair0.998001 × 0.999999 = 0.9980 (0.998000). The database has all but vanished from the arithmetic; the two single links now set the ceiling
Monthly downtime now43,830 × 0.0020 = 87.66 minutes, about 1 h 28 min. One redundant pair bought back 44 minutes a month
Next link, and all three as pairsEither single link; they are equal. With two pairs the chain is 0.999 × 0.999999 × 0.999999 = 0.9990, back to three nines and 43.92 minutes. With all three as pairs it is 0.999999³ = 0.999997, about 8 seconds a month

Two lessons. First, nines multiply in series, so a chain is only as good as its single links. Redundancy is spent one link at a time, and the next weakest link always sets the ceiling.

Second, the pair's 0.999999 assumes the two copies fail independently. A shared deploy, a shared switch, or one bad config pushed to both takes them down together, and the real number sits somewhere between 0.999 and 0.999999. The hood block in §11 runs the same multiplication for quorum writes, where waiting on all replicas is a series chain in disguise.

Fig. A2.5b is that ladder drawn to scale, with the same four lines you just computed.

1 A MONTH IS 43,830 MINUTES · BAR LENGTH = DOWNTIME PER MONTH balancer, app, database 0.999 × 0.999 × 0.999 = 0.9970 131.36 minutes — about 2 h 11 m 2 the database becomes a pair 0.999² × 0.999999 = 0.9980 87.66 minutes — one pair bought back 44 two pairs, one single link 0.999 × 0.999999² = 0.9990 43.92 minutes — back to three nines 3 all three as pairs 0.999999³ = 0.999997 about 8 seconds a month zero downtime 4 the pair's 0.999999 assumes the two copies fail independently — one shared deploy or switch and the truth is far worse
Fig. A2.5b — Composing nines, to scale. Three parts that are each up 99.9% of the time make a chain that is up 99.70%, which is 131.36 minutes a month. Redundancy is spent one link at a time, and the weakest remaining single link always sets the ceiling.
  1. Series multiplies, marker 1. The chain is up only when every link is up, so the availabilities multiply: 0.999 × 0.999 × 0.999 = 0.9970. That is 0.2997% of 43,830 minutes, or 131.36 minutes a month — three times what any single part was allowed, because each part fails on its own schedule.
  2. One pair, marker 2. A redundant pair is down only when both copies are down: 1 − 0.001² = 0.999999. The database effectively disappears from the arithmetic and the chain improves to 0.9980, which is 87.66 minutes. One pair bought back 44 minutes a month.
  3. The ceiling, marker 3. Keep going and the bar collapses: all three as pairs is 0.999997, about 8 seconds a month. Notice the shape of the spending, though — the second pair bought back another 44 minutes, and the third bought back 43.8. Each pair costs the same and buys less than the last in absolute terms only once the other links dominate.
  4. The lie in the arithmetic, marker 4. Two copies behind one load balancer, on one switch, sharing one deploy pipeline, do not fail independently. One bad config reaches both in the same second. The honest number sits between 0.999 and 0.999999, and the gap is exactly the amount of shared fate in your design.

Alert on burn rate, not point-in-time blips. And remember Module 01: latency SLOs are written against p95/p99, never the mean — the mean averages your happiest user with your angriest.

Say it in the room: "SLI is the measurement, SLO is the promise, error budget is the license to ship: 99.9% monthly buys us 43 m 49 s of failure. I'd alert on burn rate against p99 latency and error-rate SLIs, and the budget decides features-vs-reliability arguments so people don't have to."

11 · Under the hoodThe Math, If You Want It

Everything so far has been vocabulary Anand can say out loud. This block is the arithmetic underneath two of those claims, for the reader who wants it and for the interviewer who asks "why". The first part proves the quorum overlap and prices W = N at 99.70%, which is twenty-six hours a year of refusing to answer. The second is the back-of-envelope method — daily users to requests a second to terabytes — and the latency numbers it leans on, drawn to scale.

Quorum arithmetic — and why W = N kills availability

The overlap proof is pigeonhole: a write touches W nodes, a read touches R nodes, both drawn from the same N. Disjoint sets would need W + R ≤ N nodes; so if W + R > N, disjointness is impossible — every read set contains a node from every write set, and version metadata picks the newest value. Common dials at N = 3: W=2/R=2 (balanced, tolerates one node down for both operations), W=3/R=1 (fast reads, fragile writes), W=1/R=3 (the reverse).

Why not W = N for maximum safety? Availability multiplies. With each node up with probability a = 0.999, a W=3 write needs all three: a³ ≈ 0.9970 — three-nines nodes compose into a two-nines write path, down ~26 hours a year.

W=2-of-3 needs any two: a³ + 3a²(1−a) ≈ 0.999997 — back above three nines.

The latency version of the same trap: waiting on all N means every write runs at the pace of the momentarily slowest replica — tail-latency amplification, Module 01's p99 lesson in a quorum costume. Quorums exist to buy safety without paying all-nodes availability and latency.

Back-of-envelope capacity estimation — method, latency numbers, worked example
1 STEPS 1 TO 3 · TURN USERS INTO A RATE × 20 requests ÷ 10⁵ seconds × 5 for peak 10M daily users 2 × 10⁸ a day 2,000 QPS average 10,000 QPS peak 2 STEP 4 · SIZE THE STORAGE × 2 × 10⁸ events × 90 days × 3 replicas 1 KB per event 200 GB a day 18 TB at 90 days 54 TB stored 3 at about 500 QPS per app node, the 10,000 QPS needs 20 nodes — provision 30 for headroom rounding a day from 86,400 to 100,000 seconds costs 15%, which is invisible next to the assumptions
Fig. A2.5c — The back-of-envelope, as a chain. Each arrow is one multiplication you say out loud, and every box is a number the interviewer can challenge. The visible method is what earns the point; the decimals are not graded.
  1. Users to a rate, marker 1. Start from something the business knows — 10 million daily active users — and multiply by actions each. Divide by 10⁵ seconds rather than 86,400, because the rounding is easier to say and the error does not matter. Then multiply by 3 to 5 for the peak hour, because consumer traffic is never flat.
  2. Bytes to a bill, marker 2. One event of about 1 KB per request gives 200 GB a day. Retention turns that into 18 TB and replication into 54 TB. Say the last number in human terms — "a small cluster, not a data-lake problem" — because that judgement is the part being graded.
  3. Back to hardware, marker 3. Divide the peak rate by what one node serves to get a node count, then add headroom. This is the step candidates skip, and it is the one that converts arithmetic into a design you could actually order.

The method (four steps, out loud): ① Scope the driver: users and actions ("10M DAU, ~20 requests each"). ② Convert to rates: requests/day ÷ 86,400 — round a day to 10⁵ seconds; the 15% error is irrelevant at this precision. ③ Multiply for peak: 3–5× average for consumer traffic. ④ Size storage: events/day × bytes/event × retention × replication. Round aggressively; the interviewer wants visible method, not decimals.

Worked example — "ShopStream", Module 13's retailer. Four sentences of arithmetic, and the rubric's "does it scale" point is earned.

Traffic: 10M daily active users × 20 requests = 2×10⁸ requests/day ÷ 10⁵ s ≈ 2,000 QPS average, so ~10K QPS at 5× peak.

Storage: each request logs one ~1 KB event, so 200 GB/day. At 90-day retention that is 18 TB; with 3× replication, 54 TB.

Nodes: at ~500 QPS per app node, peak needs about 20. Provision 30 for headroom.

HOW LONG THINGS TAKE — LOG SCALE, EACH TICK IS 1,000× L1 cache reference 1 ns main memory 100 ns compress 1 KB 2 µs read 1 MB from RAM 10 µs NVMe random read 20 µs read 1 MB from NVMe 100 µs 1 round trip in one datacenter 500 µs spinning-disk seek 4 ms 2 one LLM output token 10–50 ms US East ↔ US West 65 ms transpacific round trip 150 ms 1 ns 1 µs 1 ms 1 s 3 a bar one tick longer is a thousand times slower — that is what a log scale hides and why these are worth memorising
Fig. A2.5d — The latency numbers, drawn. The same values as the table below, on a scale where each gridline is 1,000× the last. The ratios are the usable part: memory is 100× cache, a datacenter round trip is 5,000× memory, and crossing an ocean is another 300×.
  1. Where the network begins, marker 1. Everything left of the datacenter round trip happens inside one machine. Crossing to another machine in the same building costs about 500 µs, which is 5,000 memory reads. That is the step where a design decision starts costing real time, and it is why "just add a service call" is never free.
  2. The guest star, marker 2. One output token from a hosted frontier model costs 10 to 50 ms — about the same as a coast-to-coast round trip, for one token. A 500-token answer is therefore 5 to 25 seconds if you wait for all of it, which is why Module 12 streams tokens and caches aggressively.
  3. How to use them, marker 3. You are not asked to recite the table. You are asked to say things like "that design adds a cross-region hop per request, so there goes 65 ms of our 200 ms budget". Two or three ratios, used in a sentence, is the whole return on memorising this.
Latency numbers every engineer should know — 2026-ish values, read as orders of magnitude (as of Aug 2026)
Operation~CostVersus L1
L1 cache reference1 ns1×
Main-memory reference100 ns10²
Compress 1 KB (zstd-class)2 μs10³
Read 1 MB sequentially from RAM10 μs10⁴
NVMe random read20 μs10⁴
Read 1 MB sequentially from NVMe100 μs10⁵
Round trip inside one datacenter500 μs10⁵–10⁶
Spinning-disk seek4 ms10⁶
One LLM output token, hosted frontier model10–50 ms10⁷
Cross-region RTT (US East ↔ US West)~65 ms10⁷–10⁸
Cross-ocean RTT (transpacific)~150 ms10⁸

The ratios are the point: memory is 100× cache, network-in-DC is 5,000× memory, cross-region is 100× in-DC. These numbers exist to let you say: "that design adds a cross-region hop per request — there goes 65 ms of our 200 ms budget." (Note the guest star: one LLM token costs about a coast-to-coast round trip — why Module 12 streams tokens and caches aggressively.)

There are no dumb questions

I've operated these systems for nine years. Why am I being quizzed like a new grad?
The interviewer can't observe your tenure — only your 45 minutes. The round is a proxy, and proxies reward legibility: named patterns, quantified tradeoffs, failure modes volunteered unprompted. Unfair? Somewhat. Gameable with ~8 hours of vocabulary restoration on top of real experience? Completely — that asymmetry is this appendix.
Is citing CAP still respectable in 2026, or does it mark me as shallow?
Stated correctly, it's expected. What marks a candidate is the folklore version. Say "partitions happen; the choice is C vs A during one, per data class," and extend to PACELC for the bonus point. Interviewers genuinely use the misstatement as a screen.
Can I just say "I'd use DynamoDB / SQS / a managed service"?
Yes — but only alongside what the service does for you and where it fails: "DynamoDB — a hash-partitioned store with tunable consistency, and I still own the hot-partition problem." A product name without its mechanism scores as brand loyalty, not design.
How is this round different from Module 17's GenAI design round?
Same skeleton (requirements → capacity → design → deep dives → failure walk), different grading emphasis: the classic round grades fundamentals depth — numbers, consistency reasoning, failure narration; the GenAI round grades judgment about the newer stack — evals, cost, safety, retrieval. Increasingly they blend (see "your AI stack" below), so prepare for fluency in both dialects.
Is DDIA still the book?
Yes — Kleppmann's Designing Data-Intensive Applications (2nd edition, 2025) remains the deep track for everything here; budget 60+ hours. This appendix is deliberately the 8-hour track: enough vocabulary and numbers to make nine years of experience score, not a substitute.

12 · Worked exampleURL Shortener — The Full Seven Steps

Vocabulary restored, Anand now needs a rehearsal with a clock on it. The classic round's "hello world" is a URL shortener at 100 million stored links and 10,000 redirects a second, and every hop of Fig. A2.1 turns up in it. Run all seven steps here, out loud, and watch what actually carries the design: a read-to-write ratio of about 1000 to 1. Everything downstream — the cache, the replica, the queue — is a consequence of that one ratio.

The classic round's "hello world," which is exactly why it's worth doing at full interview depth once: the ID-generation subproblem has real tradeoffs. Prompt: "Design a URL shortener: 100M stored links, 10K redirect QPS at peak." Every hop of Fig. A2.1 turns up in the answer, so run Module 17's seven steps.

① Requirements (3 minutes, out loud). Functional: shorten a URL to a code; redirect the code; custom aliases, expiry, click counts. Non-functional: redirects are the product — target <50 ms at the server, 99.95% available; creation can be slower. State your assumption: ~1M new links/day (~12 writes/s average, ~100/s peak — Fig. A2.5c is the same ladder of arithmetic) against 10K read QPS — a ~1000:1 read-heavy system. Everything downstream follows from that ratio.

② Capacity math.

Storage: 100M links × ~500 bytes = 50 GB. That fits on one Postgres box with room to spare.

Say that sentence out loud in the room: "this is not a big-data problem, it is a latency-and-availability problem." It reframes the whole design.

Bandwidth: 10K QPS × ~500 B ≈ 5 MB/s. Trivial.

Cache: redirects are Zipf-distributed, so about 20% of links serve about 90% of reads. 20M × 500 B = 10 GB — the whole hot set fits in one Redis node.

③ API. POST /api/links {url, custom_alias?, expires_at?} → 201 {code, short_url}, authenticated, rate-limited (§09!), accepting an Idempotency-Key so client retries don't mint duplicates (§07!). GET /{code} → redirect — and choose the status deliberately: 302 keeps the browser coming back so clicks are countable; 301 is browser-cached — kinder to servers, blind to analytics. Owners want counts: 302.

④ Data model + ID generation. One table: links(code PK, long_url, owner_id, created_at, expires_at), plus an index on owner_id for dashboards. The interview meat is where codes come from.

A 7-character base62 code gives 62⁷ ≈ 3.5 × 10¹² combinations — 35,000× headroom over 100M. Options: (a) counter → base62 — no collisions ever, shortest codes; costs a coordination point, solved by leasing ranges (each app instance grabs 100K IDs in one DB hit, then mints locally); sequential codes are enumerable, so permute the counter with a fixed secret before encoding if that matters.

(b) hash the URL (md5, truncated) — dedupes identical URLs, but truncation collides eventually, so every insert needs a check-and-resalt path. (c) random 7 chars + uniqueness check — simple, unordered; at 100M of 3.5T, collision retries are rare.

Why not UUID? Say it before they ask: 36 characters — the one property this product sells is short; UUID buys uniqueness by spending exactly what we can't afford. Pick (a) with leased ranges, mention (c) as the simpler-ops fallback.

client GET /x7Kp2a LB app ×8 stateless 1 · GET code Redis — hot codes ~90% hit · 10 GB 2 · miss → SELECT read replica w1 · INSERT Postgres primary async · lag w0 · lease 100K IDs ID range allocator 3 · click event Kafka — clicks analytics consumer
Fig. A2.6 — The shortener at 10K QPS. Read path: cache hit (1) answers ~90% of redirects in ~1 ms; misses (2) hit a read replica. Write path: lease ID ranges off-path (w0), insert to the primary (w1). Clicks leave as async events (3) — analytics never touches the redirect's critical path.

⑤ Read path. GET /x7Kp2a → app → Redis: hit → 302, done in ~1 ms server-side. Miss → read replica → fill cache (cache-aside, TTL ~24 h with jitter) → 302. Cache unknown codes too — a negative cache with a short TTL — or a bot scanning the keyspace turns every 404 into a database query. The cache fleet uses consistent hashing (Fig. A2.2), so a node loss costs 1/N of hit rate for a few minutes, with coalescing (§04) absorbing the refill herd.

⑥ Write path. Check the idempotency key → take the next ID from the instance's leased range (the allocator is consulted once per 100K creations — nothing to coordinate on the hot path) → base62-encode → insert → 201. Custom aliases are arbitrated by the insert's uniqueness constraint: first writer wins, second gets 409. Note what you did not do: no cache write (the first reader fills it), no synchronous analytics — nothing between the user and their 201 except one indexed insert at ~12/s.

⑦ Failure modes & evolution — narrate unprompted. Cache node dies: hit rate dips by 1/N, the replica absorbs the misses, coalescing prevents a herd — a non-incident by design.

Primary dies: reads are unaffected (cache + replica); creation degrades for the ~30 s of failover — quorum election, fencing against split-brain (§05) — and replica lag means a just-created link can 404 on a replica read: acceptable, or route cache-miss reads for codes younger than 60 s to the primary (read-your-writes, §06, applied).

Hot link at 5K QPS: it's one cache key — add an in-process L1 above Redis, or push the top-100 codes to the CDN edge. Allocator down: instances keep minting from leased ranges — hours of runway from one design choice.

Evolution: click events flow through Kafka (§07); a consumer group aggregates per-code counts; replay rebuilds analytics after a bug without touching production reads. Every arrow in Fig. A2.6 is a section of this appendix doing its job.

13 · Worked exampleDistributed Rate Limiter — Anand's Redemption Arc

This is the exact prompt from Anand's round three, answered properly at last. The design itself is one paragraph, because section 09 already did the thinking. The probe he could not answer was the second question: is your counter atomic across gateway instances? The answer is a race you can read in eleven lines of Python, and a fix that moves those same eleven lines inside Redis.

Compact sketch, because §09 did the thinking: token bucket per API key; enforced at the edge; state in Redis so all N gateway instances share one truth; 429 + Retry-After out. The part interviews probe is the race. Here is the version that looks right and silently isn't:

You have not been shown this file yet, and you are not expected to read Redis client code fluently. Guess first, then check. Every line in the table is explained in the step-by-step list under it, and the fixed version that follows reuses the same lines with one change. The lab in §16 has you write the same bucket from scratch.

Sharpen your pencil

Below are eleven lines lifted from naive_bucket.py, in the order they appear. Three are annotated for you. In the blank rows, write what you think each line does, in plain English, before you open the answers. One row hides the bug the interviewer asked Anand about. See if you can spot which, before the code's own comment tells you.

r = redis.Redis(decode_responses=True)open a connection to the local Redis server; decode_responses makes it return text instead of raw bytes
def allow(api_key: str, capacity=10, refill_per_s=5.0) -> bool:
key = f"rl:{api_key}"
tokens, ts = r.hmget(key, "tokens", "ts")read two fields of one Redis hash in a single round trip: how many tokens were left, and when we last looked
now = time.time()
tokens = float(tokens) if tokens else capacity
ts = float(ts) if ts else now
tokens = min(capacity, tokens + (now - ts) * refill_per_s)add the tokens earned since the last look (seconds elapsed × refill rate), but never above the bucket's capacity
if tokens < 1: return False
r.hset(key, mapping={"tokens": tokens - 1, "ts": now})
return True
Check your answers
r = redis.Redis(decode_responses=True)open a connection to the local Redis server; decode_responses makes it return text instead of raw bytes
def allow(api_key: str, capacity=10, refill_per_s=5.0) -> bool:define the function the gateway calls once per request: it takes the caller's API key and answers True (serve it) or False (send a 429). The defaults say a bucket holds 10 tokens and earns 5 per second
key = f"rl:{api_key}"build the Redis key for this caller's bucket, with a prefix so rate-limit keys never collide with anything else stored in the same Redis
tokens, ts = r.hmget(key, "tokens", "ts")read two fields of one Redis hash in a single round trip: how many tokens were left, and when we last looked. This is round trip one
now = time.time()read the wall clock, in seconds, on this gateway instance. Note who owns the clock: the gateway, not Redis
tokens = float(tokens) if tokens else capacityif the hash had a tokens field, turn its text into a number; if not, this caller is new and starts with a full bucket
ts = float(ts) if ts else nowthe same for the timestamp: use the stored one, or "now" for a caller with no history, so a first call earns no refill
tokens = min(capacity, tokens + (now - ts) * refill_per_s)add the tokens earned since the last look (seconds elapsed × refill rate), but never above the bucket's capacity
if tokens < 1: return Falsethe bucket cannot pay for one request, so deny it. Nothing is written back, which is fine: the caller's refill is recomputed from ts on the next call anyway
r.hset(key, mapping={"tokens": tokens - 1, "ts": now})write both fields back: one token fewer, and the new timestamp. This is round trip two, and the gap between it and the read four rows up is where the bug lives
return Truetell the gateway to serve the request

If you wrote "read" next to the hmget row and "write" next to the hset row, look at them again. They are two separate trips across the network. If you noticed that, you found the race before the page named it. Two gateway instances can both read "1 token left" in that gap, both allow, and both write back zero. The next block shows the same eleven lines with the gap closed.

Step-by-step: what naive_bucket.py does, in plain English
  1. Bring in two libraries: time for the clock and redis, the client that talks to a Redis server. The first comment says how to start one locally with Docker.
  2. Open a client to Redis on this machine. decode_responses=True makes every value come back as text rather than bytes, so the code can convert it with float().
  3. Define allow(api_key, capacity, refill_per_s): the function the gateway calls once for every incoming request. It returns True to serve the request or False to reject it.
  4. Build the key rl:<api_key>, one hash per caller.
  5. Read the two fields tokens and ts from that hash with HMGET. This is the first network round trip. A caller with no history gets two empty values.
  6. Take the current time. Convert the stored values to numbers, defaulting a new caller to a full bucket and a timestamp of now.
  7. Refill: add the seconds elapsed since ts multiplied by the refill rate, then cap at capacity.
  8. If fewer than one token remains, return False without writing anything.
  9. Otherwise write tokens - 1 and ts = now back with HSET. This is the second round trip. The comment marks the race: a second gateway instance can run its own step 5 between this instance's step 5 and step 9, and both will allow.
  10. Return True.
naive_bucket.pyruns offline
# pip install redis==5.*        # local server: docker run --rm -p 6379:6379 redis:7
# naive_bucket.py -- readable, testable, and WRONG under concurrency.
import time

import redis

r = redis.Redis(decode_responses=True)

def allow(api_key: str, capacity=10, refill_per_s=5.0) -> bool:
    key = f"rl:{api_key}"
    tokens, ts = r.hmget(key, "tokens", "ts")          # 1 -- READ state
    now = time.time()
    tokens = float(tokens) if tokens else capacity
    ts = float(ts) if ts else now
    tokens = min(capacity, tokens + (now - ts) * refill_per_s)
    if tokens < 1:
        return False
    # RACE: a second gateway instance can run its own READ between our READ
    # and this WRITE -- both see 1.0 tokens, both allow, both write 0.0.
    # With N instances under load, this quietly multiplies your limit by ~N.
    r.hset(key, mapping={"tokens": tokens - 1, "ts": now})   # 2 -- WRITE state
    return True

The read-modify-write spans two network round trips, and every interleaving between them is a free token. The fix is to move the whole read-modify-write inside Redis, where scripts execute atomically — single-threaded, no interleaving possible:

Step-by-step: what redis_token_bucket.py does, in plain English
  1. Same two imports as before.
  2. Define LUA, a string holding a small program in Lua, the scripting language built into Redis. Redis runs a script as one unit: no other command touches the server until the script returns.
  3. The script reads its inputs. KEYS[1] is the bucket's key. ARGV carries the capacity, the refill rate, the caller's clock reading, and the cost of this request.
  4. The clock is passed in rather than read inside the script. That makes the script a pure function of its inputs: the same inputs always give the same result. A pure script is safe to replicate and easy to test with a fixed time.
  5. HMGET reads tokens and ts; a missing field defaults to a full bucket and to now, exactly as the Python version did.
  6. Refill: elapsed time times the refill rate, added to the tokens, capped at capacity. math.max(0, ...) clamps the elapsed time at zero, so a caller whose clock went backwards cannot subtract tokens.
  7. If the bucket holds at least cost tokens, subtract them and set allowed to 1.
  8. HSET writes both fields back. EXPIRE gives the key a lifetime of twice the seconds needed to refill from empty. A caller that goes quiet therefore has its bucket deleted automatically instead of living in Redis forever.
  9. Return allowed, 1 or 0. The read, the arithmetic and the write all happened inside one command on the server: one round trip, no gap.
  10. Back in Python, register_script uploads the script once and hands back a callable. Later calls send only the script's hash (EVALSHA), not its text.
  11. allow() runs the script with one key and four arguments and returns True when the reply is 1.
  12. The demo makes twelve calls: ten are allowed, two are denied. It sleeps half a second, which at 5 tokens per second earns 2.5 tokens, and the next call is allowed again.
redis_token_bucket.pyruns offline
# pip install redis==5.*        # local server: docker run --rm -p 6379:6379 redis:7
# redis_token_bucket.py -- the fix: the read-modify-write happens INSIDE Redis,
# atomically, via a Lua script. One round trip, no interleaving possible.
import time

import redis

LUA = """
local key      = KEYS[1]
local capacity = tonumber(ARGV[1])
local refill   = tonumber(ARGV[2])      -- tokens per second
local now      = tonumber(ARGV[3])      -- caller supplies the clock: script stays deterministic
local cost     = tonumber(ARGV[4])

local state  = redis.call('HMGET', key, 'tokens', 'ts')
local tokens = tonumber(state[1]) or capacity
local ts     = tonumber(state[2]) or now

tokens = math.min(capacity, tokens + math.max(0, now - ts) * refill)
local allowed = 0
if tokens >= cost then
  tokens  = tokens - cost
  allowed = 1
end
redis.call('HSET', key, 'tokens', tokens, 'ts', now)
redis.call('EXPIRE', key, math.ceil(capacity / refill) * 2)  -- idle keys evict themselves
return allowed
"""

r = redis.Redis(decode_responses=True)
token_bucket = r.register_script(LUA)   # EVALSHA under the hood: cached server-side

def allow(api_key: str, capacity=10, refill_per_s=5.0, cost=1) -> bool:
    return token_bucket(keys=[f"rl:{api_key}"],
                        args=[capacity, refill_per_s, time.time(), cost]) == 1

if __name__ == "__main__":
    print([allow("acme") for _ in range(12)])   # 10x True, then False, False
    time.sleep(0.5)                             # 0.5 s x 5 tok/s ~= 2.5 tokens back
    print(allow("acme"))                        # True

Before the anatomy, put the code's own names on the picture. Fig. A2.6b is the same bucket as Fig. A2.5, redrawn with the variables from redis_token_bucket.py and the demo's numbers on it: capacity 10, refill 5 a second, twelve calls.

THE BUCKET, WITH THE CODE'S OWN NAMES ON IT refill_per_s = 5 tokens/s 2 (now − ts) × 5 = 0.5 × 5 = 2.5 1 capacity = 10 tokens (the burst B) tokens = 2.5 10 5 0 3 cost = 1 per call calls 1–10: a token each, 200 OK calls 11–12: bucket empty, 429 sleep 0.5 s → 2.5 tokens → allowed again 4 Retry-After = (cost − tokens) ÷ refill_per_s = (1 − 0) ÷ 5 = 0.2 s — the bucket computes its own apology
Fig. A2.6b — The bucket with its variables named. Numbers are the demo's own: capacity=10, refill_per_s=5.0, twelve calls of which ten are allowed, then a 0.5 s sleep that earns 2.5 tokens back.
  1. capacity, marker 1. The rim. The bucket never holds more than 10 tokens no matter how long the caller has been quiet, which is what makes "bursts up to B" a promise. Remove the cap and a key idle for a day arrives with 432,000 tokens and spends them all at once.
  2. The lazy refill, marker 2. No thread tops the bucket up. At the moment of a call, the code turns elapsed seconds into tokens: (now − ts) × refill_per_s, here 0.5 × 5 = 2.5. The clock comes from the caller, which is why two gateways with disagreeing clocks mint or destroy tokens for the same key.
  3. The spend, marker 3. Each request costs one token, and a request is denied when the bucket cannot cover the whole cost. Tokens never go negative, so a rejected client is not left digging out of a hole it has to repay.
  4. The apology, marker 4. The same two numbers produce the Retry-After header: the tokens you are short, divided by the refill rate. The limiter is therefore able to tell the client exactly when to come back, which is the difference between a rate limiter and a wall.
Anatomy of the token-bucket refill — the two lines to know by heart
tokens = min(1capacity2, tokens3 + (now - ts)4 * refill_per_s5)
if tokens >= cost6:
    tokens -= cost
  1. min: the cap. The bucket never holds more than it can hold. Leave the cap out and an API key idle for a day arrives with 432,000 tokens (5 per second × 86,400 seconds). It then spends them on you in one burst. The cap is what makes "bursts up to B" a promise instead of a hope.
  2. capacity: the burst allowance, B. How many requests a quiet client may fire at once. It is a policy number, not a performance one. The interviewer wants to hear that bursts are permitted on purpose, and that B is chosen from how real clients behave.
  3. tokens: what was left last time. Read from Redis, or from the object's own field in ratelimit.py. A caller with no history starts full. The common mistake is starting a new caller at zero, which turns the first request of every new key into a 429.
  4. (now − ts): the seconds elapsed. This is lazy refill: no background thread tops up buckets, and elapsed time becomes tokens at the moment of the next call. Both versions take the clock from the gateway, so two gateways whose clocks disagree mint or destroy tokens for the same key. A clock that steps backwards makes the elapsed time negative; the Lua version clamps that at zero, and time.monotonic never steps backwards.
  5. × refill_per_s: the sustained rate, r. Seconds elapsed times tokens per second gives tokens earned. Check the units: an elapsed time in milliseconds refills a thousand times too fast, and nobody notices until the limiter admits everything.
  6. ≥ cost: spend or deny, never borrow. Deny when the bucket cannot cover the whole cost, so tokens never go negative and a rejected client is not left digging out of a hole. The same numbers give the apology: Retry-After = (cost − tokens) / refill_per_s, which retry_after() in the lab computes.

Close the sketch with the judgment call: this costs one ~1 ms Redis round trip per request and makes Redis a dependency of every request — so the edge keeps a coarse local bucket as belt-and-braces, and if Redis is down you fail open (serve traffic unlimited) for a public API, or fail closed for a metered billing API. Saying "fail open or closed — here's which and why" is precisely the sentence that separates "strong AI, inconsistent fundamentals" from an offer.

The stack, and why

Before the lab, here is every building block this appendix leans on, what the code in it actually runs, and what you would pick instead.

The stack, and why

The one question that decides each layer: what breaks first when traffic grows ten times? (As of October 2026.)

The classic distributed-systems building blocks: what this appendix uses, what else you could use, and when to switch
LayerWe useAlternativesWhy this oneSwitch when
Shared counters and cacheRedis 7 with redis-py 5 (the code in §13)Memcached, Valkey, DynamoDBAtomic scripts, expiring keys and a hash type in one box. Weakness: data lives in memory and a node that dies loses the last writes.Memcached when you only need plain get/set caching of small blobs across many cores; Valkey when your licence review rejects Redis 8’s AGPL option.
Atomic check-and-spendA Lua script run inside RedisMULTI/WATCH transactions, a gateway’s built-in limiter (Envoy, NGINX)The script runs as one unit, so no other gateway can slip in between the read and the write. Weakness: a slow script blocks every other client of that Redis.The gateway’s built-in limiter when you only need per-IP limits and no custom rules; MULTI/WATCH never, because retries under load make it slower than the script.
Primary database (prose, §05)PostgreSQLMySQL, DynamoDB, CassandraStrong consistency, joins and transactions on one primary with replicas. Weakness: writes stop scaling at one primary.DynamoDB or Cassandra when one primary cannot take the writes (roughly tens of thousands of writes a second sustained) or you need several regions accepting writes at once.
Queue or stream (prose, §07)KafkaRabbitMQ, Amazon SQS, Redis StreamsA replayable log many consumers read at their own pace. Weakness: heavy to run and wasteful for a few thousand jobs a day.SQS or RabbitMQ when you need simple “do this job once” work queues with retries and no replay, or when you do not want to run brokers yourself.
Hash ring and bucket logicPlain Python standard library (ratelimit.py)Libraries built in Go, Java or Rust; a managed limiterYou can read every line, and the tests need nothing installed. Weakness: Python is too slow for a gateway handling 50,000+ requests a second per box.A compiled language (see the coding-round patterns appendix, A3, for the same ideas in interview form) when the limiter sits on the hot path of a gateway.
Testspytest 8unittest, HypothesisPlain assert statements and clear failure output. Weakness: needs installing; unittest ships with Python.Hypothesis added on top when you want random inputs to hunt for a bucket that goes negative.

Choose each block by what it must survive: Redis for shared fast state, Postgres until one primary is not enough, a log or a queue depending on whether you need replay.

14 · The bridge to AIDistributed Systems in Your AI Stack

Anand's first two rounds went well because his AI vocabulary was current and his examples were his own. This section shows that the two dialects are one language: every classic pattern in this appendix already exists in something he built in modules 07 to 12. Read the mapping in both directions before the loop. Used out loud, mid-sentence, it is what turns "strong AI, inconsistent fundamentals" into "architect".

Here is why this appendix belongs in an AI course: you have already built a distributed system in these seventeen modules — it was just wearing GenAI vocabulary. And the interview rounds are blending to match: 2026 loops increasingly ask classic questions about AI infrastructure. "Shard your RAG index" is a real question — it's §05's partitioning logic pointed at Module 08's vector store.

The mapping: classic concept → where you built it in this course → the blended interview question
Classic conceptWhere you built itThe 2026 blended question
Sharding + rebalancing (§05)Module 08 — vector index at scale"Your corpus hits 200M vectors. How do you shard the index, and how do you reindex without downtime?" (Answer: partition by tenant or hash; blue-green index + dual-write during the swap — a resharding migration wearing embeddings)
Durable state, event sourcing (§07)Module 09 — LangGraph checkpointer"An agent crashes mid-run. How do you resume?" (The checkpointer is a write-ahead log of graph state; resume = replay from the last checkpoint)
LB + cache + circuit breaker (§03, §04, §08)Module 12 — the LLM gateway"Design an LLM gateway over three providers" (routing = load balancing, semantic cache = §04 with embeddings as keys, breaker-per-provider = §08 verbatim)
Consistency checking, CI gates (§06)Module 07 — eval CI"How do you stop a prompt change regressing prod?" (Eval gates are consistency checks on behavior: no deploy while the invariant fails)
Service mesh entry: auth, quotas (§09)Module 10 — MCP servers"You're exposing internal tools over MCP. How do you secure and rate-limit them?" (An MCP server is a service-mesh entry point: authN/Z, per-client token buckets, audit logs)

Use the mapping in both directions: when the classic round asks about caching, your Module 12 semantic cache is a memorable example; when the GenAI round asks about scaling retrieval, §05's sharding vocabulary is the frame. Candidates who move between the dialects mid-sentence read as architects — the "inconsistent fundamentals" gap, closed.

15 · Watch it breakThe Five Classic Traps

Anand's failure was never ignorance. It was the half-answer: the confident opening sentence with no second sentence behind it, and an interviewer waiting for the second one. These five phrases are the ones that lose points when they are said alone. Each is followed here by the sentence that rescues it, and then the two ideas that cost the most — Consistency and Availability — argue in front of you with a real outage each.

Failure mode

Each of these phrases, said without its follow-through, actively loses points — the interviewer hears the confident opener and then watches for the second sentence that doesn't come. The trap isn't ignorance; it's the half-answer.

"Just add a cache." Heard as: never been paged for staleness. The second sentence: which write strategy, what invalidation, and what happens when a hot key expires (coalescing). A cache is a liability you take on purpose.

"Shard by user_id." Right default — and the interviewer is already thinking about the celebrity. Volunteer the hot-key story yourself (salting, dedicated outlier handling, cache in front) or watch the follow-up dismantle you.

"Retry on failure." Without backoff, jitter, a budget, and idempotency, you've described a retry storm: a thousand clients synchronized into a battering ram, DDoSing yourself precisely when you're weakest, duplicating every side effect.

"We need strong consistency everywhere." Heard as: cost unexamined. Strong consistency is coordination; coordination is latency and unavailability (the W=N math in the hood block). Price it per data class: the ledger earns it; the like-counter doesn't.

"CAP says pick two of three." The folklore version, and a genuine screen. Partitions are not on the menu — they happen. The choice is C-vs-A during a partition, latency-vs-consistency the rest of the time (PACELC).

Before the two of them argue, look at what each one is actually defending. Fig. A2.6c puts a real outage on each side and the moment of choice in the middle. Every claim in the chat below points at something in this picture.

1 CONSISTENCY refuse rather than answer wrong GitHub, October 2018 43 seconds of lost connectivity two primaries, both taking writes 24+ hours of degraded service spent merging two histories what it costs if you buy it everywhere: wait for all 3 replicas, each up 99.9% 0.999³ = 0.9970 → 26 hours a year of refusing to answer at all 2 THE MOMENT OF CHOICE a node the partition refuse (CP) answer (AP) the node cannot reach a majority refusing has to be chosen in advance a system that never chose is AP by accident 3 AVAILABILITY answer now, reconcile later Amazon Dynamo, 2007 the cart always accepts "add item" even with a replica unreachable a refused write is a lost sale two cart versions, merged after what it costs: a deleted item can come back somebody must write the merge rule and the product team never asked for it 4 while the network is healthy you can have both, and the only bill is latency — that is the "else" half of PACELC the fight starts when a switch dies, and then it is settled per data class: the ledger refuses, the counter answers
Fig. A2.6c — The two sides, with a real outage each. Consistency's bill is GitHub's day of reconciliation avoided, paid for in refused writes. Availability's bill is a resurrected cart item, paid for in merge code. Neither is free, and neither is chosen for the whole system at once.
  1. What consistency prevents, marker 1. In October 2018 a 43-second network fault between two GitHub sites left an old primary still accepting writes while a new primary was promoted elsewhere. Two histories of one database took more than a day of degraded service to merge. Forty-three seconds of choosing availability by accident, and a day of cleanup.
  2. What consistency costs, marker 1. Bought everywhere, it is coordination on every write. Waiting for all three replicas, each up 99.9%, gives 0.999³ = 0.9970 — about twenty-six hours a year when the write path refuses to answer. That is why it is spent per data class and not by default.
  3. The moment itself, marker 2. The choice only exists while a node cannot reach a majority. It either refuses, which is consistency, or answers with what it has, which is availability. The refusing has to be written into the code beforehand; a system whose designers never chose ends up answering from a stale replica with nobody reconciling anything.
  4. What availability buys and owes, marker 3. Amazon's 2007 Dynamo paper made the shopping cart always writable, because a refused "add to cart" is a lost sale. The paper is equally clear about the bill: versions must be merged afterwards, and a merge can resurrect an item the customer deleted. Choosing availability means owning the reconciliation code.
  5. The part everyone forgets, marker 4. These two only fight during a partition. The rest of the time a system can have both, and pays in latency instead — which is the "else" half of PACELC and the thing the "pick two of three" folklore hides.
Fireside chat

Tonight's talk: Consistency and Availability argue over the question, "Who's more important?"

Consistency
Availability

Marker 1 of Fig. A2.6c is my opening argument. October 2018, GitHub. Forty-three seconds of lost connectivity between two of their sites. The old primary kept accepting writes that never reached the other coast. Then the failover tooling promoted a new primary there, which took writes of its own. Two histories of one database, and more than twenty-four hours of degraded service to reconcile them. Forty-three seconds of you, a day of cleanup.

a short network fault left two nodes both behaving as primary, and both accepted writes. Nothing looked broken while it was happening. The bill arrived afterwards, as a day spent merging two versions of the truth by hand.

And marker 3 is mine, from the paper that made me respectable. Amazon's Dynamo, 2007, the shopping cart. Amazon decided that a customer must always be able to add an item, even while a replica is unreachable, because a refused write is a lost sale. They accepted that two versions of a cart might exist for a while and merged them afterwards. You would have shown that customer an error page and called it correctness.

Dynamo keeps accepting writes during a failure and sorts out the disagreement later. The reason was commercial rather than technical: a cart that refuses to take an item loses the order.

A merged cart that brings back the item they deleted — you wrote that cost on your own panel, marker 3, so at least we agree on it. I read the paper too; the authors admit it. Merging is a debt you take on now and pay later, in reconciliation code nobody on the product team asked for. And the reader has lived the version where nobody wrote that code at all: the night two "primaries" both accepted writes that could not be merged.

reconciling two versions is real work, and some merges quietly undo what the user did. Choosing availability means owning that merge rule and its mistakes.

And "we need strong consistency everywhere" is one of the five traps the reader just walked past. You are coordination, and coordination is a round trip you charge on every single write. Look at the bottom of your own panel, marker 1: three replicas at 99.9% each, every one of them required, is 0.999³ = 0.9970. That is twenty-six hours a year of refusing to answer. You call it safety. The customer calls it an outage.

when a write must reach every replica, any one replica being down stops the write. Multiplying three 99.9% parts gives 99.70%, which is about twenty-six hours a year of downtime on the write path.

Twenty-six hours a year is the price of never lying, and marker 4 is where I admit I do not charge it everywhere. I charge it on the ledger, where a stale read is a double spend, and you may have the like counter. Per data class — the reader's own "say it in the room" line already says so. I am expensive, so I am spent where being wrong costs more than being late.

consistency is bought for one kind of data at a time, not for a whole system. Money paths earn it; counters and feeds do not.

Then we agree on more than the audience thinks, so let me say the part they keep getting wrong — it is the second line under marker 4. We only fight during a partition. When the network is healthy a system can have both of us: every write reaches every replica, every read is fresh, and the only bill is latency. "Pick two of three" pretends we fight all day. We do not. We fight when a switch dies.

the trade-off only exists while the network is broken. The rest of the time you can have both, and what you pay instead is waiting.

PACELC, in one breath, and it is written along the bottom of the picture. During a Partition, you or me. Else, latency or me. Say that sentence in the room and the interviewer stops asking.

PACELC is CAP plus the healthy case: during a Partition it is Availability against Consistency; Else it is Latency against Consistency.

During that partition, be honest about the default — marker 2, the two doors. A node that cannot reach a majority either refuses, which is you, or answers with what it has, which is me. Refusing has to be chosen in advance, in code. A system whose designers never chose ends up as me by accident: an asynchronous replica answering reads, and nobody reconciling anything. That is the worst of both of us.

the choice is made while the code is written, not while the switch is down. A team that never decided gets availability by default, without any of the merge logic that makes availability safe.

Which is exactly marker 1 of Fig. A2.3d: a user's edit "disappeared" for four seconds because a replica answered before it had the write. You, with no plan. With a plan it is marker 2 of that same picture — read-your-writes, pinning that one author to the primary for about a minute. That is me, spent carefully, on one user, and nobody else paid a thing.

the disappearing edit was a stale read from a lagging replica. Sending only the author's reads to the primary fixes it for the one person who would notice, and leaves everybody else on the fast path.

Spent carefully. I can live with that phrase. So, for the record: you own the money path while the switch is down, I own the browse path and the counters, and the rest of the time we are both just arguing with latency.

they settle on a split by data class, which is exactly the answer an interviewer is listening for.

For the record. We will revisit who's more important the next time a switch fails, which, since we are both being honest tonight, is not a question of whether.

neither of them wins. Partitions are certain, so the decision has to be made in advance, for each kind of data.

Boardroom translation

Reliability is revenue math, and the engineer who can do it in front of executives gets the architect title.

An SLO is a budget decision, not a virtue: downtime × traffic × conversion = the cost of an outage, so the marginal nine has a price tag. Concretely: checkout at 50K sessions/hour × 2.1% conversion × $38 AOV ≈ $40K/hour of protected revenue.

Moving 99.9% → 99.95% halves the monthly error budget from 43 m 49 s to 21 m 55 s — roughly $14K/month of protected checkout revenue at peak — against the cost of the extra nine: multi-AZ, another replica, on-call maturity.

Sometimes the nine is a bargain; sometimes graceful degradation buys the same protection for a tenth of the spend. The elevator version: "I can tell you what a nine costs and what it protects — and which of our features deserves one."

16 · The labThe Classic Round, Twice Over

Everything in this appendix is now a sentence Anand can say. What he has not done is say any of it under a clock, which is the only genuinely hard part of the round. Part 1 is thirty-five minutes at a whiteboard with no notes, self-scored against section 12, and the gaps are the week's study list. Part 2 is the code: build the token bucket and the hash ring until six tests pass, so the numbers in your answers come from something you ran yourself.

LAB A2 — Whiteboard drill + rate-limiter kit

Part 1 — the whiteboard drill (do this BEFORE reading §12, or use "design Pastebin" if you already have). Set a timer: 35 minutes, no notes, out loud. Run the URL shortener end to end, then self-score against §12 with this rubric — one point per line, 8+ is offer territory:

  • Stated functional + non-functional requirements and the read:write ratio in the first 5 minutes
  • Capacity math out loud: QPS, storage, cache size — within 10× of §12's numbers
  • API sketched with status codes, idempotency key, and a deliberate 301-vs-302 choice
  • ID generation: two options compared, one chosen with a stated reason, "why not UUID" addressed
  • Read path with cache strategy named (cache-aside + TTL jitter) and herd control
  • Write path with no synchronous analytics on the critical path
  • One failure walk narrated unprompted ("when the primary dies…") including the replica-lag consequence
  • One evolution step (click stream → analytics consumer) with delivery semantics named
  • Log 3 gaps between your run and §12 — those are your review list for the week

Part 2 — the code. Build ratelimit.py below (token bucket + consistent-hash ring, stdlib only), run its demo, then make the pytest suite pass. Acceptance criteria:

  • python3 ratelimit.py reproduces the expected output shown in the code comments
  • pytest test_ratelimit.py -q → 6 passed — refill math, burst behavior, and ≈1/N ring redistribution all proven
  • Your extension (the 20%): add a SlidingWindowLimiter class with two tests of your own, and wire either limiter into a ~20-line WSGI middleware returning 429 + Retry-After
  • README documents: the ring-redistribution measurement, 3 failure modes you'd expect in production, and your fail-open/fail-closed choice with one sentence of justification

Stretch goal: run two threads against naive_bucket.py (§13) hammering one key and measure how far past the limit it lets you — then repeat against the Lua version and watch the race disappear. Numbers in the README.

Build it in chunks

We build ratelimit.py in four chunks. Each one runs on its own; the whole file comes at the end. The files are in code/a2-distributed-systems/ladder/.

  1. Chunk 1 — a token bucket that says yes or no

    This comes first because the bucket is the whole idea: a counter that refills over time. Nothing else in the file works without it, and it needs no clock tricks yet, only the real one.

    Step-by-step: what chunk 1 does, in plain English
    1. Import the three standard-library modules. Only time is used in this chunk; bisect and hashlib wait for chunk 3.
    2. TokenBucket.__init__ stores the capacity and refill rate and starts the bucket full, so a new client may burst.
    3. _refill adds elapsed seconds times the rate and caps at capacity.
    4. allow refills, spends the cost if it can, and returns True or False. It never goes negative.
    5. retry_after says how many seconds until the missing tokens exist.
    6. The small demo makes a bucket of 3 and calls it four times at once.
    ratelimit.py — chunk 1runs offline
    import bisect
    import hashlib
    import time
    
    class TokenBucket:
        """Classic token bucket: capacity B tokens, refills at r tokens/second.
    
        Lazy refill: instead of a background thread topping the bucket up, we
        compute how many tokens accrued since the last call. Same math, no timer,
        and it works identically with a fake clock in tests.
        """
    
        def __init__(self, capacity: float, refill_per_s: float, now=time.monotonic):
            self.capacity = float(capacity)
            self.refill_per_s = float(refill_per_s)
            self.tokens = float(capacity)   # a fresh bucket starts full -> bursts allowed
            self.now = now                  # injectable clock: determinism in tests
            self.last = now()
    
        def _refill(self) -> None:
            t = self.now()
            self.tokens = min(self.capacity,
                              self.tokens + (t - self.last) * self.refill_per_s)
            self.last = t
    
        def allow(self, cost: float = 1.0) -> bool:
            self._refill()
            if self.tokens >= cost:
                self.tokens -= cost
                return True
            return False                    # never goes negative: no token debt
    
        def retry_after(self, cost: float = 1.0) -> float:
            """Seconds until `cost` tokens exist -- this is your Retry-After header."""
            self._refill()
            return max(0.0, (cost - self.tokens) / self.refill_per_s)
    
    if __name__ == "__main__":
        b = TokenBucket(capacity=3, refill_per_s=1)
        print("four quick calls:", [b.allow() for _ in range(4)])

    Lazy refill — no timer thread; elapsed time is turned into tokens at the moment of the next call.

    Run python3 chunk1_bucket.py. You should see four quick calls: [True, True, True, False].

  2. Chunk 2 — a clock you control, so the bucket can be tested exactly

    The real clock makes every run slightly different, so you cannot prove the refill math. A fake clock you move by hand fixes that. The demo from chunk 1 is replaced by one that uses it.

    Step-by-step: what chunk 2 does, in plain English
    1. ManualClock stores a time t that starts at 0.
    2. Calling it like a function returns t, which is the same shape as time.monotonic.
    3. advance(dt) moves time forward by hand.
    4. The new demo builds a bucket of 10 refilling 5 per second on this clock, makes 11 calls (10 allowed, the 11th denied), reads retry_after, advances 0.4 s and finds exactly 2 tokens back.
    ratelimit.py — chunk 2runs offline
    class ManualClock:
        """Deterministic clock so tests never sleep."""
    
        def __init__(self) -> None:
            self.t = 0.0
    
        def __call__(self) -> float:
            return self.t
    
        def advance(self, dt: float) -> None:
            self.t += dt
    
    if __name__ == "__main__":
        # the chunk 1 demo is replaced by this one
        clock = ManualClock()
        b = TokenBucket(capacity=10, refill_per_s=5, now=clock)
        burst = [b.allow() for _ in range(11)]
        print(f"burst: first 10 -> {sum(burst[:10])}/10 allowed, 11th -> {burst[10]}")
        print(f"retry_after(1) -> {b.retry_after():.1f}s")
        clock.advance(0.4)                       # 0.4 s x 5 tok/s = 2 tokens back
        print(f"after 0.4s: {[b.allow() for _ in range(3)]}")

    Dependency injection — now=clock hands the bucket its clock instead of letting it read the real one. __call__ makes an object callable like a function.

    Run python3 chunk2_clock.py. You should see burst: first 10 -> 10/10 allowed, 11th -> False / retry_after(1) -> 0.2s / after 0.4s: [True, True, False].

  3. Chunk 3 — a consistent-hash ring that assigns keys to nodes

    The bucket answers how often; the ring answers which gateway node owns this client. It comes after the clock because the ring also has to behave the same every run, and it sets up chunk 4, where a node dies.

    Step-by-step: what chunk 3 does, in plain English
    1. HashRing keeps two parallel lists: sorted positions on the ring, and which node owns each one.
    2. _hash turns a string into a big number with md5, the same on every machine and every run.
    3. add puts a node on the ring 128 times (node#0 to node#127) so its share is spread out, using bisect to insert in order.
    4. node_for hashes the key, finds the first position clockwise from it, wraps around with modulo, and returns that position’s owner.
    5. The demo assigns 20,000 keys to four nodes and prints each node’s share.
    ratelimit.py — chunk 3runs offline
    class HashRing:
        """Consistent-hash ring with virtual nodes.
    
        Each physical node is hashed onto the ring `vnodes` times; a key belongs
        to the first vnode clockwise from its own hash. Removing a node deletes
        only that node's arcs, so only ~1/N of keys change owner.
        """
    
        def __init__(self, nodes=(), vnodes: int = 128):
            self.vnodes = vnodes
            self.nodes: set[str] = set()
            self._hashes: list[int] = []          # sorted vnode positions
            self._owners: list[str] = []          # parallel array: who owns each position
            for n in nodes:
                self.add(n)
    
        @staticmethod
        def _hash(s: str) -> int:
            # md5 for spread, not security -- stable across runs and machines
            return int.from_bytes(hashlib.md5(s.encode()).digest()[:8], "big")
    
        def add(self, node: str) -> None:
            if node in self.nodes:
                return
            self.nodes.add(node)
            for i in range(self.vnodes):
                h = self._hash(f"{node}#{i}")
                idx = bisect.bisect(self._hashes, h)
                self._hashes.insert(idx, h)
                self._owners.insert(idx, node)
    
        def node_for(self, key: str) -> str:
            if not self._hashes:
                raise LookupError("ring is empty")
            idx = bisect.bisect(self._hashes, self._hash(key)) % len(self._hashes)
            return self._owners[idx]
    
    if __name__ == "__main__":
        # (the bucket demo from chunk 2 stays above these lines)
        ring = HashRing([f"n{i}" for i in range(4)])
        keys = [f"user:{i}" for i in range(20_000)]
        before = {k: ring.node_for(k) for k in keys}
        share = {n: sum(v == n for v in before.values()) / len(keys)
                 for n in sorted(ring.nodes)}
        print("ring shares:", {n: f"{s:.1%}" for n, s in share.items()})

    bisect.bisect — binary search in a sorted list; hashlib.md5 — a stable hash used for spread, not security.

    Run python3 chunk3_ring.py. After the three bucket lines you should see burst: first 10 -> 10/10 allowed, 11th -> False / retry_after(1) -> 0.2s / after 0.4s: [True, True, False] / ring shares: {'n0': '24.1%', 'n1': '24.0%', 'n2': '27.0%', 'n3': '24.9%'}.

  4. Chunk 4 — remove a node and measure how many keys move

    This is the payoff of the ring and the claim an interviewer probes: when a node dies, only about its own share of keys should change owner, not all of them.

    Step-by-step: what chunk 4 does, in plain English
    1. remove drops only that node’s positions and leaves every other node’s untouched.
    2. Remember each key’s owner before (before was already built in chunk 3), remove n2, then count the keys whose owner changed.
    3. Print the moved fraction next to the ideal 1/N = 25%.
    ratelimit.py — chunk 4runs offline
    class HashRing:
        # (__init__, _hash, add and node_for stay as written in chunk 3)
        def remove(self, node: str) -> None:
            if node not in self.nodes:
                return
            self.nodes.discard(node)
            keep = [(h, o) for h, o in zip(self._hashes, self._owners) if o != node]
            self._hashes = [h for h, _ in keep]
            self._owners = [o for _, o in keep]
    
    if __name__ == "__main__":
        # (the demo from chunk 3 stays above these lines)
        ring.remove("n2")
        moved = sum(ring.node_for(k) != before[k] for k in keys)
        print(f"removed n2 -> {moved / len(keys):.1%} of keys moved (expected ~1/N = 25%)")

    A list comprehension over zip to filter two parallel lists together.

    Run python3 chunk4_remove.py (this is the whole program). The new last line is burst: first 10 -> 10/10 allowed, 11th -> False / retry_after(1) -> 0.2s / after 0.4s: [True, True, False] / ring shares: {'n0': '24.1%', 'n1': '24.0%', 'n2': '27.0%', 'n3': '24.9%'} / removed n2 -> 27.0% of keys moved (expected ~1/N = 25%).

The whole program

Chunk 1 is the imports and TokenBucket, chunk 2 is ManualClock and the first demo lines, chunk 3 is HashRing without remove and the ring-shares demo, chunk 4 is remove and the key-movement measurement. Each chunk starts with a # ── chunk n ── comment.

Step-by-step: what ratelimit.py does, in plain English
  1. Bring in three standard-library modules: bisect to keep a sorted list and search it, hashlib for md5, and time for the default clock.
  2. Define TokenBucket. Its constructor stores the capacity and the refill rate, starts the bucket full so a fresh client may burst, and accepts a clock function. The default is time.monotonic, which never jumps backwards. It records when the bucket was last refilled.
  3. _refill(): read the clock, add elapsed seconds times the rate, cap at capacity, remember the time. This is the refill drawn in Fig. A2.6b and pulled apart in the anatomy in §13, with the clock injected.
  4. allow(cost): refill, then spend if there is enough and return True; otherwise return False. The bucket never goes negative, so there is no token debt.
  5. retry_after(cost): refill, then compute how many seconds until the missing tokens will exist. Zero if the bucket can already pay. This number is what goes in the Retry-After header.
  6. Define ManualClock: an object you can call like a function to get the time, and advance by hand with advance(dt). Tests pass it in as the clock so they never sleep and always get the same answer.
  7. Define HashRing. It keeps a set of node names and two parallel lists: the sorted positions on the ring, and which node owns each position. Every node is placed on the ring vnodes times (128 by default), so its share of the ring is spread out and even.
  8. _hash(): md5 the string and take the first 8 bytes as an integer. md5 is used for spread, not for security, and it gives the same answer on every machine and every run, which Python's built-in hash() does not.
  9. add(node): for each of the 128 virtual positions, hash "node#i" and insert it into the sorted lists at the right place with bisect.
  10. remove(node): drop only that node's positions and owners. Every other node's positions are untouched, which is the whole point of consistent hashing.
  11. node_for(key): hash the key, use bisect to find the first position clockwise from it, wrap around the ring with modulo, and return the owner at that position.
  12. The demo builds a bucket of 10 at 5 per second on a manual clock. Ten of eleven burst calls are allowed. retry_after reports 0.2 s, and advancing the clock 0.4 s earns exactly 2 tokens. Then it builds a four-node ring and assigns 20,000 keys, printing each node's share (near 25%). It removes n2 and counts how many keys changed owner: about 27%, which is just n2's share.
ratelimit.pyruns offline
# ratelimit.py -- token bucket + consistent-hash ring, stdlib only (Python 3.10+)
# Run:  python3 ratelimit.py        Test:  pytest test_ratelimit.py -q
# ── chunk 1: the token bucket ──
import bisect
import hashlib
import time


class TokenBucket:
    """Classic token bucket: capacity B tokens, refills at r tokens/second.

    Lazy refill: instead of a background thread topping the bucket up, we
    compute how many tokens accrued since the last call. Same math, no timer,
    and it works identically with a fake clock in tests.
    """

    def __init__(self, capacity: float, refill_per_s: float, now=time.monotonic):
        self.capacity = float(capacity)
        self.refill_per_s = float(refill_per_s)
        self.tokens = float(capacity)   # a fresh bucket starts full -> bursts allowed
        self.now = now                  # injectable clock: determinism in tests
        self.last = now()

    def _refill(self) -> None:
        t = self.now()
        self.tokens = min(self.capacity,
                          self.tokens + (t - self.last) * self.refill_per_s)
        self.last = t

    def allow(self, cost: float = 1.0) -> bool:
        self._refill()
        if self.tokens >= cost:
            self.tokens -= cost
            return True
        return False                    # never goes negative: no token debt

    def retry_after(self, cost: float = 1.0) -> float:
        """Seconds until `cost` tokens exist -- this is your Retry-After header."""
        self._refill()
        return max(0.0, (cost - self.tokens) / self.refill_per_s)


# ── chunk 2: a clock you control ──
class ManualClock:
    """Deterministic clock so tests never sleep."""

    def __init__(self) -> None:
        self.t = 0.0

    def __call__(self) -> float:
        return self.t

    def advance(self, dt: float) -> None:
        self.t += dt


# ── chunk 3: the hash ring ──
class HashRing:
    """Consistent-hash ring with virtual nodes.

    Each physical node is hashed onto the ring `vnodes` times; a key belongs
    to the first vnode clockwise from its own hash. Removing a node deletes
    only that node's arcs, so only ~1/N of keys change owner.
    """

    def __init__(self, nodes=(), vnodes: int = 128):
        self.vnodes = vnodes
        self.nodes: set[str] = set()
        self._hashes: list[int] = []          # sorted vnode positions
        self._owners: list[str] = []          # parallel array: who owns each position
        for n in nodes:
            self.add(n)

    @staticmethod
    def _hash(s: str) -> int:
        # md5 for spread, not security -- stable across runs and machines
        return int.from_bytes(hashlib.md5(s.encode()).digest()[:8], "big")

    def add(self, node: str) -> None:
        if node in self.nodes:
            return
        self.nodes.add(node)
        for i in range(self.vnodes):
            h = self._hash(f"{node}#{i}")
            idx = bisect.bisect(self._hashes, h)
            self._hashes.insert(idx, h)
            self._owners.insert(idx, node)

    # ── chunk 4: remove a node (and measure it in the demo below) ──
    def remove(self, node: str) -> None:
        if node not in self.nodes:
            return
        self.nodes.discard(node)
        keep = [(h, o) for h, o in zip(self._hashes, self._owners) if o != node]
        self._hashes = [h for h, _ in keep]
        self._owners = [o for _, o in keep]

    def node_for(self, key: str) -> str:
        if not self._hashes:
            raise LookupError("ring is empty")
        idx = bisect.bisect(self._hashes, self._hash(key)) % len(self._hashes)
        return self._owners[idx]


if __name__ == "__main__":
    clock = ManualClock()
    b = TokenBucket(capacity=10, refill_per_s=5, now=clock)

    burst = [b.allow() for _ in range(11)]
    print(f"burst: first 10 -> {sum(burst[:10])}/10 allowed, 11th -> {burst[10]}")
    print(f"retry_after(1) -> {b.retry_after():.1f}s")
    clock.advance(0.4)                       # 0.4 s x 5 tok/s = 2 tokens back
    print(f"after 0.4s: {[b.allow() for _ in range(3)]}")

    ring = HashRing([f"n{i}" for i in range(4)])
    keys = [f"user:{i}" for i in range(20_000)]
    before = {k: ring.node_for(k) for k in keys}
    share = {n: sum(v == n for v in before.values()) / len(keys)
             for n in sorted(ring.nodes)}
    print("ring shares:", {n: f"{s:.1%}" for n, s in share.items()})

    ring.remove("n2")
    moved = sum(ring.node_for(k) != before[k] for k in keys)
    print(f"removed n2 -> {moved / len(keys):.1%} of keys moved (expected ~1/N = 25%)")

# Expected output:
#   burst: first 10 -> 10/10 allowed, 11th -> False
#   retry_after(1) -> 0.2s
#   after 0.4s: [True, True, False]
#   ring shares: {'n0': '24.1%', 'n1': '24.0%', 'n2': '27.0%', 'n3': '24.9%'}
#   removed n2 -> 27.0% of keys moved (expected ~1/N = 25%)
Step-by-step: what test_ratelimit.py proves, in plain English
  1. Import pytest and the three classes from ratelimit.py.
  2. test_refill_math: drain a bucket of 10 to zero and confirm the next call is denied. Advance the clock 2.5 s at 2 tokens per second. Exactly 5 calls succeed and the sixth fails, so the refill arithmetic is right to the token.
  3. test_burst_up_to_capacity_then_deny: with no time passing, a fresh bucket of 25 allows exactly 25 calls and denies the 26th. Bursts are permitted, up to capacity and no further.
  4. test_refill_caps_at_capacity: leave the bucket idle for 1,000 s, then confirm only 10 of 20 calls succeed. Idle time cannot accumulate beyond the cap.
  5. test_retry_after_is_exact: a bucket of 1 at 2 per second, spent once, reports 0.5 s until the next token. That number is what a client would see in Retry-After.
  6. test_ring_is_deterministic_and_balanced: asking the ring twice for 20,000 keys gives the same owners both times. Each of the four nodes owns a share within 8 percentage points of 25%.
  7. test_node_loss_moves_about_one_nth_and_nothing_else: record every key's owner, then remove n2. Two checks follow for every key. A key that lived on n2 now lives elsewhere. A key that did not live on n2 has not moved at all. The moved fraction is near one quarter. The second check is the exact claim of consistent hashing, not a statistical one.
test_ratelimit.pyruns offline
# pip install pytest==8.*
# test_ratelimit.py -- proves the three claims: refill math, burst behavior,
# and ~1/N redistribution on node loss.        Run: pytest test_ratelimit.py -q
import pytest

from ratelimit import HashRing, ManualClock, TokenBucket


def test_refill_math():
    clock = ManualClock()
    b = TokenBucket(capacity=10, refill_per_s=2, now=clock)
    for _ in range(10):                      # drain the bucket to zero
        assert b.allow()
    assert not b.allow()
    clock.advance(2.5)                       # 2.5 s x 2 tok/s = exactly 5 tokens
    assert [b.allow() for _ in range(6)] == [True] * 5 + [False]


def test_burst_up_to_capacity_then_deny():
    clock = ManualClock()
    b = TokenBucket(capacity=25, refill_per_s=1, now=clock)
    assert all(b.allow() for _ in range(25))  # full burst allowed, no time passing
    assert not b.allow()


def test_refill_caps_at_capacity():
    clock = ManualClock()
    b = TokenBucket(capacity=10, refill_per_s=2, now=clock)
    clock.advance(1_000)                     # idle for ages -> still only B tokens
    assert sum(b.allow() for _ in range(20)) == 10


def test_retry_after_is_exact():
    clock = ManualClock()
    b = TokenBucket(capacity=1, refill_per_s=2, now=clock)
    assert b.allow()
    assert b.retry_after() == pytest.approx(0.5)   # 1 token / 2 per sec


def test_ring_is_deterministic_and_balanced():
    ring = HashRing(["n0", "n1", "n2", "n3"])
    keys = [f"user:{i}" for i in range(20_000)]
    owners = [ring.node_for(k) for k in keys]
    assert owners == [ring.node_for(k) for k in keys]   # same key -> same node
    for n in ring.nodes:                      # 128 vnodes -> shares near 25%
        assert owners.count(n) / len(keys) == pytest.approx(0.25, abs=0.08)


def test_node_loss_moves_about_one_nth_and_nothing_else():
    ring = HashRing(["n0", "n1", "n2", "n3"])
    keys = [f"user:{i}" for i in range(20_000)]
    before = {k: ring.node_for(k) for k in keys}
    ring.remove("n2")
    moved = 0
    for k in keys:
        after = ring.node_for(k)
        if before[k] == "n2":
            assert after != "n2"             # orphans re-homed...
            moved += 1
        else:
            assert after == before[k]        # ...and NOBODY else moves. Exact.
    assert moved / len(keys) == pytest.approx(0.25, abs=0.10)

# Expected: 6 passed

17 · Interview radarHow the Classic Round Actually Probes

Interview radar

Per the market research, FAANG-tier loops run traditional, ML, and GenAI design rounds side by side — and screeners explicitly probe failure-mode awareness. These five prompts cover ~80% of what the traditional round asks a senior candidate.

"Design X at scale."

The real test The opener grades minute one — requirements before boxes.

Strong answer Start by asking for numbers: how many users, what read:write ratio, what latency target, what consistency needs. Run the capacity math out loud, and only then draw Fig. A2.1, shaped to the answers you just got.

Land it Candidates who draw boxes first are pattern-matching; candidates who ask for numbers first are engineering — a 120-second habit that changes the round's grade.

"Would you sacrifice consistency or availability?"

The real test The CAP trap — a false binary the senior candidate refuses, politely.

Strong answer "During a partition — because that's the only time the tradeoff exists — and per data class: payments go CP, while browse and counters go AP with reconciliation afterward. In normal operation the dial is latency vs consistency."

Land it That is the complete senior answer in three sentences.

"How would you shard this?"

Strong answer Name the key and defend it against the hot-key attack before it comes: "Hash-shard on user_id for even spread. Range queries will scatter, which I accept because our access pattern is point lookups. Celebrity keys get salted across sub-shards."

Land it Give the resharding path too: consistent hashing, so growth moves 1/N of the keys rather than everything.

"Walk me through what happens when a node dies."

The real test The narration question — it tests whether you've lived it.

Strong answer Narrate the failure tier by tier:

  • App node — the health check fails, the load balancer ejects it, in-flight requests retry idempotently, and nobody notices
  • Cache node — 1/N of the keys go cold, and coalescing absorbs the refill
  • Primary — heartbeats miss, a quorum elects the most-caught-up replica, and fencing blocks the old leader

Land it The replication-lag window is the data-loss conversation — raise it before they do.

"How much storage for 90 days of events?"

The real test Capacity estimation on the spot — a method test, not an arithmetic test.

Strong answer State your assumptions, round to powers of ten (a day is 10⁵ seconds), multiply, and sanity-check the result against real hardware: "54 TB — a small cluster, not a data-lake problem."

Land it Showing the method with wrong-by-2× numbers scores; silent precision doesn't.

Quick reference — Distributed systems

The three-question rubric
Does it scale? What fails? What does it cost? Answer all three unprompted, before being asked, and you are already scoring like a senior candidate.
Vertical vs horizontal
Vertical is a bigger machine — simple, and it runs out. Horizontal is more machines — unlimited in theory, and it requires the tier to be stateless.
Load balancing
Round-robin · least-connections · consistent-hash. Consistent hashing is what keeps a cache useful when the node count changes.
Cache invalidation
TTL is simple and serves stale data. Explicit invalidation is correct and easy to get wrong. Most systems use both, deliberately.
thundering herd
A popular key expires and every request goes to the database at once. Fixes: request coalescing, jittered TTLs, and serving stale while refreshing.
Replica lag
Read replicas are behind. Reading your own write from a replica returns the old value — route to the primary briefly after a write.
Split-brain
A network partition leaves two halves each believing they are in charge. This is why consensus needs a quorum.
Quorum overlap (R + W > N)
A write that waits for W copies and a read that asks R of the same N must share a replica when R + W > N. With N = 3 and W = R = 2 all 9 pairs share one, and at 99.9% per replica the quorum refuses about 8 seconds a month.
Idempotency key
One key per order, created before the first attempt and sent on every retry. The server replays the stored answer instead of charging again; a new key on each try is the same as no key.
Full jitter
Wait a random time between 0 and the backoff. After a 250 ms outage it got 497 of 1,000 failed requests served, against 30 for lockstep backoff with almost the same number of retries.
Picking a building block
Ask what the block must survive. Redis for shared fast state, Postgres until one primary cannot take the writes, a Kafka log when consumers need replay, a plain queue (SQS, RabbitMQ) when they do not.
p99
Sort the requests and read the 99th of every 100. Two retried charges in 100 move the average from 40 to 52 ms, and p99 from 40 to 640 ms.

18 · RecapWhat You Can Do Now

  • You can draw the canonical request path in 90 seconds and narrate every hop's purpose, failure mode, and scaling lever
  • You can choose and defend a caching strategy — write policy, invalidation, TTL jitter, herd control — and explain why consistent hashing moves 1/N keys, with code to prove it
  • You can state the sync/async replication tradeoff in one sentence and design around replica lag with read-your-writes
  • You can state CAP correctly, extend to PACELC, and set N/R/W quorums per data class with the overlap math
  • You can design async pipelines with at-least-once delivery, idempotency keys, and the outbox pattern — and say why exactly-once is an end-to-end contract
  • You can armor any dependency with timeouts, jittered backoff under a retry budget, circuit breakers, and a named degraded mode — and point at your Module 12 gateway as proof
  • You can run DAU → QPS → storage capacity math out loud in under five minutes
  • You can price an SLO in minutes per month and in revenue — and argue for or against the next nine in front of a CFO
  • You can check R + W > N case by case for three replicas, and say what a W = 2 or W = 3 quorum costs in refused seconds or minutes a month
  • You can walk one payment through a timeout and a retry, say why the idempotency key belongs to the order, and explain what jitter and a retry budget each change
🧠 Flex your memory

From this appendix: close the page and redraw Fig. A2.1 from memory, then write the token-bucket refill line — tokens, capacity, elapsed × rate — without peeking.

From Module 12: list which four patterns from this appendix your LLM gateway already implements, and which one it is missing.

From Module 01: compute the monthly error budget for 99.95%, and explain in one sentence why that objective is written against p99 latency rather than the mean.