Data Storage & Caching

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.

Choose where "saved" happens

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

One Database Hits Three Walls

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.

WallSymptomFix
Too much datadisk full, working set larger than RAMpartitioning: split the data over machines (Partitioning & Storage)
Too many readsCPU at 100%, queries queuereplication: copies of the data that also serve reads
Reads too slow20 ms for the same hot rows again and againcaching: 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.

Say it aloud

L equals R times, one minus h, divided by n.

L
L the reads per second that reach one database server.
R
R all reads the app makes per second: 40,000 here.
h
h the hit ratio: the share of reads the cache answers, from 0 to 1. One minus h is the share that misses.
n
n database servers that serve reads: the leader plus its read replicas.
In plain words

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 numbers

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.

Spread 40,000 reads

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.

0%
1

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.

  1. Disk: when a write is safe on one machine, and fsync's price.
  2. Sync: wait for a follower or not, and what replication lag loses.
  3. Leaders: one leader, many leaders or none, and write conflicts.
  4. Copies: how many copies give how many nines, and block, file and object storage.
  5. Models: key-value, document, wide-column and graph stores.
  6. Columns: store by row or by column, and compress.
  7. Cache writes: cache-aside, read-through, write-through and write-behind.
  8. Local: a cache inside each app or one shared cache.
  9. Showcase: a cache you can size, scan and kill.
  10. The field guide: numbers, choices, code and links.
Your database serves 10,000 reads a second and you add 3 read replicas. Which problem is still not solved?

Chapter 1

When Is a Write Safe?

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.

Say it aloud

X equals B divided by t-f.

X
X the most commits per second the log can make safe.
B
B the batch: commits stored by one fsync. Without group commit, B = 1.
tf
t-f the time of one fsync: 5 ms here, illustrative.
In plain words

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 numbers

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.

Flush the log

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.

1,000

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.

An fsync takes 5 ms. About how many commits a second can a log make safe if each flush stores 16 commits?

Chapter 2

Wait for a Follower, or Not

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:

  1. Asynchronous. After its own fsync. Fast. Followers lag behind, and that lag is lost if the leader dies for good.
  2. Synchronous to all. After every follower stores the entry. Nothing is lost, but each write waits for the slowest follower.
  3. Semi-synchronous. After one follower, any one, stores it. The write is on two machines; the other followers stay asynchronous.

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).

Say it aloud

Lost equals lambda-w times delta.

lost
lost acknowledged writes that are gone if the leader dies for good and the follower takes over.
λw
lambda-w the write rate: 2,000 writes a second here.
Δ
delta the replication lag: how many seconds of log the follower has not received yet. 200 ms here.
In plain words

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 numbers

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.

Choose who must confirm

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.

A leader takes 2,000 writes a second and its async follower lags 0.5 s. The leader's disk dies. About how many acknowledged writes are lost?

Chapter 3

One Leader, Many, or None

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.

Say it aloud

P equals one minus e to the minus two lambda d.

P
P the chance that one write to the key conflicts with a write at the other leader.
e
e to the minus x the chance that a random stream of writes puts none in a window. e is about 2.718.
λ
lambda writes per second to this key at the other leader: 0.1 here, one every 10 s.
d
d the replication delay between leaders: 0.15 s here.
In plain words

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 numbers

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%.

Write one key in two regions

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.

0.1 /s
150 ms

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.

Two leaders replicate with d = 0.15 s. A key is written 0.1 times a second at each. About what share of writes conflict?

Chapter 4

How Many Copies Make Eleven Nines?

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.

Say it aloud

P-loss is about r times lambda, times lambda T to the power r minus one.

Ploss
P-loss the chance of losing this piece of data in one year.
r
r the number of copies: the replication factor.
λ
lambda the annual failure rate of one disk: 0.02, or 2% a year, illustrative. r times lambda is how often some copy dies.
λT
lambda T the chance that one other disk also dies during a repair window.
T
T the repair time in years: 24 hours is 1/365 of a year.
r − 1
to the r minus one every one of the other copies must die inside the window too.
In plain words

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 numbers

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.

Where the formula comes from, and a check

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).

Buy nines with copies

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.

3
2.0%
24 h

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:

KindWhat you getDurability (vendor)Price, illustrative
Blocka disk for one machine: fast reads and writes of small blocks (EBS, a local SSD)EBS gp3 99.8 to 99.9% a yearabout $0.08 per GB a month
Filepaths and directories that many machines share (NFS, EFS)varies by serviceabout $0.30 per GB a month
Objectwhole objects by key over HTTP; no partial overwrite (S3, Cloud Storage)designed for 11 ninesabout $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.

Why does a third copy add so much more durability than its cost suggests?

Chapter 5

Shape the Data for the Question

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.

Ask four stores one question

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.

Say it aloud

E equals the sum over i from 1 to k of d to the i.

E
E the edges followed to answer the query.
Σi=1..k
the sum over i from 1 to k add one term for each hop.
d
d the degree: friends per user, 200 here.
i
to the i hop i reaches d times as many people as hop i minus one.
In plain words

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 numbers

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.

Users have 200 friends each. How many edges does a friends-of-friends query follow, and what does it depend on?

Chapter 6

Store by Row or by Column

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.

Say it aloud

B-col equals N times the sum over the read columns of w-j, divided by c.

Bcol
B-col bytes a column store reads from disk for the query.
N
N rows in the table: one billion here.
Σj∈read
the sum over the read columns add the widths of only the columns the query names.
wj
w-j bytes per value in column j: 8 here.
c
c the compression ratio: raw bytes over stored bytes. 4 here, illustrative.
In plain words

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 numbers

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.

Scan a billion orders

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.

3 of 50

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.

A query reads 3 of 50 equal columns. About how many times fewer raw bytes does a column store read than a row store?

Chapter 7

Who Writes the Cache?

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.

PatternRead pathWrite pathCache dies
Cache-asideapp checks the cache; on a miss it reads the database and fills the cacheapp writes the database, then deletes the cache keyslower, nothing lost
Read-throughapp asks the cache; the cache loads misses itselfany of the write patternsreads fail unless the app falls back
Write-throughfrom the cachecache writes the database, then answers: database speednothing lost
Write-behindfrom the cachecache answers at once and flushes to the database in batchesunflushed 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.

Say it aloud

Lost equals lambda-w times F, over 2.

lost
lost the acknowledged writes a cache crash erases, on average.
λw
lambda-w writes per second into the cache: 500 here.
F
F the flush interval: seconds between flushes to the database, 10 here. Over 2: a crash lands halfway through the window on average.
In plain words

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 numbers

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.

Crash the cache

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.

Write-behind flushes every 10 s and takes 500 writes a second. The cache crashes at a random moment. How many acknowledged writes are lost on average?

Chapter 8

A Cache in Each App, or One for All

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.

Say it aloud

S equals r, times n minus one over n, times TTL over 2.

S
S stale reads served after one write, on average.
r
r reads of this key per second, over all instances: 80 here.
n − 1
n minus one the instances that did not take the write and keep the old copy.
n
over n reads spread evenly, so this is the share of reads that land on those instances. n = 8 here.
TTL
T-T-L over 2 the local time to live, 30 s here. A cached copy has half its TTL left on average.
In plain words

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 numbers

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.

Write user 42

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).

Eight instances cache user 42 locally. Instance 1 takes a write and drops its own copy. How many instances can still serve the old value?

Chapter 9

A Cache You Can Size, Scan and Kill

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.

Run the cache

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.

20 keys
10 s

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:

  1. Zipf, 20 keys, LRU. The hit ratio settles near 55%. The top 20 keys get 69% of the traffic, so a perfect 20-key cache would reach 69%.
  2. Switch to uniform. It falls to about 18%, near the 20% of keys that fit. No key is hot, so only size helps.
  3. Back to Zipf, then run the batch scan. Under LRU, the scan's one-time keys push the hot keys out. Under LFU the hot keys' counts protect them.
  4. Drop the TTL to 0.1 s. Copies expire before their next read, and the hit ratio falls to about 37% at any size.
  5. Kill the cache. Every request reaches the database: 2.2 times the load it saw at a 55% hit ratio, because 1 / (1 − 0.55) = 2.2.

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.

A nightly job reads 10,000 cold keys once each through the cache. Which eviction policy keeps the hot keys?

Chapter 10

The Field Guide

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.

Terms and numbers

TermWhat it isThis lesson's number
Read load per serverL = R(1 − h) / n40,000 reads, h 0.9, n 4: 1,000 a second
Group commitX = B / tftf 5 ms: 200 a second alone, 3,200 at B = 16
Sync commitleader fsync + round trip + follower fsync5 + 1 + 5 = 11 ms, illustrative
Async losslost = λw · Δ2,000 writes, 0.2 s lag: 400
Multi-leader conflictsP = 1 − e−2λdλ 0.1, d 0.15 s: 2.96%
Loss with r copiesPloss ≈ rλ(λT)r−12% AFR, 24 h repair, r 3: 1.8 × 10−10 a year
Graph hopsE = Σ did 200, 2 hops: 40,200 edges
Column scanBcol = N Σwj / c400 GB by row against 6 GB by column
Write-behind losslost = λw F / 2500 writes, F 10 s: 2,500 on average
Local cache stalenessS = r (n − 1)/n · TTL / 280 reads, 8 instances, 30 s: 1,050

Which store for which job

JobChoiceExamples
Sessions, carts, lookups by keykey-valueRedis, DynamoDB
Records of varying shape, queried by fielddocumentMongoDB, Firestore
Events per entity, sorted by timewide-column with a clustering keyCassandra, Bigtable
Paths through relationshipsgraphNeo4j, Neptune
Scans and sums over a few columnscolumnar files or a column storeParquet, Dremel and BigQuery
Large blobs, backupsobject storage in several zonesS3, Cloud Storage

Corrections to common figures

Checklist

  1. Know where "saved" happens for every write path: memory, one disk, or two machines.
  2. Use group commit or batched transactions before buying a faster disk.
  3. Wait for one follower of several, not all of them.
  4. Give each key one home leader unless you have a merge rule.
  5. Spread copies over failure domains: racks, zones, regions.
  6. Pick the data model from the questions you will ask most.
  7. Run analytics on columnar copies, not on the transactional database.
  8. Cache-aside with delete-on-write and a TTL as the default; write-behind only for data you can lose.
  9. Keep local cache TTLs in seconds; use LFU when batch jobs share the cache.

The core as code

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

Keep going

The takeaway. Decide where "saved" happens before you decide anything else: memory is fast and forgetful, one disk survives a power cut, two machines survive a dead machine. Then add copies across failure domains, shape the data for its questions, and treat every cache as a copy you must invalidate.

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.

Data Storage & Caching
GFS 2003 · Dremel 2010 · Redis eviction · Back to Gleams