Say "saved" when the write reaches cache memory, and it takes 0.5 ms, but a crash can lose 5 seconds of writes. Wait until a second machine has it on disk, and it takes about 11 ms, and losing one machine loses nothing.
Pick where the write is acknowledged, then lose a machine and count the writes that vanish. Then we build, piece by piece, fsync, replication, copies and nines, data models, column storage, and the caches that sit in front of it all.
You need what a key-value lookup is and what a network round trip is. Consensus & Replication helps. We build the rest from zero.
Illustrative numbers, not measurements: 500 writes a second, 0.5 ms to cache memory, 5 ms for a disk to flush (fsync), 1 ms round trip between machines, the cache flushes to the database every 5 s, the async follower runs 200 ms behind. Chapters 1, 2 and 7 work each number.
Chapter 0
Grow one database until it fails, then match each failure to the fix it needs
Your app keeps everything in one PostgreSQL server. Reads take 2 ms. Then you reach ten million users. The data no longer fits in RAM, so reads go to disk and take 20 ms. The server answers 5,000 reads a second, and you need 40,000.
Three different things broke, and each has its own fix.
| Wall | Symptom | Fix |
|---|---|---|
| Too much data | disk full, working set larger than RAM | partitioning: split the data over machines (Partitioning & Storage) |
| Too many reads | CPU at 100%, queries queue | replication: copies of the data that also serve reads |
| Reads too slow | 20 ms for the same hot rows again and again | caching: keep hot rows in memory |
Replicas and a cache both cut the read load on each database server. Call the reads your app makes each second R, the share of them the cache answers h (the hit ratio), and the number of database servers that serve reads n.
L equals R times, one minus h, divided by n.
Take all reads R. Keep only the misses, the share one minus h. Spread those over the n servers. The result L must stay below what one server can answer.
With made-up numbers: R = 40,000. No cache and one server: L = 40,000, eight times too many. Three replicas (n = 4): 10,000. A cache with h = 0.9 and n = 4: 40,000 × 0.1 / 4 = 1,000 reads a second per server, a fifth of its 5,000.
Each warm box is a database server; the purple fill is its read load and the dashed line its limit of 5,000 a second. Teal reads stop at the cache. Drag the hit ratio and the server count.
Illustrative: 40,000 reads a second, 5,000 per server at most, reads spread evenly. Writes are left out here: they all still go to the leader, which no replica or cache fixes.
Every fix adds a copy of the data, and a copy can be stale or lost. The rest of this lesson is about those copies: where a write is safe, how many copies you need, how you lay the data out, and how caches keep their copies right.
Failure. Symptom: you add four read replicas and writes still time out. Measure: writes per second on the leader against its limit. Cause: replicas copy every write, so they add read capacity and no write capacity. Fix: partition the writes over several leaders.
Chapter 1
Force the write to the disk before you say "saved", then share each flush among many commits
A database gets INSERT ... ; COMMIT. When may it answer "done"? If the change sits only in memory, a power cut erases it. The operating system also keeps written files in memory for a while, in its page cache, so even a write() call is not on the disk yet.
So the database first appends the change to a write-ahead log (WAL): a file it only ever adds to. Then it calls fsync, which blocks until the disk confirms the bytes are stored. Only then does it acknowledge the commit. After a crash it replays the log.
An fsync takes time: about 5 ms on a networked cloud volume in this lesson's illustrative numbers. One fsync per commit caps the database at 200 commits a second. The fix is group commit: while one fsync runs, new commits wait; the next fsync stores all of them at once. Call the number of commits in one flush B and the time of one fsync tf.
X equals B divided by t-f.
The disk does one flush every t-f seconds. Each flush stores B commits. So it stores B divided by t-f commits a second. Bigger batches raise X without a faster disk.
With t-f = 5 ms: B = 1 gives 200 commits a second. B = 16 gives 3,200. In our simulation at 1,000 commits a second, group commit averaged about 5 commits per flush and 7.5 ms per commit. One fsync per commit cannot keep up at all.
Blue commits arrive. Pink ones wait for the disk; the yellow bar is an fsync in progress; green ones are safe. Pick a mode, drag the rate, then pull the plug.
Simulated in your browser: random arrivals, one 5 ms fsync at a time, 20 simulated seconds per setting with one fixed seed. "No fsync" acknowledges at once and lets the OS write the page cache back later; the toy assumes the last 5 s were not written back. Real disks with a power-loss-protected cache flush far faster.
Group commit trades a little latency for a lot of throughput: a commit may wait for the flush in progress, then for its own. PostgreSQL, MySQL and most databases do it.
Failure. Symptom: the database tops out near 200 commits a second with idle CPUs. Measure: fsync latency and commits per flush. Cause: each commit pays its own flush. Fix: group commit, batch writes in one transaction, or a disk with a faster flush.
Chapter 2
Send each log entry to followers, then choose how many must store it before the client hears "saved"
An fsync protects against a power cut. It does not protect against a dead disk or a burned machine. For that you need the write on a second machine. In single-leader replication, the leader takes every write and streams its log to followers (replicas), which replay it.
The question is when the leader acknowledges. Three choices:
With the illustrative numbers, a synchronous write costs the leader's fsync, a round trip and the follower's fsync: 5 + 1 + 5 = 11 ms, against 5 ms asynchronous. An asynchronous follower's cost is loss. Call the writes per second λw and how far the follower runs behind Δ (the replication lag).
Lost equals lambda-w times delta.
The follower is missing the last delta seconds of the log. The leader acknowledged lambda-w writes in each of those seconds. Multiply the two to count what a failover throws away.
With made-up numbers: λw = 2,000 writes a second, Δ = 0.2 s. Lost = 2,000 × 0.2 = 400 writes the clients were told were saved. If a slow network pushes the lag to 5 s, it is 10,000.
The leader sends each entry to three followers. Teal confirmations come back; the leader acknowledges when the mode says so. The yellow bars are mean and slowest-1-in-100 commit time. Slow one follower, then crash the leader.
Simulated in your browser: 5 ms leader fsync; each follower's round trip plus fsync is random around 6 ms (40 ms for the slow one); 100,000 commits per setting with one fixed seed; 2,000 writes a second and 200 ms of lag for the failover count. Illustrative numbers.
In our run, semi-sync averaged 9.6 ms and sync-to-all 13.3 ms. Slow one follower to 40 ms and sync-to-all jumps to a 94 ms slowest-1-in-100, while semi-sync stays near 14 ms: one quick follower is enough. PostgreSQL replicates asynchronously unless you name synchronous standbys; MySQL's semi-synchronous replication waits for one replica.
Failure. Symptom: after a failover, users report orders they placed a minute ago are gone. Measure: replication lag at the moment of failover. Cause: asynchronous followers missed the last writes. Fix: semi-synchronous replication, or fail over only to a follower that is caught up.
Chapter 3
Let more than one node accept writes, and count how often two of them change the same key
A user in Tokyo writes to a leader in Virginia. Light alone needs about 109 ms for that round trip (Load Balancing works it), so every write feels slow. Two other designs let the write stay near the user.
The multi-leader price is a write conflict: two leaders change the same key before either sees the other's change. How often? Call the rate at which each leader writes one particular key λ, and the time a write takes to reach the other leader d.
P equals one minus e to the minus two lambda d.
Your write conflicts if the other leader wrote the key within d before it or d after it, a window 2d wide. Random writes at rate lambda land in it with chance one minus e to the minus two lambda d. For small windows, that is about two lambda d.
With made-up numbers: λ = 0.1, d = 0.15 s. 2λd = 0.03, so P = 1 − e−0.03 = 2.96%. Our simulation of 200,000 writes counted 2.96%. A hot key written once a second gives 26%.
Each blue dot is a write leaving its leader. A red flash is a conflict: the other leader wrote the key inside the window. Under single leader, Tokyo pays the round trip instead. Drag the rate and the delay.
Illustrative: random writes at each leader; a conflict is any pair of writes less than d apart. The 109 ms is the speed-of-light floor for Tokyo to Virginia in fibre; real round trips are longer.
Something must resolve each conflict. Last write wins (LWW) keeps the write with the later timestamp and silently drops the other. One write of each conflicting pair vanishes: about 1.5% of all writes here, 1 in 67. The alternatives are to keep both versions for the app to merge, or to use data types that merge by themselves (Coordination Avoidance).
Failure. Symptom: a user's edit to a shared document disappears with no error. Measure: writes discarded by conflict resolution. Cause: two leaders wrote the key inside one replication delay, and LWW kept one. Fix: route each key's writes to one home leader, or merge both versions.
Chapter 4
Count the chance that every copy dies before one is repaired, then see what one shared rack does to it
Disks die. A storage system keeps r copies on different disks, and when one dies it copies a survivor onto a new disk. Data is lost only if every copy dies before the repair finishes. GFS (2003) stored three replicas of each chunk by default, and three is still the usual choice.
Call the chance that one disk dies in a year λ (its annual failure rate), and the time to rebuild a lost copy T, in years. Assume disks die independently.
P-loss is about r times lambda, times lambda T to the power r minus one.
Some copy dies r times lambda times a year. Each time, the other r minus one copies must all die before the repair ends, and each does so with chance lambda T. Multiply. Every extra copy multiplies the risk by another small lambda T.
With λ = 0.02 and T = 1/365: one copy loses data with chance 2% a year. Two copies: 2 × 0.02 × 0.0000548 = 2.2 in a million, about 5.7 nines. Three copies: 1.8 in ten billion, about 9.7 nines.
With k copies dead, each of the r − k live ones dies at rate λ, and each dead one is rebuilt within T. The chance of one more death before a rebuild is about (r − k)λT / k. Multiply these for k = 1 to r − 1 and the factorials cancel, leaving (λT)r−1. An event simulation with an exaggerated λT = 0.02 gave 0.0756 losses a year for r = 2 (formula 0.08) and 0.00227 for r = 3 (formula 0.0024).
The purple bar is durability in nines (two nines is 99%). The marks are published design figures. Add copies, slow the repair, then put all copies in one rack.
The independent-failure model above. "One rack" adds an illustrative 0.5% a year chance of an event (power, a switch, a fire) that takes every copy at once. Marks: Amazon EBS gp3 99.8 to 99.9%, io2 99.999%, S3 and Cloud Storage designed for 99.999999999% a year (vendor documentation).
Real losses come from shared causes: one rack, one power feed, one bad firmware, one bug. So S3 stores objects across at least three Availability Zones. Its "eleven nines" is a design goal, not a measurement of your bucket.
Copies live behind three interfaces:
| Kind | What you get | Durability (vendor) | Price, illustrative |
|---|---|---|---|
| Block | a disk for one machine: fast reads and writes of small blocks (EBS, a local SSD) | EBS gp3 99.8 to 99.9% a year | about $0.08 per GB a month |
| File | paths and directories that many machines share (NFS, EFS) | varies by service | about $0.30 per GB a month |
| Object | whole objects by key over HTTP; no partial overwrite (S3, Cloud Storage) | designed for 11 nines | about $0.023 per GB a month, plus requests |
Failure. Symptom: a database volume fails and the only backup was on the same volume. Measure: where every copy of each byte lives. Cause: a block volume is one failure domain, 99.8 to 99.9% a year. Fix: snapshots or backups to object storage in another zone.
Chapter 5
Store the same users four ways, then count what each store must touch to answer four questions
A relational table answers any question, at some cost. NoSQL ("not only SQL") stores give up some questions to answer others cheaply. There are four main families, and each fits one shape of question.
GET and PUT. Redis, DynamoDB used by key, etcd. The store cannot look inside the value.Each column is one store. The bar is the items it touches, on a log scale; the dots are round trips from the app. Green marks the best fit. Pick a question.
Illustrative counts for 1 million users with 200 friends and 1,000 events each, 1,000 of them in Oslo, the data stored the natural way for each family, an index only where the store builds one on a field (the document store).
Friends of friends shows the graph's case. Call the friends per user d (the degree) and the hops k. The edges to follow are E.
E equals the sum over i from 1 to k of d to the i.
Hop 1 follows d edges. Each of those people has d friends, so hop 2 follows d squared. Add the hops. E depends on d and k, not on how many users exist.
With d = 200: one hop is 200 edges, two hops 200 + 40,000 = 40,200, three hops 8,040,200. Each edge is a pointer in a graph store. In a relational join each is an index lookup, about 3 to 4 B-tree levels for a billion rows.
Every store follows the same 40,200 edges. The graph store follows them inside one query, one pointer each. The others pay a lookup or a round trip per batch. The data model does not change the work; it changes the price of each step.
Failure. Symptom: a "recent activity" page slows down month by month. Measure: document size for active users. Cause: events are embedded in the user document, which grows without limit and is read whole. Fix: store events as rows sorted by time under the user's partition key.
Chapter 6
Read only the columns a query names, then compress each column on its own
An orders table has a billion rows and 50 columns of 8 bytes. The question: "total revenue by country for March". It needs three columns: country, date and price. A row store keeps each row's 50 values together on disk, so it must read all 50 to get three.
A column store keeps each column in its own file or chunk. It reads only the three it needs. Parquet files work this way. So did Google's Dremel (Melnik and others, 2010), which stored nested records by column to scan billions of rows interactively.
Call the rows N, the bytes per value of the columns the query reads wj, and the compression ratio c.
B-col equals N times the sum over the read columns of w-j, divided by c.
Add the widths w-j of the columns you read. Multiply by the rows N. Divide by the compression c. A row store reads the full row width for every row, and compresses less, because neighbouring bytes are unlike.
With made-up sizes: a row store reads 109 × 400 B = 400 GB. The column store reads 109 × 24 B = 24 GB raw, 6 GB at c = 4. At 1 GB/s that is 400 s against 6 s.
The grid is the table on disk. Blue cells are what the scan must read; purple ones it skips. The yellow bars compare time at 1 GB/s. Change the layout and the columns.
Illustrative: 109 rows, 50 columns of 8 bytes, 1 GB/s of disk. The ratios come from our test of zlib on a synthetic five-column order table: 4.2× compressed column by column, 3.6× row by row.
Columns compress well because one column holds one kind of value. Parquet uses dictionary encoding (store each distinct value once, then small codes) and run-length encoding (store "Japan, 40,000 times"). In our test a sorted country column of 200,000 values held 40 runs, and zlib shrank it 667×. Random user IDs shrank only 1.3×.
Failure. Symptom: a dashboard query on the main database takes minutes and slows checkout. Measure: bytes read per query against bytes the query needs. Cause: an analytics scan on a row store reads every column of every row. Fix: copy the data to a column store and run analytics there.
Chapter 7
Compare four ways to keep a cache and a database in step, then crash the cache under each
A cache holds copies of database rows in memory. When a row changes, something must fix or drop the copy. Four patterns split that job differently.
| Pattern | Read path | Write path | Cache dies |
|---|---|---|---|
| Cache-aside | app checks the cache; on a miss it reads the database and fills the cache | app writes the database, then deletes the cache key | slower, nothing lost |
| Read-through | app asks the cache; the cache loads misses itself | any of the write patterns | reads fail unless the app falls back |
| Write-through | from the cache | cache writes the database, then answers: database speed | nothing lost |
| Write-behind | from the cache | cache answers at once and flushes to the database in batches | unflushed writes lost |
pythondef get_user(uid): # cache-aside read v = cache.get(f"user:{uid}") if v is not None: return v # hit v = db.query("SELECT * FROM users WHERE id=%s", uid) cache.set(f"user:{uid}", v, ex=300) # TTL 5 min: a safety net return v def update_user(uid, data): # cache-aside write db.execute("UPDATE users SET ... WHERE id=%s", uid, data) cache.delete(f"user:{uid}") # delete, do not set
Write-behind is fast because the client never waits for the database. Its risk is a window. Call the write rate λw and the time between flushes F.
Lost equals lambda-w times F, over 2.
Between flushes, writes pile up only in the cache's memory. A crash comes at a random moment, on average F over 2 seconds after the last flush. It erases every write since then: lambda-w per second. The worst case is a full F.
With made-up numbers: λw = 500, F = 10 s. Lost = 500 × 10 / 2 = 2,500 writes on average, up to 5,000. Flushing every second cuts it to 250, at ten times the flushes.
Blue writes and reads flow from the app. Pink writes sit in the cache, not yet in the database. Pick a pattern, then crash the cache or drop one invalidation.
Illustrative: 500 writes a second, 0.5 ms to the cache, 5 ms to the database, a 10 s flush interval for write-behind, a 300 s TTL. The clock runs fast.
Why delete the key instead of setting the new value? Two writers can set the cache in the opposite order from their database commits, leaving the older value cached until its TTL. Deleting lets the next read fetch the current row. Even delete has a rare race with a slow reader, so keep a TTL as the safety net. Caching & CDNs prices TTLs and stampedes.
Failure. Symptom: after a cache node restarts, a few counters jump backwards. Measure: writes acknowledged but not flushed at the crash. Cause: write-behind kept them only in memory. Fix: write-behind only for data you can lose, such as view counts, or a cache that logs writes durably.
Chapter 8
Trade a network round trip for copies nobody can invalidate, then bound the damage with a short TTL
The fastest cache is a dictionary inside your own process. A lookup takes about 100 ns, with no network. A shared cache such as Redis or Memcached takes a network round trip, about 1 ms in one data centre in this lesson's illustrative numbers: ten thousand times slower.
The local cache has a catch. You run 8 copies of the app. User 42 edits a profile through instance 1. Instance 1 can drop its own copy, but the other 7 never hear about the write. They serve the old profile until their copies expire. A shared cache has one copy, so one delete fixes it for everyone.
How many stale reads does one write cause? Call the reads of this key per second across all instances r, the instances n, and the local time to live TTL.
S equals r, times n minus one over n, times TTL over 2.
Take the reads r. Keep the share that lands on the n minus one instances with an old copy. Each old copy lives on for about half a TTL. Multiply to count the stale answers.
With made-up numbers: r = 80, n = 8, TTL = 30 s. S = 80 × 7/8 × 15 = 1,050 stale reads after each write. Cut the local TTL to 5 s and it is 175.
Eight warm app boxes. Purple means a fresh copy; red means a stale copy still served. Pick a layout, then write the key and watch the copies.
Illustrative: 80 reads a second spread over 8 instances, 100 ns local, 1 ms shared, local hit ratio 90% for the two-tier layout. The clock runs fast. Each local copy was filled at a random moment, so copies expire at different times.
Most large systems use both. A small local tier (L1) holds the hottest keys with a TTL of seconds. The shared tier (L2) holds many more and is invalidated on every write. The database sits behind both. The L1 TTL bounds staleness, and most reads never leave the process.
Failure. Symptom: after a price change, some page loads show the old price for half a minute. Measure: stale reads per write, by instance. Cause: local caches on other instances keep the old copy until their TTL. Fix: a short local TTL, or broadcast invalidations on a message bus (Messaging & Events).
Chapter 9
Run cache-aside over 100 keys, change the size, the TTL and the eviction, then run a batch scan
Here is a cache-aside cache in front of a database, with every knob from Chapters 0 and 7. Requests ask for keys 1 to 100. Under Zipf traffic key k is asked for in proportion to 1/k, so key 1 is twice as popular as key 2. When the cache is full, the eviction policy picks the copy to drop. LRU (least recently used) drops the copy unread for longest. LFU (least frequently used) drops the copy read least often.
The grid is keys 1 to 100: purple cells are cached. Teal ticks are hits, blue ones are misses that go to the database. The yellow line is the hit ratio over time. Change anything and watch the line.
Simulated in your browser: 200 requests a second, keys 1 to 100, Zipf exponent 1. The batch scan reads 1,000 other keys once each, 200 a second for 5 s, mixed into the traffic. LFU counts reads with no decay, and an expired key starts its count again. The hit ratio counts the normal traffic only. The clock runs 4 times fast.
Things to try:
The worked number, from the same engine run for 60 simulated seconds per setting: Zipf traffic, 20 keys, TTL 10 s. LRU holds 55% and LFU 64%. During a 5 s scan, the hot traffic's hit ratio drops to 36% under LRU and stays at 57% under LFU. Redis has offered approximate LFU since version 4.0 for this reason.
Failure. Symptom: every night at 2 a.m. the database load triples for ten minutes. Measure: cache hit ratio and evictions during the nightly job. Cause: a batch job reads many cold keys once and LRU evicts the hot set for them. Fix: LFU eviction, or send batch reads around the cache.
Chapter 10
Keep the numbers, the choices and the code for the next time you decide where data lives
A write is safe only where it is on disk, and on more than one machine. fsync makes it safe on one disk, group commit makes that cheap, and a synchronous follower puts it on a second machine for one round trip. Copies buy nines only when they fail independently. The data model and the layout set the price of each question. Caches cut the load on the database, and every cache is a copy that can be stale or lost.
| Term | What it is | This lesson's number |
|---|---|---|
| Read load per server | L = R(1 − h) / n | 40,000 reads, h 0.9, n 4: 1,000 a second |
| Group commit | X = B / tf | tf 5 ms: 200 a second alone, 3,200 at B = 16 |
| Sync commit | leader fsync + round trip + follower fsync | 5 + 1 + 5 = 11 ms, illustrative |
| Async loss | lost = λw · Δ | 2,000 writes, 0.2 s lag: 400 |
| Multi-leader conflicts | P = 1 − e−2λd | λ 0.1, d 0.15 s: 2.96% |
| Loss with r copies | Ploss ≈ rλ(λT)r−1 | 2% AFR, 24 h repair, r 3: 1.8 × 10−10 a year |
| Graph hops | E = Σ di | d 200, 2 hops: 40,200 edges |
| Column scan | Bcol = N Σwj / c | 400 GB by row against 6 GB by column |
| Write-behind loss | lost = λw F / 2 | 500 writes, F 10 s: 2,500 on average |
| Local cache staleness | S = r (n − 1)/n · TTL / 2 | 80 reads, 8 instances, 30 s: 1,050 |
| Job | Choice | Examples |
|---|---|---|
| Sessions, carts, lookups by key | key-value | Redis, DynamoDB |
| Records of varying shape, queried by field | document | MongoDB, Firestore |
| Events per entity, sorted by time | wide-column with a clustering key | Cassandra, Bigtable |
| Paths through relationships | graph | Neo4j, Neptune |
| Scans and sums over a few columns | columnar files or a column store | Parquet, Dremel and BigQuery |
| Large blobs, backups | object storage in several zones | S3, Cloud Storage |
synchronous_standby_names is set. "Semi-synchronous" is MySQL's name for waiting on one replica.volatile-random and, since Redis 8.6, least-recently-modified (allkeys-lrm, volatile-lrm).python# the lesson's numbers in a few lines (sketch) import math from collections import OrderedDict def p_loss(r, afr=0.02, repair_h=24): # chance per year that every copy dies lam, T = afr, repair_h / 8760 return r * lam * (lam * T) ** (r - 1) def conflict(lam, d): # multi-leader conflict chance per write return 1 - math.exp(-2 * lam * d) class LRU: # the eviction behind most caches def __init__(self, size): self.size, self.d = size, OrderedDict() def get(self, k): if k not in self.d: return None # miss: caller reads the database self.d.move_to_end(k); return self.d[k] # hit: now the most recent def put(self, k, v): self.d[k] = v; self.d.move_to_end(k) if len(self.d) > self.size: self.d.popitem(last=False) # drop the least recent for r in (1, 2, 3): print(r, f"{p_loss(r):.2e}") # 2.00e-02, 2.19e-06, 1.80e-10 print(round(conflict(0.1, 0.15), 4)) # 0.0296
Now press Present or Teach and explain five things from memory. Explain why group commit turns 200 commits a second into thousands. Explain what an async follower loses in a failover. Explain why three copies give about ten nines and one rack gives two. Explain why a column store reads 6 GB where a row store reads 400. Then go back to the hero, pick Cache memory, and lose a machine.