Chapter 41 — System Design Mastery
Part VIII · Synthesis | Prerequisites: Parts I–VII | Builds: the repeatable method applied to redesign Pulsely features at 100x scale
You can build the endpoint. You proved that across forty chapters — you can route a request, model the data, wrap it in a transaction, cache the hot path, push the slow work to a queue, and ship it through a canary pipeline. Each of those was a box on the spine you learned to furnish. This chapter is the opposite move: it asks you to draw the whole house, under time pressure, for a system that doesn't exist yet, in front of someone who will interrupt you. That is the system-design conversation — the interview round, yes, but also every RFC, every design review, every incident postmortem where someone asks "why is it shaped like that?"
Nothing here is new infrastructure. The skill is a method: a disciplined order in which to apply the mechanisms you already own, plus the ability to narrate the tradeoffs aloud so a listener can follow your reasoning. We'll state the method, then prove it on five canonical designs — a rate limiter, a URL shortener, an activity feed, a messaging system, a notification system — each one reusing prior chapters by reference, never re-teaching them. Then we redesign three real Pulsely features at 100x. This is the chapter where Parts I–VII converge into one motion.
📎 Borrowed on credit: the rest of the interview loop. This chapter owns the design round and nothing else. The behavioral/STAR stories, the coding round, leveling rubrics, and salary negotiation are a separate craft — they live in Ch 44. Here, "interview" means "narrate a system design." When I say "the senior tell," I mean the design signal, not the career signal.
1. The problem: the developer who freezes at the whiteboard
Here's the scene, because almost everyone pivoting into backend lives it once.
You're in a loop. The interviewer says, "Design the provider worklist — the feed of new results and alerts across a clinician's whole patient panel." You know worklists. You've built one — you built Pulsely's. So you start drawing: a chart_events table, a care_team table, SELECT ... WHERE patient_id IN (my_panel) ORDER BY created_at. Reasonable. Then she asks, "What happens when a drug-recall notice has to land in five million charts at once?" and you stall. Not because you don't know about queues or partitioning — you wrote those chapters of your own brain. You stall because you have no order of operations. You don't know whether to talk about sharding or caching or the fan-out worker first, you haven't said a single number out loud, and the silence reads — fairly or not — as "not senior."
The same gap shows up in production, just slower and more expensive. A feature ships. It works in staging, where there are forty rows. Week two of the launch, real traffic arrives, and it falls over — nobody estimated the fan-out, nobody estimated storage growth, the design was vibes plus the framework defaults. The postmortem says "we didn't anticipate the load," which is a polite way of saying nobody did the arithmetic.
So the missing thing is not knowledge. You already met queues, caches, replication, partitioning, indexes, idempotency, and the consistency spectrum. The missing thing is a repeatable method for applying them in the right order, under ambiguity, while talking. And the reason to learn it from first principles rather than memorizing famous designs is simple: a memorized answer collapses the instant the requirements shift. Change the read/write ratio, change the latency target, change "5M patients" to "5M devices, 30k providers," and the canned answer is wrong while a derivation still holds. You don't want the answer. You want the machine that produces the answer.
🧭 Mental model. A system design is a funnel, not a checklist:
requirements → numbers → contract → boxes → one deep box → where it breaks → what you traded. Each stage constrains the next. Skip a stage and everything below it floats free — you're sharding before you know the QPS, optimizing a box nobody validated is on the critical path. The funnel is the whole method; the rest of this chapter is learning to walk it without rushing.
2. The mental model: numbers pick the architecture
Hold one governing idea above all others: a design is a set of constraints meeting a set of mechanisms, and your job is to find the cheapest mechanism that satisfies the hardest constraint — not to assemble the most impressive architecture you can name.
That reframes everything. You are not "designing a worklist." You are answering: given these numbers, what is the simplest arrangement of boxes-on-the-spine that holds? The numbers do most of the deciding for you. QPS, payload size, read/write ratio, growth rate — feed those four in and the architecture mostly falls out. Design without them and you are guessing, and a trained interviewer can smell a guess from across the room.
Two disciplines fall out of this, and they separate people who sound senior from people who merely know words.
Think one axis at a time. "Scale" is not one problem. Scaling reads, scaling writes, scaling storage, and scaling fan-out are four different problems with four different families of solution, and conflating them is the single biggest cause of muddled designs. Read-heavy? You reach for caches, replicas, denormalization (store the answer pre-joined so a read is one lookup, not a five-table assembly), and precompute. Write-heavy? Partitioning, append-only logs (only ever add rows, never rewrite one in place — which keeps writes fast), compute-on-read (do the assembly work when someone asks, so the write stays cheap), and async aggregation (roll the numbers up in a background job instead of on the write path). When someone says "it won't scale," your first move is to ask which axis — because the answer changes completely.
Treat the design as a living artifact with stated assumptions. Every "I'll assume 10 chart entries per patient per day" is a knob, written down, visible. When the interviewer pushes back — "what if it's 100?" — you don't start over; you turn one knob and re-derive. The assumptions are not throat-clearing; they are the thing that makes your design robust to questioning, which is exactly what the round is testing.
🔑 The numbers-first invariant. No box gets drawn before a number justifies it. Capacity estimation precedes architecture, always. If you cannot say roughly how many requests per second, how many bytes of new data per day, and whether the workload is read- or write-dominated, you are not ready to choose a mechanism — and choosing one anyway is the cardinal junior error. This echoes what you saw earlier: measure per hop before you optimize. You do not out-architect arithmetic you never did.
3. Theory & invariants: the seven steps and the numbers that drive them
The method is seven steps, in order, none skippable. Memorize the order; the order is the skill.
- Clarify requirements — functional (what it does) and non-functional (how well), and explicitly scope things out. "We'll support charting an encounter and reading the timeline; we'll ignore ranking and co-sign workflows for now." Scoping out is not weakness — it's the senior tell that you know the system is bigger than the time.
- Estimate scale — turn the product into numbers: QPS, peak QPS, storage growth, bandwidth, working-set size.
- Define the contract — the API (endpoints, shapes, pagination) and the data model (tables, the partition key, the hottest query).
- High-level design — the boxes and the data flow between them. Breadth, not depth.
- Deep-dive one component — pick the interesting one and go to the bottom of it. Exactly one.
- Find bottlenecks — name the single points of failure and the first resource to saturate, before you're asked.
- State tradeoffs — for each major choice, the rejected alternative and the condition that would flip your decision. Plus: "with more time/budget, I'd…"
Each step has a home, and you state each rule once, in its home, then build on it.
Clarifying is itself a graded skill. Step 1 is not a formality you rush through to "get to the design." A vague prompt is deliberately vague — "design a worklist" hides whether it's chronological or prioritized, whether 99% or 1% of a panel is active daily, whether a ten-second delay is fine or fatal. Each ambiguity you surface and pin is a decision you've earned the right to make. The questions that move the design: who are the actors and what are the top three operations? read-to-write ratio? latency target — p50 and p99? is stale data acceptable, and for how long? what's the growth curve? what's explicitly out of scope? Ask these and the design narrows itself; skip them and you'll design the wrong system beautifully.
Non-functional requirements are first-class. Features tell you what to build; the non-functionals tell you what shape it must take, and they decide far more than features do. The five that matter: latency target (p50 and p99 — and recall that p99 is what users feel), availability (how many 9s, and what an hour of downtime costs in dollars — or in a missed critical result), consistency need (read-your-writes vs eventual), durability (can we ever lose a write? — a dropped claim or a lost lab result is not negotiable), and a cost ceiling. A worklist tolerates eventual consistency and a stale p99; a claim ledger and a booked appointment slot do not. Same domain, opposite shapes, because the non-functionals differ.
Capacity estimation has a small vocabulary, and you must have it cold.
QPS (avg) = DAU × actions/user/day ÷ 86,400 (seconds/day ≈ 100,000)
QPS (peak) ≈ avg × 2 to 10 (diurnal + spikes)
storage = objects × avg_size × retention × replication_factor
bandwidth = QPS × payload_size
cache size = working_set (the hot subset), not the whole corpus
And the round-number kit that makes mental math fast and defensible: seconds/day ≈ 100k; 1 character ≈ 1 byte; a typical row ≈ a few hundred bytes; 1 million events/day ≈ ~12/sec average; a million seconds is ~11.5 days. You are not computing to three significant figures — you are establishing magnitude. "Is this thousands or billions of rows?" decides the architecture; the second digit never does.
Watch it run once. Pulsely worklist, 10M active users (patients checking results, clinicians working panels), each opens their timeline 5×/day, and 2 new chart entries land per user/day. Reads = 10M × 5 ÷ 100k = 500 reads/sec average, peak ×5 ≈ 2,500/sec. Writes = 10M × 2 ÷ 100k = 200 writes/sec average. That ratio — reads outrunning writes ~2.5:1 even before peak, and each read fanning across a care-team/panel graph — lands us squarely on the read-heavy side of the fork, which immediately recommends precompute + cache. Three multiplications told us the architecture family. That's why estimation precedes boxes: it isn't busywork, it's the step that makes the next decision obvious.
🔑 The read/write fork is the master decision. Before any mechanism, classify the workload. Read-heavy → cache + read-replicas + denormalize + fan-out-on-write (precompute the answer so reads are cheap). Write-heavy → partition + append-only + fan-out-on-read (assemble at read time so writes stay cheap) + async aggregation. Almost every "which pattern?" question is really "which side of this fork am I on?" — answer that first and the mechanism family chooses itself.
The tradeoff axes are few, and you'll argue the same six forever: consistency vs availability, latency vs cost, read-optimized vs write-optimized, simplicity vs flexibility, push vs pull, sync vs async. Every real decision lands on one of these. Knowing the list means you're never surprised by a tradeoff — you're just locating which axis this particular choice sits on.
📎 Borrowed on credit: the CAP intuition. When I say "consistency vs availability," I'm leaning on Ch 23–24's distributed-systems theory — that under a network partition you must choose. I won't re-derive it; I'll use it as a move. Likewise "at-least-once delivery" (Ch 25) and "the tail is the user experience" (Ch 30) are tools I pick up without re-explaining. This is a synthesis chapter; the theory is paid for.
4. Under the hood: five worked designs, each reusing the book
This is the heart of the chapter. Five canonical designs, each walked through the funnel, each a chance to watch prior chapters show up as moves rather than topics. First, the map of which part supplies which move:
requirements/contract ── Ch 10–11 (REST, pagination, versioning)
data model/partition ── Ch 16, 18 (modeling, how DBs store bytes, sharding)
caching ── Ch 21 (cache-aside, TTL, invalidation, hot keys)
async / fan-out ── Ch 26–27 (queues, backpressure, retries/DLQ, log streaming)
idempotency / dedupe ── Ch 25 (dedupe keys, exactly-once-effect)
consistency ── Ch 23–24 (strong vs eventual, replication lag)
reliability ── Ch 33 (timeouts, retries, circuit breakers, SLOs)
realtime ── Ch 28 (WebSockets, presence, connection routing)
Keep that table in your peripheral vision. Every design below is just selecting rows from it. Notice what the five designs collectively cover: a read-heavy cache problem (shortener), a write-amplification problem (feed), a coordination problem (rate limiter), a stateful-connection problem (messaging), and an at-least-once-delivery problem (notifications). Those five shapes recur across nearly every system you'll ever design — learn them here and most "new" prompts decompose into combinations you've already solved.
Worked design 1 — Rate limiter
Requirements. Cap a caller to N requests per window; reject (429) or shed beyond it. Non-functional: must add <1ms to the hot path and must itself never be the bottleneck. Scope out: billing, quotas-as-a-product.
The algorithm fork. Fixed window (a counter per minute) is trivial but allows a 2× burst at the boundary. Sliding-window log (timestamps of every request) is exact but stores one entry per request — expensive. Token bucket is the workhorse: a bucket refills at a steady rate, each request spends a token, empty bucket → reject. It permits controlled bursts and costs two numbers per key (token count, last-refill time). Default to token bucket and say why.
Where it lives. At the gateway (the edge — protects everything behind it), in the app (per-route nuance), or a sidecar. Edge for blanket protection; app tier when the limit depends on business state.
The distributed problem — and this is the whole interview. With many app instances (the server is plural), a per-node in-memory counter lets a user do N×(node count) by spraying requests across nodes. So you need a shared counter with an atomic increment — Redis, INCR + EXPIRE, or a Lua script for atomic token-bucket math:
// Atomic token-bucket check in Redis (Lua keeps refill+spend a single op — no race).
const allowed = await redis.eval(TOKEN_BUCKET_LUA, {
keys: [`rl:${userId}`],
arguments: [String(capacity), String(refillPerSec), String(now())],
}); // returns 1 = allow, 0 = reject. One round trip, one source of truth.
🔑 Accuracy costs coordination. Per-node approximate limiting is cheap and leaky; global exact limiting needs a shared store and adds a network hop plus a dependency. Choose by what an over-limit actually costs. Protecting the patient-portal login from credential-stuffing? Be exact. Smoothing a read API? Approximate-per-node is fine, and you've saved yourself a Redis round trip on every request.
The JVM contrast where it teaches: in Express this is middleware; in Spring it's a Filter or HandlerInterceptor — same position in the chain, same shared-counter problem, just a thread-per-request runtime (one OS thread per in-flight request) instead of an event loop. The coordination problem is identical; the runtime is incidental.
Contract. 429 Too Many Requests with a Retry-After header and X-RateLimit-Remaining so a well-behaved client backs off instead of hammering — the limiter's response is part of its design, not an afterthought. A bad limiter that just drops connections trains clients to retry harder.
Worked design 2 — URL shortener
Requirements. POST /urls {long} → {short}; GET /{short} → 301/302 redirect. Read-heavy, extremely — billions of reads, comparatively few writes. (We keep this classic in the mix because it's the cleanest read-heavy shape there is — the same shape as caching a patient's chart-header or an eligibility response.)
The numbers, fast. Say 100M new links/day → ~1,200 writes/sec avg, but reads at 100:1 → ~120k reads/sec. Now the storage, one step at a time: 100M links × ~500 bytes ≈ 50 GB of new rows per day. Over five years that's 50 GB × 365 × 5 ≈ 90 TB. Times replication 3 ≈ 270 TB — call it a few hundred TB. That magnitude tells you: storage is non-trivial but ordinary; the read path is the whole game.
Deep-dive: key generation (the genuinely interesting component). Three options:
- Hash the URL, take 7 base62 chars — deterministic, but collisions force a check-and-retry.
- A global counter, base62-encode it — no collisions, but the counter is a write hotspot and the keys are guessable/sequential.
- A pre-generated key pool — a background job mints random unused keys into a table; the write path just claims one. No collision check on the hot path, no counter hotspot. This is usually the senior answer because it moves the hard work off the request path entirely.
Read path. Cache the hot short→long map aggressively (cache-aside) — a tiny fraction of links get nearly all the traffic, so the cache hit rate is huge and the database barely feels the reads.
Why the pre-generated pool wins, concretely. Hash-and-check costs a read (collision lookup) on every write, and the lookup gets slower as the table fills. The counter creates a single hot row every write contends on — and exposes your growth rate to anyone who decodes two sequential keys. The pool moves both costs off the request path: minting happens in a background job during idle capacity, and the write path does one indexed UPDATE ... WHERE claimed = false LIMIT 1 (the SKIP LOCKED pattern — SKIP LOCKED tells the database: when you grab an unclaimed key row, skip any row another request is already claiming instead of waiting in line behind it, so a hundred simultaneous writers each grab a different key with nobody blocking). The hot path pays nothing for uniqueness. That move the expensive work off the critical path instinct is the same one behind worklist fan-out and async notifications — it's a recurring senior reflex, not a shortener trick.
The one detail that flips on the requirements: 301 vs 302. A 301 (permanent) lets browsers and CDNs cache the redirect — fastest, cheapest. But if you want click analytics, a cached 301 means the request never reaches you, so you can't count it. Need analytics → 302 (temporary), accept that every click hits your server. Watch how a single non-functional requirement (analytics) reverses a technical choice — that's the funnel working.
Worked design 3 — Provider worklist / chart-activity feed (the Pulsely-relevant one)
Requirements. A clinician opens Pulsely and sees recent activity — new results, RPM alerts, patient messages — for the patients on their panel, newest-ish first. Read-heavy, latency-sensitive (the worklist is where clinicians live all day), and eventual consistency is fine within a small window — nobody is harmed if a routine result takes ten seconds to surface. A critical value is different: it does not ride the eventually-consistent feed, it takes the alert path (design 5). Naming that split out loud is a clinical-safety tell.
Contract and data model — name them before the boxes. GET /worklist?cursor=<opaque>&limit=20 with keyset pagination, never OFFSET — at panel scale, offset pagination re-scans rows it then throws away, so the deepest scrolls are the slowest, exactly backwards. The data model has a chart_events table (the source of truth, partitioned by event_id) and, for the push path, a worklist store keyed by provider_id holding an ordered list of event IDs — the precomputed answer. Name the partition key out loud: chart_events by event_id so writes spread; the worklist by provider_id so a read is a single key lookup. That choice constrains everything downstream.
The master fork — and the broadcast that breaks it. Two strategies:
- Fan-out-on-write (push): when a patient event lands (a new result), immediately write that event's ID into the precomputed worklist of every care-team member watching that patient. Reads are then trivial — just read your own worklist list. Fast reads, cheap delivery. But a broadcast event — a drug-recall notice or public-health advisory that must land in 5M patient charts / every provider's worklist — enqueues 5M writes, most into worklists nobody opens today. The broadcast tail breaks pure push.
- Fan-out-on-read (pull): store events once; at read time, gather events from every patient on your panel and merge. Writes are trivial. But reads are expensive — a high-panel provider on the care team of thousands of patients does thousands of lookups and a merge on every worklist open.
PUSH (fan-out-on-write) PULL (fan-out-on-read)
event ─▶ [fan-out worker] ─▶ write event ─▶ store once
into N care-team worklists read ─▶ gather across M panel patients, merge
broadcast (recall → 5M charts): broadcast:
one event ─▶ 5M writes ✗ explodes one event ─▶ 1 write ✓
read: O(1) ✓ read: O(M) merge, high-panel providers slow ✗
The senior answer is hybrid. Push for normal-cardinality events (cheap fan-out, fast reads); pull for the handful of high-fan-out broadcast sources — a recall notice is fetched-and-merged at read time so a single population event doesn't trigger millions of writes. You detect "broadcast" by a fan-out-cardinality threshold and route per-event. Prioritization, if any (surfacing overdue or high-acuity items first), is a separate stage layered on top of retrieval — don't entangle "what's in the worklist" with "in what order."
Deep-dive: the fan-out worker and its queue. The push path is an async pipeline: an event lands → a job is enqueued → workers fan it out into care-team worklists stored in a fast read store (Redis lists or a denormalized table). The queue is the shock absorber: a burst of events grows the queue depth, not the request latency. And the queue depth is your early-warning metric — when it climbs, fan-out is falling behind, and you scale workers or shed the broadcast tail to pull.
Worked design 4 — Secure messaging system
Requirements. 1:1 provider–patient messages and care-team group threads, delivered in near-real-time, with ordering and read receipts; show who's online. All of it is PHI, so every message is auditable. The defining non-functional: persistent connections, which changes everything about scaling.
Connection model. Long-polling works but wastes resources; WebSockets are the right tool — a durable bidirectional pipe. This is where the runtime matters. Node keeps tens of thousands of sockets open cheaply because each idle socket is just an entry in the event loop — think 50k React Query subscriptions parked waiting on data, not 50k running functions. A traditional Java server historically gave each open connection its own OS thread, and 50k mostly-idle threads is 50k stalled workers eating memory — so even the Java world switched to an event-loop-style approach (Netty) for this workload. The concurrency model sets your connection ceiling per box.
The stateful-scaling problem — the deep-dive, and the thing that makes messaging hard. A WebSocket is stateful: provider A's socket lives on app node 3. When patient B (whose socket is on node 7) sends A a message, node 7 must find and reach node 3. This breaks the stateless-instances assumption you relied on earlier. Two standard moves: a connection registry (which node holds which user's socket — in Redis) so node 7 can route to node 3, or a pub/sub backbone where node 7 publishes to a channel node 3 subscribes to. Messages persist to a store (partitioned by conversation ID — that's your partition key, name it early) so history survives reconnects and offline users get delivery on return.
Ordering and receipts. Per-conversation ordering via a monotonic sequence or server timestamp; read receipts are just another small message type fanned out to the conversation's members. Note the subtle trap: client clocks lie, so ordering must be assigned server-side on write — the server stamps the sequence, not the sender. Group fan-out reuses the worklist's push/pull thinking at smaller scale: small care-team threads push to each member's inbox; a broadcast thread to an entire clinic is a "broadcast" again and wants pull. The same fork, a third time — which is the point of working five designs: the moves repeat.
Presence. "Online" is soft, high-churn state — store it in Redis with a short TTL refreshed by a heartbeat, never in the durable DB (you don't want a write to Postgres every time someone's connection blips). Presence is the one place here where losing the data on restart is fine, so it gets the cheapest, most ephemeral store.
Worked design 5 — Notification / clinical-alert system
Requirements. "Critical potassium — 6.9," "lab result ready," "appointment reminder," "task assigned to you" — delivered across multiple channels (in-app push, secure message, SMS, pager/email), respecting user preferences and clinical escalation rules, never double-sent. This is an async pipeline, end to end.
Shape. An event ("observation.critical") enters a queue. A pipeline stage resolves who to notify (the care team) and which channels (their preferences), renders from a template, dedups, then hands each channel-message to a provider adapter (APNs/FCM, an SMS gateway, a paging service, an email API) behind a uniform interface so channels are pluggable. Critical alerts carry an escalation policy: if the on-call clinician doesn't acknowledge within N minutes, escalate to the covering provider — silence on a critical value is itself a failure mode.
event ─▶ [queue] ─▶ resolve recipients+prefs ─▶ template ─▶ dedup ─▶ ┬─▶ in-app push
├─▶ secure message
└─▶ sms / pager
each provider call: timeout + retry + failover
critical + unacknowledged ─▶ escalate to covering provider
🔑 Idempotency is the load-bearing invariant here. The queue is at-least-once — your worker will occasionally see a message twice (redelivery, a retry after a timeout that actually succeeded). Without a dedupe key, a retry double-sends, and a clinician gets the same critical alert twice, or the same page five times. Carry an idempotency key
(event_id, recipient_id, channel); record "sent" before acknowledging; a duplicate finds the record and no-ops. A notification pipeline without idempotency is a spam generator with extra steps — and in a clinical setting, repeated duplicate alerts are an alert-fatigue generator, which desensitizes clinicians to the real ones. That's a patient-safety bug wearing a plumbing costume.
Provider calls get the full reliability treatment — per-provider timeouts, jittered retry, circuit-break a dead provider, and failover to a backup channel/provider so one vendor outage doesn't silence all alerts.
🛑 What we deliberately did not re-explain. How Redis executes that atomic increment (Ch 21); how the queue guarantees at-least-once and how a DLQ works (Ch 26); how WebSockets multiplex over one TCP connection (Ch 28); how replication lag produces stale reads (Ch 19, 24); how a circuit breaker decides to open (Ch 33). Each is a furnished room from earlier in the book. This chapter only shows which rooms a given design walks through, and in what order. That restraint is the synthesis discipline — cite, don't re-teach.
5. In production: the cadence, the worksheet, and the boring baseline
A design conversation has a clock, and managing it is half the performance. The cadence that keeps you out of ratholes:
~15% requirements (functional + non-functional + scope-out)
~15% estimation (QPS, storage, read/write fork)
~20% API + data model (contract, partition key, hottest query)
~25% high-level design (boxes + data flow — breadth)
~20% one deep-dive (the interesting component)
~5% tradeoffs + "what breaks first" + "with more time"
Narrate the budget out loud — "I'll spend a couple minutes on requirements before I draw anything" — and you've already signaled seniority, because you've shown you know that jumping to boxes is the failure mode.
Keep the assumptions visible. Write them where you (and the interviewer) can see them. Every number you derive traces back to one. When a constraint changes, you change the assumption and re-derive downstream — you never start over. This is the single habit that makes a design survive an hour of pushback.
Default to the boring baseline, then break it on purpose. Open every design with: "single primary Postgres + a cache + a queue." For an enormous fraction of real systems, that is the answer, and saying so earns credibility — it shows you don't reach for Kafka and sharding reflexively. Then use the numbers to prove where the baseline breaks ("at 120k reads/sec one primary can't serve reads, so I add replicas; at this RPM write rate the primary's write IOPS saturate, so now I partition"), and add complexity exactly there. Complexity introduced to solve a demonstrated bottleneck reads as senior; complexity introduced upfront reads as cargo-culting.
Treat pushback as a gift, not an attack. When the interviewer says "what if writes are 10× higher?" they are not catching you out — they're handing you the chance to demonstrate the one assumption, re-derive habit. The wrong reflex is to defend your original number or quietly rebuild from scratch. The right one: "Good — let me change that assumption. At 10× writes, the primary's write IOPS saturate, so the boring baseline breaks here, and now I partition by X." You've shown the design is a machine that responds to inputs, not a memorized artifact. Every pushback you absorb gracefully is points; every one you resist is a flag.
Pre-empt the bottleneck question. Before the interviewer asks "where does it fail?", say it: "The first thing to saturate here is the fan-out queue depth; the early-warning metric is queue lag; the mitigation is more workers, and if that's not enough, route broadcasts to pull." Naming your own single point of failure before being asked is one of the clearest senior tells in the whole round.
🏭 The interview is a rehearsal for the doc. This isn't a trick you do only in interviews. The RFC/design-doc template — context, goals, non-goals, proposed design, alternatives, risks — is the seven steps in document form. The same arithmetic, the same stated assumptions, the same "what breaks first," just written down and reviewed asynchronously. Master the spoken version and the written one comes nearly free. The capacity worksheet you build here is the same worksheet you'll paste into the design doc on the job.
The worksheet itself, which you should be able to fill from a one-line prompt in under ten minutes:
INPUTS: DAU · actions/user/day · avg payload · read/write ratio · retention · peak ×
DERIVE: avg QPS · peak QPS · storage/yr · bandwidth · cache (working set) · #partitions
6. Common pitfalls
Each is signature → fix. These are the ways the design round goes wrong, and every one is recoverable if you catch the signature in yourself.
Jumping straight to detail. Signature: you're three minutes in, deep in a sharding scheme, and nobody has validated the system even needs sharding — you skipped straight to a box. Fix: force yourself through steps 1–2 out loud before drawing anything. "Let me get the requirements and a rough QPS first." The discipline of saying it makes you do it.
Ignoring scale. Signature: your design is identical whether it's 1,000 patients or a hundred million; not one number was spoken. Fix: do the estimation. Let QPS and storage tell you what changes. A design that doesn't move with the numbers is a design that did no arithmetic.
No tradeoffs stated. Signature: every choice is presented as obviously correct, with no alternative and no condition that would change it. Fix: for each major box, name the rejected option and the trigger to reverse. "I chose push fan-out; I'd switch to pull for broadcast events over ~100k recipients." A choice with no stated alternative isn't engineering, it's a guess that happened to be right.
Boiling the ocean. Signature: five new subsystems sketched, none of them deep — breadth with no bottom. Fix: breadth in the high-level pass, then one deliberate deep-dive. Depth on one component beats shallow on five, every time.
Hand-waving the data model.
Signature: boxes connected by arrows, but no schema, no partition key, no index named.
Fix: name the partition key and the hottest query early — they constrain everything downstream. A worklist partitioned by provider_id and one partitioned by event_id are different systems.
Mismatched mechanism. Signature: fan-out-on-write for a write-heavy, low-read feature; strong consistency where eventual is fine. Fix: classify read-heavy vs write-heavy first (§3's master fork), then pick the matching family. The mismatch is almost always a skipped fork.
Silent reasoning. Signature: long pauses, you arrive at a correct answer, but the interviewer couldn't follow how — so they can't credit it. Fix: narrate the funnel continuously. The process is the score, not the endpoint. A correct answer nobody could follow scores worse than a flawed one narrated clearly, because the round measures how you think, not whether you've memorized this particular system.
7. Tradeoffs
The six axes from §3, now as decisions you argue — each with the rejected side and the condition that flips it.
Push (fan-out-on-write) ↔ pull (fan-out-on-read). Push buys fast reads and cheap delivery but explodes on high fan-out and wastes work on inactive recipients. Pull is write-cheap and simple but slow on reads at scale. Reverse toward hybrid the moment the fan-out distribution is heavy-tailed (any real panel/broadcast mix) — push the normal-cardinality events, pull the broadcasts and high-panel providers.
Strong ↔ eventual consistency. Strong simplifies reasoning but caps availability and throughput and adds latency. Eventual scales but pushes staleness into the product, where you must handle it visibly. Reverse toward strong only where inconsistency is user-visible and costly — a booked appointment slot, a submitted claim, a signed e-prescription, where a double-book or a duplicate has teeth, not worklist ordering. The senior move is to apply different consistency to different parts of the same system.
Denormalize/precompute ↔ compute-on-read. Precompute trades storage, write amplification, and invalidation complexity for read speed. Reverse toward compute-on-read when write volume or fan-out makes precompute uneconomical — when you'd spend more maintaining the precomputed copy than you save reading it.
Sync ↔ async. Async decouples and absorbs spikes but adds queues, ordering, and at-least-once delivery to reason about. Keep sync when the caller genuinely needs the result now — booking a slot must return the confirmed appointment, or two front-desk staff will grab it twice. Push to async the work the caller doesn't need to wait for: fan the result into worklists, ship the 837, post the remittance. This is the earlier "split slow work out of the request path," grown up.
Single beefy DB ↔ partitioned/sharded. Vertical scaling stays correct far longer than juniors believe — one large Postgres with replicas serves enormous workloads. Shard only when one node can't hold the working set or absorb the write throughput — and when you do, you've signed up for resharding and hot-key pain, so own that cost out loud. "I'd run one primary until the RPM write IOPS saturate, then partition by X" is a stronger answer than sharding from slide one.
Accuracy ↔ coordination cost (the rate-limiter axis, generalized). Cheap-and-approximate-per-node vs exact-but-coordinated-via-shared-store. Choose by how much being wrong actually costs. This same axis governs distributed counters, metrics, and quotas everywhere — exactness is never free, so buy only as much as the failure mode demands.
🚫 A framing this book rejects. "Senior system design means knowing the famous architectures." It's seductive and it's backwards. Memorizing how Twitter does feeds gives you one answer to one set of numbers — and it shatters the instant the numbers differ. The actual skill is the derivation: state the constraints, do the arithmetic, let the numbers pick the mechanism, narrate the tradeoff. Someone who can derive will out-design someone who has memorized, on any prompt — including the famous ones.
8. Security & scale notes
Scale mechanisms introduce their own threat surface, and naming it unprompted is, again, the senior tell.
Your own scale mechanisms can attack you. A cache amplifies whatever it holds — including poisoned or stale data, served fast to everyone. In healthcare that's not just a bug: a cache that serves one patient's chart to the wrong clinician is a reportable HIPAA breach. A fan-out worker is a way to DoS yourself: one broadcast recall enqueuing 5M writes is an internally generated traffic spike. A notification pipeline without idempotency is a spam vector and an alert-fatigue vector. Design assuming your own components can be turned against you.
A broken access check is a reportable breach. At scale you're tempted to cache aggressively and denormalize widely — but every cached chart-header and every fanned-out worklist entry is PHI. Scope cache keys and worklist entries by the viewing identity, not just the patient, so a cache hit can never cross a patient boundary. And the immutable audit log is first-class here: every chart view is logged, not just writes, so "who saw this record" is always answerable. That requirement shapes the design — it isn't bolted on after — and it's exactly the kind of non-functional a senior surfaces before drawing a single box.
Rate limiting is a security control, not just a capacity knob. It's the frontline defense against credential-stuffing, PHI scraping, and cost-bombing (especially against expensive downstreams — foreshadowing Ch 42's LLM cost-bombs). Design it in tiers — per-user and per-IP and per-endpoint — and decide fail-open vs fail-closed for when the limiter store itself is down. Fail-open keeps the site up but removes the protection; fail-closed preserves the protection but turns a Redis blip into an outage. State which one and why.
Name the load-failure modes explicitly. Three recur across every design: cache stampede / thundering herd — a hot key expires and a thousand requests hit the DB simultaneously (mitigate with request coalescing, jittered TTLs, stale-while-revalidate). Retry storms — a blip triggers synchronized retries that amplify the outage (mitigate with backoff + jitter + circuit breaker + load shedding). Queue backlog growth — when consumers fall behind, decide now what you drop or shed first (and in a clinical firehose, critical values never get shed — they ride a separate priority lane). Knowing these by name means you mitigate them in the design instead of discovering them in the postmortem.
🔑 The "what breaks first" discipline. For every design, name the first resource to saturate and its early-warning metric. DB write IOPS? Cache memory eviction rate? Fan-out queue depth? WebSocket connection count per node? RPM ingest lag? This is the design-round form of the earlier "one slow hop sets the floor" and the tail-latency thinking you've already met: the slowest, most-constrained stage governs the whole system, so find it before it finds you. An engineer who can point at the first domino and its trip-wire metric has demonstrated they'll operate the system, not just draw it.
Multi-tenant fairness. At scale, one heavy tenant, one high-volume RPM device, or one enormous broadcast must not starve everyone else (the noisy-neighbor problem, grown up). Per-tenant (per-clinic/org) quotas and isolation belong wherever a single tenant can monopolize a shared resource — the fan-out queue, the cache, the connection pool, the ingest pipeline. Name where they go.
9. Interview lens & exercises
Interview questions
Every one of these separates levels by narration quality, not by the final box.
"Design a patient scheduling system." — the finite-slot, no-double-booking problem.
- Junior: read the slot, check it's free, write the booking — the classic read-check-write race two front-desk staff hit at the same instant.
- Senior: makes the slot the unit of concurrency — a unique constraint or a conditional
UPDATE ... WHERE status='open'(orSELECT ... FOR UPDATE) so the database, not the app, arbitrates; classifies it strong-consistency because a double-book has teeth; names the hot slot (the 9:00 with the one in-demand provider) as the contention point and what happens to it under a booking rush.
"Design an RPM ingestion pipeline." — the device firehose.
- Junior: one endpoint that writes each reading straight to Postgres.
- Senior: classifies it write-heavy first; does the arithmetic (devices × readings/hour → writes/sec) before choosing anything; puts a queue at the front as the shock absorber; writes readings append-only to a store built for high write volume (partitioned by device/patient — a document or time-series store); names ingest lag / queue depth as the first thing to saturate; and separates the firehose from the critical-value path so an out-of-range reading never sits behind a million routine ones.
"Design a claims submission pipeline (837 → clearinghouse → 835)."
- Junior: on "submit," POST the claim to the clearinghouse inside the request.
- Senior: recognizes the external partner is slow and unreliable, so submission is async and must be exactly-once — writes the claim and an outbound intent in one local transaction (the outbox you built earlier), a worker ships the 837 with an idempotency key, and the 835 remit comes back as an async callback that posts a payment or a denial. Duplicate submission is a duplicate claim, which is fraud-adjacent, so idempotency isn't optional — it's the whole point. Names the callback backlog and the clearinghouse timeout as the failure modes.
"Design a provider worklist / chart-activity feed."
- Junior: "Store events in a table, query them on load." No scale math, no fork, no fan-out.
- Senior: clarifies the read/write ratio and the fan-out shape (panel sizes, broadcast events) first; classifies it read-heavy; picks hybrid fan-out because of the broadcast tail; names the fan-out queue as the bottleneck and its depth as the warning metric; states that eventual consistency is fine for routine items but critical values must ride the alert path, not the feed. The numbers drove every choice and you could hear them do it.
"How would you rate-limit the patient-portal API?"
- Junior: "A counter in memory." Ignores multiple nodes and what happens when the store is down.
- Senior: asks "per what — patient, IP, endpoint?"; names token bucket and why; raises the distributed-counter coordination cost; and volunteers the fail-open vs fail-closed decision for limiter-store outages.
"Estimate the storage for five years of Pulsely observations."
- Junior: guesses a number, or stalls without a method.
- Senior: states assumptions (enrolled patients, readings/patient/day, avg size, replication, retention), derives a defensible magnitude step by step, and sanity-checks it ("a few hundred TB — large but ordinary, so storage isn't the hard part; the ingest and read paths are").
"Where does this design fail first under 10x load?"
- Junior: "We'd add more servers."
- Senior: points to a specific saturating resource, its metric, the mitigation, and the mitigation's cost — "the RPM ingest queue depth; we scale workers, but past a point the write store's IOPS become the new ceiling, so then we partition."
Exercises & the Pulsely increment
-
Capacity drill. From the one-line prompt "Pulsely grows to 50M patient-users," fill the §5 worksheet — avg QPS, peak QPS, storage/yr, bandwidth, cache size, partition count — in under ten minutes, assumptions written down. Then change one assumption (RPM enrollment surges, so readings/patient/day goes from 2 to 20) and re-derive only what it touches. That re-derivation, not the first pass, is the skill.
-
Worked-design reproduction. Design the URL shortener (worked design 2) end-to-end on a single page — API, schema, key-gen deep-dive, bottlenecks, tradeoffs — narrating each funnel step in writing. Grade yourself only on: did every choice name its rejected alternative? (It's domain-neutral on purpose: the clean read-heavy shape transfers straight to caching chart-headers and eligibility responses.)
-
The Pulsely 100x increment. Take three existing Pulsely features and run each through the full method at 100x current load. For each: re-estimate capacity, redraw the high-level diagram, deep-dive one component, and write the single "what breaks first" line with its mitigation.
- Worklist → deep-dive the fan-out worker. At 100x, the push path's write amplification dominates. What breaks first: fan-out queue depth as broadcast events (recalls, advisories) and a few high-panel providers spike. Mitigation: hybrid — pull for broadcast sources past a fan-out threshold; the warning metric is queue lag.
- Clinical alerts → deep-dive the dedup/idempotency pipeline. At 100x, at-least-once redelivery and retry-after-timeout make duplicates routine, not rare. What breaks first: duplicate sends (and the pager/SMS provider rate limits behind them, plus alert fatigue). Mitigation: an idempotency key
(event_id, recipient_id, channel)recorded before ack; per-provider circuit breakers, failover, and escalation on unacknowledged criticals. - Patient/order search → deep-dive the index/partition strategy. At 100x the corpus, a single search index node can't hold the working set. What breaks first: index memory / query latency on the hot node. Mitigation: partition the index by a key that matches the hottest query (MRN/DOB exact-match vs full-text), replicate read-side, cache top queries.
The redrawn high-level diagram for Pulsely-at-100x — the convergence of the whole book:
clients ─▶ [gateway: rate-limit] ─▶ API tier (stateless, N) ─┬─▶ cache (hot worklist/search)├─▶ primary Postgres (writes) ─▶ replicas (reads)├─▶ queue ─▶ fan-out workers ─▶ alert channels└─▶ (every access) ─▶ append-only audit log▲first-to-saturate: queue depth ◀── circle this -
Narration drill. Record yourself designing one system aloud for 20 minutes — the RPM ingestion pipeline or the claims saga is a good pick. Transcribe it. Grade against the seven steps — and score not "was the answer right" but "did every choice state its rejected alternative." The gap between what you know and what you said is exactly the gap the interview measures, and this drill closes it.
Key takeaways
- System design is a method, not more facts — you already own the mechanisms (Parts I–VII); the skill is the disciplined order to apply them under ambiguity, narrated aloud.
- Walk the funnel: requirements → numbers → contract → boxes → one deep box → where it breaks → what you traded. Each stage constrains the next; skipping one floats everything below it.
- Numbers pick the architecture. No box before a QPS/storage estimate justifies it. The read-heavy vs write-heavy fork is the master decision and selects the mechanism family.
- The seven steps are invariants you never skip; the non-functional requirements (latency, availability, consistency, durability, cost) decide the shape more than the features do.
- Default to the boring baseline (single Postgres + cache + queue), prove where the numbers break it, then add complexity exactly there — never upfront.
- For every design, name the first resource to saturate and its warning metric before you're asked; "what breaks first" is the senior tell.
- State tradeoffs on the six axes — push/pull, strong/eventual, precompute/compute-on-read, sync/async, single-DB/sharded, accuracy/coordination — each with its reversal condition.
- The process is the score. A clearly narrated flawed design beats a silent correct one, because the round measures how you think. Same conversation powers the RFC and the postmortem.
← Previous: Ch 40 — Working in Existing & Brownfield Systems · Up: Part VIII overview · Master TOC · Next: Ch 42 — Backend for AI Features →