Day 1 left you with one web server and one database. Each is a single point of failure and neither has room to grow. This lesson is the standard sequence of moves that fixes them — in order, with the bottleneck each one clears and the new problem each one creates.
24 TBRAM in the biggest single box. The vertical ceiling (§1)
~50 msTypical replication lag — and the window where reads lie (§3)
95%A realistic cache hit rate, which removes 95% of database reads (§4)
150 msRound trip California ↔ Europe. What a CDN deletes (§5)
Key points
Scaling up is simpler and correct for a long time, but it has a hard ceiling and — the real problem — no second copy of anything. Scaling out trades simplicity for redundancy.
The moves have an order, and each one is a response to a measured bottleneck: load balancer, replication, cache, CDN, stateless sessions, then multiple data centres. Adding them out of order means paying for complexity you cannot yet use.
Every move buys something and charges something. Replicas buy read capacity and charge you stale reads. Caches buy latency and charge you invalidation. Knowing the charge is the actual skill.
Outcomes
01Choose up or out by naming the failure mode, not the throughput number.
02Place a load balancer and replicas correctly, and say which traffic goes where.
03Describe replication lag precisely enough to predict the bug it causes.
04Compute what a cache hit rate does to database load, and name the two ways caches go wrong.
05Say what a stateless web tier is worth and what breaks it.
01
Up or out
There are exactly two ways to get more capacity, and the choice is usually mis-framed as a performance question. It is not. It is a redundancy question.
Option A
Scale up (vertical)
Buy a bigger machine: more CPU, more RAM, faster disk.
Zero code changes. No distributed systems problems. Genuinely the right answer when traffic is low.
Hard ceiling: the largest single RDS instance is about 24 TB of RAM, and price rises far faster than capacity on the way there.
No failover. One machine is one thing to lose.
Option B — where large systems end up
Scale out (horizontal)
Add more machines to a pool and spread work across them.
No ceiling in practice; capacity grows roughly linearly with boxes.
Survives losing a machine, which is the point.
Requires a load balancer, a stateless web tier, and a plan for the data. All of that is work.
The real argument
Scaling up is not “worse.” It is bounded and it is fragile. You can run a very large business on one big box right up until the afternoon it reboots. The reason to go horizontal is that you want two of something, and the extra capacity is a side effect.
02
The order of moves
These components usually get introduced as a list. They are better understood as a sequence, because each one is a response to the bottleneck the previous one exposed. Here is the whole target architecture with the order marked on it.
How to read: The green numbers are the order you add things, not the order traffic flows. Traffic flows left to right. Each number is explained in the table below the picture.
One architecture, five additions. Everything on this page is one of these numbers.
#
Move
The bottleneck it clears
The bill it creates
1
Load balancer + 2nd web server
A deploy or crash is an outage; web CPU is maxed
Sessions can no longer live in process memory (→ move 5)
2
Database replicas
Read queries saturate the one database
Replicas are behind. Reads can return stale data (§3)
3
Cache tier
The same expensive query runs thousands of times
Invalidation, and a new thing that can go down (§4)
4
CDN
Big static files cross an ocean on every page load
Cost, and stale assets until the TTL expires (§5)
5
Stateless web tier
Sticky sessions block autoscaling and lose data on restart
An extra round trip to fetch session state (§6)
Beyond these five, the chapter continues to multiple data centres, message queues, and finally database sharding — covered in §7 and in Day 6.
03
Moves 1 and 2: the load balancer and the replicas
The load balancer
The load balancer takes the public IP. Your web servers move to private IPs that the internet cannot reach at all, which is a security win as much as a capacity one. The balancer keeps a health check against each server — typically an HTTP request to /healthz every few seconds — and quietly removes any server that stops answering.
How it chooses is worth one more sentence than most candidates give it:
Algorithm
Behaviour
When it is wrong
Round robin
Next server in rotation.
Assumes every request costs the same and every server is equally fast. A server that is slow but still answering keeps receiving its full share — and is the one you most want to avoid.
Least connections / least outstanding requests
Send to whoever is least busy right now.
Rarely wrong. This is the sensible default: a struggling server naturally accumulates outstanding requests and so stops being chosen.
Power of two choices
Pick two servers at random, send to the less loaded of the two.
Almost as good as checking every server, at a fraction of the coordination — which is why it is popular at scale.
Consistent hashing
Route by a key, so the same key lands on the same server.
When you want cache locality rather than even load. Day 6.
Gotcha — health checks can cause the outage
Make the check too aggressive and a brief latency spike fails it on several servers at once. The balancer removes them, the surviving servers take their traffic, get slower, fail their checks, and you have removed your entire fleet one node at a time while every machine was actually alive. Defences: require several consecutive failures before removal, and set a floor — never drop below N healthy servers no matter what the checks say. Also distinguish a liveness check (is the process up? restart it) from a readiness check (should it receive traffic right now?) — conflating them is how a warming cache gets a server killed.
That health check is the part that matters. It is what turns “server 2 crashed” from an outage into a non-event, and it is what lets you deploy by draining one server at a time while the other keeps serving.
Replication, and the direction of traffic
The web tier can now grow, so the database becomes the bottleneck. The standard first answer is primary/replica replication: one database takes every write, and copies of it take the reads. This works because real applications read far more than they write — often 10:1 or more — so moving reads off the primary buys most of the relief.
Writes (INSERT, UPDATE, DELETE) go to the primary. Only the primary.
Reads (SELECT) go to any replica. Add replicas to add read capacity.
The primary streams its change log to each replica asynchronously — it does not wait for them.
That last word is the whole problem, and it deserves its own picture.
How to read: Time runs downward. Step through it. The red band is the gap between the primary accepting a write and the replica having it. Any read that lands in that band gets the old value — and your code has no way to tell.
This is the single most common bug introduced by adding replicas: the user saves something, the page reloads, and their change has vanished. Nothing has actually gone wrong — the write is safe on the primary. The read just went somewhere that had not heard yet.
Read-your-own-writes is one of three named anomalies that asynchronous replication produces. Knowing all three by name is a cheap way to sound like you have debugged one:
Anomaly
What the user sees
Usual fix
Read-your-own-writes
“I saved it and it vanished.” Your own write is missing from your own next read.
Route that user's reads to the primary for a few seconds after they write.
Monotonic reads
Time appears to run backwards: a comment is there, you refresh, it is gone, you refresh again and it is back. Two reads hit replicas with different lag.
Pin a given user to one replica (hash the user ID to a replica) so they never move backwards.
Consistent prefix
Effects arrive before causes: you see the reply before the question. Happens when writes are partitioned and each partition replicates at its own pace.
Keep causally related writes in the same partition, or carry causality metadata.
The fix is called read-your-own-writes, and the usual implementation is blunt: after a user performs a write, route that user's reads to the primary for a short window (a few seconds, or until a replication position catches up). Everyone else keeps reading from replicas. You give up a little read capacity in exchange for not confusing the one person who most expects to see the change.
Gotcha — failover is not automatic magic
If the primary dies, a replica is promoted. In production that is harder than it sounds: the chosen replica may be behind, so the writes that existed only on the dead primary are gone. Teams run recovery scripts to replay what they can from the binary log. “Promote a replica” is one sentence in an interview and a very bad afternoon in real life.
Interview tip
If a replica dies, reads go to the remaining ones. If there is only one replica, reads temporarily go to the primary — which is fine briefly and dangerous if you leave it. Say this out loud; interviewers are checking whether you thought about the degraded state, not just the happy path.
04
Move 3: the cache, and the arithmetic that justifies it
Replicas give you more database capacity. A cache lets you not use the database at all. For read-heavy traffic that is a much bigger lever, because the cheapest query is the one you never run.
How to read: One lookup, two outcomes. The green path is what happens almost all the time. The amber path is the rare miss, which costs a database round trip and then writes the result back so the next reader takes the green path.
This pattern is called read-through (or cache-aside when the application, rather than the cache, does the fallback). It is the default for anything read often and changed rarely.
What a hit rate is actually worth
Hit rate is not a vanity metric — it is a direct multiplier on database load. If you serve 10,000 reads per second, the database sees 10,000 × (1 − hit rate):
Try it: drag the hit rate and watch what reaches the database. The interesting part is not the line — it is how steep the last five points are.
what your users generate
fraction answered from RAM
reaching the database500/s
database reads
500/s
databases needed
1
at ~2,000 reads/s each
average read latency
1.5 ms
1 ms on a hit, 10 ms on a miss
Hit rate is a direct multiplier on database load: reads × (1 − hit rate). Drag it to 50% to see why a mediocre cache is barely worth its invalidation problem, and to 99% to see why the last few points are worth chasing.Cache-aside, written outpython
TTL = 60 # seconds. The single most important tuning knob.
def get_user(user_id):
key = f"user:{user_id}"
cached = redis.get(key)
if cached is not None:
return json.loads(cached) # hit: done in ~1 ms
row = db.query("SELECT * FROM users WHERE id = %s", user_id) # missredis.setex(key, TTL, json.dumps(row))# store for next time
return row
def update_user(user_id, fields):
db.execute("UPDATE users SET ... WHERE id = %s", user_id)
redis.delete(f"user:{user_id}")# invalidate. Delete, do not overwrite:# overwriting races with concurrent writers.
The two ways caches go wrong
Failure 1
Stale data
The database changed; the cache did not hear about it.
Two defences, used together: a short TTL so wrong answers expire on their own, and explicit invalidation on write.
Only cache things where being a few seconds out of date is survivable. Not account balances.
Failure 2
Thundering herd
A popular key expires. A thousand requests miss simultaneously and all hit the database with the same query.
The cache was the only thing keeping the database alive, and it just stepped aside for a moment.
Fixes: stagger TTLs with jitter, or let a single request rebuild the key while others serve the slightly stale value.
The fix most people have not heard of: leases
Jitter spreads expiries out; it does not stop many readers missing the same key at once. Meta's memcache work introduced leases, which solve two problems with one mechanism. On a miss, the cache hands exactly one client a short-lived token and tells everyone else to wait briefly and retry. (1) Thundering herd: only the token-holder queries the database; the rest get the value a moment later. (2) Stale sets: the cache refuses a write whose lease was invalidated while the client was away, which kills the classic race where a slow reader overwrites a fresher value with the stale one it fetched before the update. The simpler cousins you can build in an afternoon are single-flight (one in-process request per key, the rest wait on it) and stale-while-revalidate (serve the expired value and refresh in the background, so no user ever waits on a rebuild).
Interview tip — eviction
When the cache fills, something must go. LRU (least recently used) is the default and the right answer in most interviews. LFU (least frequently used) protects items that are popular over a long horizon but rarely touched in any given minute. FIFO ignores access entirely and is mostly a teaching example. Also: run more than one cache node. A single cache server that dies drops the whole load onto the database at once — the thundering herd, but for every key simultaneously.
05
Move 4: the CDN, which is a cache you cannot see
A cache removes database work. A CDN removes distance. For static files — images, CSS, JavaScript, video — distance is usually the dominant cost, and no amount of server tuning touches it, because the limit is the speed of light in fibre.
How to read: Same user, same file, two topologies. The length of the arrow is the point.
The 150 ms figure is the California ↔ Netherlands round trip you will meet again on Day 3. It is a floor set by physics, not by your code.
The mechanics: the first user in a region requests the file, the edge server does not have it, so it fetches from your origin, stores it for the duration of the Cache-Control TTL, and serves it. Every subsequent user in that region is served locally.
Three things that catch people out:
You pay for data transfer out of the CDN. Putting rarely-requested files behind it costs money and saves nothing. Cache what is hot.
Invalidation is awkward. You can call the CDN's purge API, but the reliable approach is versioned URLs — ship app.3f9c1e.js instead of app.js, so a new deploy produces a new URL that was never cached. You never invalidate anything; you just stop referring to the old file.
Plan for the CDN being down. Clients should fall back to the origin. It will be slow. Slow beats a blank page.
06
Move 5: keeping the web tier stateless
This one is not a component you add. It is a discipline you keep, and it is the thing that makes move 1 actually work.
Option A — what happens by accident
Stateful
User A logs in; their session is stored in web server 1's memory.
Every subsequent request from User A must reach server 1, so the load balancer needs sticky sessions.
Server 1 restarts → User A is logged out. Traffic is uneven, because stickiness overrides balancing.
Autoscaling is now dangerous: removing a server throws away live sessions.
Option B
Stateless
Session state lives in a shared store — Redis, or a NoSQL table keyed by session ID.
Any request can go to any server. The load balancer is free to actually balance.
Restart, deploy, or terminate any box at any time. Nothing is lost.
Autoscaling works: add servers at 9 a.m., remove them at midnight, no coordination needed.
What to say out loud
“I'd move session state out of the web tier into a shared store — Redis for speed, or a NoSQL table if I want it to survive a cache flush. That's what lets me treat web servers as disposable, which is the whole reason I put a load balancer in front of them.”
Gotcha
Sessions are the obvious state. The sneaky ones are uploaded files written to local disk, in-process caches that differ per box, and scheduled jobs that assume they are the only instance running. Each one quietly makes a server special. Uploads belong in object storage; cron belongs behind a lock or a scheduler.
07
Past the five moves: where this goes next
The chapter continues past the architecture drawn in §2. Three more moves, in rough order of when you need them:
Move
What it is
Why you reach for it
Multiple data centres
Run the whole stack in two or more regions; geoDNS sends each user to the nearest one, and traffic reroutes to the survivor if a region fails.
Latency for a global audience, plus surviving the loss of an entire region. The hard part is keeping data consistent across regions.
Message queues
Producers drop jobs on a durable queue; a separate pool of workers consumes them.
Decouples slow work (video encoding, sending email) from the request. The web tier answers fast; workers scale independently of it. Day 11 is this idea in full.
Sharding
Split one dataset across many databases, each holding a slice. A shard key such as user_id % 4 decides which.
The last resort, when a single primary cannot hold the writes or the data. It costs you cross-shard joins, resharding pain, and hotspots when one shard gets a celebrity. Day 6 is about doing the routing part properly.
Gotcha — sharding is not move 6user_id % 4 looks harmless and is the exact pattern that breaks the moment you add a fifth shard: the modulus changes and almost every row needs to move. Day 6 is entirely about why, and what to use instead. Do not shard until replicas, caching and a bigger primary have all run out.
Q&A
Check yourself
Each of these is a symptom, a push-back, or a migration — the three shapes scaling questions actually take in an interview.
Q1“Scale this from one user to ten million.” The interviewer wants the order, not the list. What forces each move, and which one would you deliberately delay?
Shard the database first, since data is always the bottleneck
Load balancer → replicas → cache → CDN → stateless sessions, each triggered by a measured bottleneck — and delay sharding as long as possible
Move everything to microservices
✓ Follow the bottleneck, and delay sharding. The ordering logic: a second web server plus a balancer first, because it removes the deploy-is-an-outage problem and buys compute; replicas next, when read queries saturate the primary; a cache next, because it removes queries rather than adding capacity to serve them; a CDN when static bytes dominate; stateless sessions whenever move 1 forces it. Sharding is deliberately last because it is the only one you cannot easily undo — it costs you cross-shard joins, transactions, resharding operations and hotspots, permanently. The strong version of this answer names the signal for each step (“I'd add replicas when read CPU on the primary passes ~60% at peak”) rather than reciting the sequence.
Q2A replica is lagging 45 seconds behind the primary during your evening peak. It catches up overnight. Name two distinct causes and say how you would tell them apart.
The network between them is slow
Either the replica is CPU/IO saturated applying changes, or one long transaction on the primary is blocking the stream — check whether lag grows smoothly or jumps
The replica needs more RAM
✓ Saturation versus a single blocking transaction — and the shape of the lag graph tells you which.Cause A: the replica cannot keep up. Many replication implementations apply changes in a single thread while the primary accepts writes from hundreds of connections, so a write-heavy peak simply outpaces it. Lag ramps up smoothly with traffic and decays smoothly after. Cause B: one enormous transaction — a bulk delete, a schema change, a nightly batch job — must be applied atomically, so lag jumps in a step and then collapses. Fixes differ completely: A needs parallel apply, a bigger replica, or fewer writes; B needs the offending job chunked. A third cause worth naming: an analytics query on the replica holding locks that block the apply thread, which is why dedicating a replica to reporting is standard. And meanwhile, read-your-own-writes protects users from seeing their own changes disappear, but everyone else is reading 45-second-old data — so you also need to decide whether that is acceptable for the product.
Q3At 09:00 sharp your database CPU spikes, a few requests time out, and cache hit rate briefly drops to near zero. It recovers in 30 seconds and happens every weekday. Diagnose it and give the one-line fix.
A scheduled job is scanning a table
Thousands of keys written during yesterday's 09:00 burst are expiring in the same second — add jitter to the TTL
The cache server restarts nightly
✓ Synchronised TTL expiry — a thundering herd on a daily clock. Yesterday's 09:00 traffic populated thousands of keys with an identical TTL, so today they all expire within the same second and every one of those reads falls through simultaneously. The fix is one line:TTL = 3600 + random(0, 600), spreading expiries over ten minutes instead of concentrating them in one second. The follow-up they will ask: jitter spreads the load but does not stop many requests for the same key missing at once. For that you need either a per-key lock so one request rebuilds while the others wait, or — better — serving the stale value while a single background refresh runs, so no user ever waits on a rebuild. The third defence is a probabilistic early refresh, where each read has a small chance of refreshing the key before it expires, scaling with how close to expiry it is.
Q4You need to add a NOT NULL column to a 400-million-row table that is read constantly. Describe a zero-downtime plan. Which step is the one people get wrong?
Run ALTER TABLE during a low-traffic window
Add it nullable, backfill in batches, dual-write from the application, then add the constraint — and the step people get wrong is deploying code that reads the new column before the backfill finishes
Create a new table and swap the names
✓ Expand, migrate, contract — and the ordering of the code deploys is the trap. The sequence: (1) add the column nullable with a default, which is cheap on modern engines; (2) deploy code that writes both old and new, but still reads the old; (3) backfill in small batches with a pause between them, so you never hold a long transaction (which would also blow up replication lag — see Q2); (4) verify no nulls remain; (5) deploy code that reads the new column; (6) add the constraint and drop the old column in a later release. The common failure is collapsing steps 2 and 5 into one deploy — then during the rolling deploy some servers read a column that older servers are not populating, and you serve nulls. The other classic mistake is a single unbatched UPDATE, which locks rows for minutes and stalls every replica. Interviewers like this question because it tests whether you think about the deploy as a distributed system too: for a while, two versions of your code are running at once.
Q5Your team wants to put the CDN in front of authenticated API responses, not just static files, to cut latency for international users. What goes wrong, and is there a version that works?
CDNs cannot serve dynamic content at all
Shared caching of per-user responses risks serving one user's data to another; it works only with a correct cache key and Cache-Control: private discipline
It works fine — CDNs respect authentication headers automatically
✓ The risk is cross-user data leakage, and the fix is the cache key. A CDN caches by URL. If two users request /api/v1/me and the edge does not know they are different people, the second user gets the first user's response — a real and recurring production incident, not a theoretical one. Versions that work: cache only responses that are genuinely identical for everyone (product pages, public feeds, config) and mark everything per-user Cache-Control: private, no-store; or include the identity in the cache key via Vary or a signed cookie the edge is configured to key on, accepting that the hit rate collapses because each user now has their own entry. The thing actually worth doing is usually different: terminate TLS at the edge and route over the CDN's backbone without caching the response at all. That removes most of the round-trip cost — which was the real goal — with none of the correctness risk.
In practiceWhat production adds, and the questions that come next optional
This lesson covers the layer that decides an interview. Below it is the operational layer — the things that only show up once a system is running, and the questions that come if someone keeps pulling the thread. None of it is answered above.
Caching strategies
Eviction: LRU, LFU, TinyLFU/W-TinyLFU, FIFO, TTL-only, and what workload each suits
Sizing from the working set and estimating hit rate; why hit rate has a steep marginal-value curve
Replication
Log shipping mechanics: statement-based vs. WAL shipping vs. logical/row-based, and why logical enables CDC
Cache invalidation
Multi-region cache coherence and why cross-region invalidation broadcast is lossy
Terms used
Health check
A periodic request the load balancer sends to each server. Failing it removes the server from rotation.
Private IP
An address reachable only inside your network. Web servers behind a balancer use these, so the internet cannot reach them directly.
Primary / replica
The database that accepts writes, and the read-only copies fed from its change log. Older material calls these master and slave.
Replication lag
The delay between the primary committing a write and a replica having it. Typically milliseconds; occasionally much worse under load.
Read-your-own-writes
Routing a user's reads to the primary for a short period after they write, so they always see their own change.
Cache-aside
The application checks the cache, and on a miss queries the database and populates the cache itself.
Hit rate
The fraction of cache lookups that find a value. Multiplies directly against database load.
Thundering herd
Many requests missing the same expired key simultaneously and all hitting the database at once.
LRU
Least recently used — the usual eviction policy when a cache is full.
Sticky session
Load balancer configuration pinning one client to one server. A symptom of state in the web tier.
Shard key
The column deciding which database shard a row belongs to.
What breaks next. Every move on this page was justified with a number — 10,000 reads per second, 150 ms, a 95% hit rate. In an interview nobody hands you those numbers; you are expected to produce them in about two minutes from a handful of assumptions. Day 3 is that skill: back-of-the-envelope estimation.
Source: System Design Interview, Ch. 1 — Scale from zero to millions of users (pp. 1–30). Replication-lag sequence, hit-rate arithmetic, thundering herd and versioned-URL invalidation are standard practice added here to make the trade-offs concrete.