Lesson 02

Caching at Scale

Building block

A cache is the cheapest capacity a read-heavy system can buy, and it is bought with a number: the hit rate. At 90 percent, nine reads in ten never reach the store, so the store carries a tenth of the traffic. At 99 percent it carries a hundredth. Every caching decision in an interview comes down to what that number is, what it costs to raise it, and what happens to the store in the minute it falls.

This lesson treats the cache as a tier of many machines, which is how an interview treats it. How one service talks to one cache, from the read that falls through to the stampede on one expiring key, is the subject of Backend Deep Dive's caching chapter, and this lesson does not repeat it.

The Hit Rate Decides

What reaches the store is the read rate times the miss rate. Take 20,000 reads a second. At a 95 percent hit rate, 5 percent miss, and 1,000 reads a second reach the store. At 99 percent, 200 do. Moving the hit rate from 95 to 99 percent sounds like four points; for the store it is a fivefold cut, because a cache is judged by its misses, not its hits.

The hit rate is set by the traffic before it is set by the cache. When a small share of the keys takes most of the reads, a small cache holds most of the hits, and that skew is what makes a cache worth its memory. Traffic spread evenly over billions of keys gives a cache little to do. So the first question about any cache is not which product, but how skewed the reads are.

The same 20,000 reads a second at two hit rates
95 percent hits1 read in 20 misses
19,000 answered by the cache. 1,000 a second reach the store.
99 percent hits1 read in 100 misses
19,800 answered by the cache. 200 a second reach the store, a fifth of what reaches it at 95 percent.

Who Writes the Cache

Four patterns decide who puts a value in the cache, and each one fails differently. In cache-aside, the application reads the cache, falls through to the store on a miss, and fills the entry itself. In read-through, the cache does that fetch on the application's behalf. Both fill only what is read, but when the cache tier is down only cache-aside still has a path to the store; read-through needs one the application keeps for that case, and either way the store has to take every read.

In write-through, every write goes to the cache and the store together, so a key that was just written is already warm. It costs a cache write on every store write, and keys that are written but never read take memory for nothing. In write-behind, the cache acknowledges the write and flushes it to the store later. That makes writes fast, and it means a cache node that dies before the flush takes acknowledged writes with it. In an interview, write-behind needs a reason good enough to accept that loss.

Layers on the Read Path

A read can stop at several places before it reaches the store: in the client, at the edge, in a small cache inside each application server, or in the shared cache tier. Each layer is closer to the reader and faster to answer. Each also holds less and is harder to invalidate, because there are more copies of it and they are further away.

Choosing the layers is choosing how stale each answer may be. A product description can sit at the edge for an hour. A price can sit in the shared tier for seconds. An account balance may not be cached at all. A strong answer names the layers it uses and the staleness each one allows, and says which read in the system must never be stale.

Read path layers, nearest the reader at the top
Client
fastest, most copies, hardest to recall
Edge
a CDN, purged by key or by expiry
Local cache in each server
seconds of staleness, no network hop
Shared cache tier
one copy per key, invalidated on write
Store
the source every layer can be rebuilt from

A Cluster, Not a Box

At scale the shared tier is many nodes, and each key belongs to exactly one of them, chosen by hashing the key. How that assignment survives nodes joining and leaving is consistent hashing, taught in Chapter 3; here it is enough that the keys spread and that one key always lands on one node. Each node can carry a replica, so that losing a node costs a failover instead of its share of the hits.

The failure to plan for is the node that goes without a replica. Its keys all miss at once, and the arithmetic from the start of this lesson says how much load moves. With 20,000 reads a second spread over ten nodes, losing one sends its 2,000 reads a second to the store at a cold hit rate of zero. A store sized for the 200 a second it sees on a good day takes about eleven times that until the node's keys are warm again.

One cache node of ten is lost
With a replicafailover
The replica takes over the node's keys. The store sees no change.
Without a replicacold keys
The node's 2,000 reads a second all miss and go to the store until they are warm again.

Sizing It

The memory a cache needs is set by the working set, the keys that are actually read, not by the size of the data. Say the reads go mostly to entries from the last month, 300 million of them at 500 bytes each. That is 150 GB. A mid-size memory-optimised cache node holds about 100 GB, so the working set fits on two nodes with room to spare, and doubling them for replicas gives four.

Past the working set, more memory buys little. The keys outside it are read rarely, so caching them raises the hit rate by a fraction of a point at the cost of a node. That is the point to say out loud in an interview: the cache is sized to the hot set, and the long tail goes to the store.

Cache-Aside vs Write-Through

Cache-aside fills only what is read and survives a cache outage by sending every read to the store. Use it when reads are skewed and a miss is affordable.

Write-through keeps every written key warm and costs a cache write on every store write. Use it when a read right after a write must hit the cache and writes are few.

How Interviewers Probe This

The first probe is "What is your hit rate, and why?" A good answer names the skew in the traffic, gives a number, and says what reaches the store at that number. You might say: "Most reads go to links from the last month, so I'll assume 99 percent, which leaves the store about 200 reads a second at peak."

The second is "A cache node dies. What happens?" A good answer says that the node's keys miss, puts a number on the load that moves to the store, and names what absorbs it: a replica, or headroom the store was given on purpose.

The third is "How stale can a read be?" A good answer ties the expiry time and the invalidation path to what the product can tolerate, and names the one read that must never be stale. An answer that only says "we set a TTL" has not answered it.

Misconceptions
  • "A cache makes every read faster." A miss now pays for the cache lookup and the store read, so the average improves only when the hit rate pays for that extra trip on every miss.
  • "An expiry time solves invalidation." It bounds how stale an entry can get. It does not make the entry correct, and a page that must never show a deleted value needs invalidation on write.
  • "The cache is a fast database." It evicts under memory pressure and can lose everything on a restart. A design that cannot rebuild the cache from the store has two databases, and one of them is unreliable.
  • "Doubling the memory doubles the hit rate." The hit rate follows the skew of the traffic. Once the hot set fits, extra memory holds keys that are read once.
  • "One big cache node is simpler." It is one failure that sends every read to the store at the worst moment. A tier of smaller replicated nodes loses a fraction instead.
Why It Matters
  • State the hit rate you assume and what reaches the store at that rate, before you name a cache product.
  • Size the cache from the working set and the memory of one node, then add replicas for the failure case.
  • Pick the pattern by the failure you can afford: cache-aside when a miss is fine, write-through when a stale read right after a write is not.
  • Say what happens to the store when the cache is cold or a node is gone, and how the system survives that minute.
RelatedBackend Deep Dive one service's cache-aside and stampedeRead Replicas and Lag the other read-path toolConsistent Hashing how keys find their node

Knowledge Check

A service takes 20,000 reads a second. Its cache hit rate rises from 95 to 99 percent. What happens to the reads that reach the store?

  • They fall by about four percent, from 1,000 a second to 960
  • They fall to a fifth, from 1,000 a second to 200 a second
  • They stay about the same, because the store still holds every key
  • They fall to almost nothing, since nearly every read is now cached

The cache tier goes down for a minute. Which pattern keeps the system answering, and at what price?

  • Write-behind, because the store is updated later in the background
  • Write-through, because every key already sits in both places at once
  • Cache-aside, as long as the store can carry every read for that minute
  • None of them, because every pattern needs the cache to answer reads

Reads go mostly to 300 million recent entries of 500 bytes each. How should the cache be sized?

  • To the 150 GB working set, about two nodes plus their replicas
  • To the whole data set, so that every read is a hit from the start
  • To a single large node, which avoids partitioning the keys at all
  • To half the working set, because the hit rate barely changes below it

One of ten cache nodes dies and it had no replica. The tier serves 20,000 reads a second. What does the store see?

  • No change, because the other nine nodes simply take over its keys
  • All 20,000 reads a second, because the whole tier is now cold
  • About 2,000 more reads a second until the lost keys are warm again
  • About 20 more reads a second, its share of the usual 1 percent misses

The interviewer asks how stale a read can be. Which answer is strongest?

  • "We set a short expiry time on every key, so staleness stays small."
  • "Nothing is cached that could change, so staleness never comes up."
  • "Write-through keeps the cache current, so no read is ever stale."
  • "Seconds for prices, an hour at the edge, and balances never cached."

You got correct