Learn

PATTERN · ORIGINAL

Caching and hot keys

Cache-aside vs write-through, TTLs and invalidation, stampede protection, hot-key tactics, negative caching, and how to make a takedown beat your own caches.

A cache is a copy you are allowed to be wrong about for a while. That framing helps more than any list of cache products: every caching decision is really two decisions. How wrong can this copy be, and for how long? And what happens to the system behind it when the copy is missing?

This article covers the patterns you will draw most often, the failure modes interviewers like to poke at, and the specific case of one key getting far more traffic than the rest.

Where a cache sits

Most read-heavy designs end up with three layers, and it helps to draw them separately because each has a different job:

  • Edge or CDN: closest to users, great for public, identical responses (images, video segments, redirects, public pages). You control it mainly through TTLs and purge calls.
  • Local in-process cache: a small map inside each service instance. No network hop, so it is the fastest layer, but every instance has its own copy and they drift apart.
  • Shared cache tier: a cluster of in-memory nodes, partitioned by key. One copy per key (plus replicas), so invalidation is easier, but every read costs a network round trip.
FIG. 4ORIGINAL SKETCH
GET1miss2get3hot: any copymiss: load4change stream5delete key6ClientsEdge cachepublic responsesAPI + localcachehot keys, 1-5 sShared cachesharded by keyHot key copieskey#1..key#8DatabaseInvalidator
A layered read path: edge cache, a small local cache per API instance for hot keys, a partitioned shared cache, and the database; hot keys are copied to several cache nodes and invalidations flow from the database change stream.

Cache-aside vs write-through

Cache-aside (also called look-aside or lazy loading): the application reads the cache; on a miss it reads the database and puts the value in the cache. On a write, the application updates the database and then deletes the cache entry. The cache only ever holds data someone asked for, and if it dies the system still works, just slower.

Write-through: every write goes to the cache and the database together, so the cache is always populated with the latest value. Reads right after writes hit the cache. The cost is that you cache things nobody reads, and writes are slower because they touch two systems.

Write-behind (write-back) takes writes into the cache and flushes to the database later. It absorbs write bursts, which is why it shows up in counters, but a cache node failure can lose acknowledged writes. Only use it where losing a few seconds of updates is acceptable, as in some like counter designs.

OptionWins whenCosts
Cache-aside, delete on writeRead-heavy, data changes occasionally, cache failure must not break correctnessFirst read after a write or eviction is a miss; a race can briefly re-cache an old value
Write-throughReads usually follow writes closely and must see the new valueCaches cold data; write latency includes the cache; still needs eviction
Write-behindVery high write rates to a few keys where a small loss is acceptableAcknowledged writes can be lost on cache failure; harder to reason about
TTL only, no invalidationData tolerates fixed staleness (weather, rankings, public pages)Every reader may see data up to one TTL old; no way to force freshness except purge

Why delete on write instead of updating the cache with the new value? Because two concurrent writers can apply their cache updates in the opposite order from their database commits, leaving the old value cached indefinitely. Deleting is safer: the next reader loads whatever the database holds. There is still a smaller race (a slow reader loads an old value and writes it after the delete), which is why a TTL is a useful backstop even on invalidated keys. The Facebook memcache paper in further reading describes using leases to close this gap.

TTLs and invalidation

A TTL is a promise about maximum staleness. Choose it from the product, not from habit:

  • A weather forecast updates every 10 to 15 minutes upstream, so a TTL of a few minutes loses nothing and serves almost every read from cache.
  • A redirect in a URL shortener never changes destination, but it can be disabled. The TTL is set by the takedown requirement (for example, 60 seconds), not by the data.
  • Autocomplete suggestions can be minutes or hours old. Long TTLs at the edge make the read path almost free.

Explicit invalidation (delete on write, or a worker consuming the database change stream) gives fresher data than a TTL, but it is another moving part that can fail. Use both: invalidate for freshness, and keep a TTL so a lost invalidation heals on its own.

Stampedes

A stampede (thundering herd) happens when a popular key expires or is evicted and thousands of concurrent requests all miss at once, all hit the database, and all try to rebuild the same value. A key read 20,000 times per second with a 100 ms rebuild means about 2,000 requests pile onto the database in that window. Three defences, usually combined:

  1. Request coalescing (single-flight): only one request per key rebuilds the value; the others wait for its result. Do it per process (cheap, a map of in-flight futures) and, if needed, across processes with a short lock or lease in the shared cache.
  2. Jittered expiry: add a random 0-20% to every TTL so keys written at the same moment (a deploy, a cache warm-up) do not expire at the same moment.
  3. Refresh ahead of expiry: serve the cached value while one background request refreshes it shortly before the TTL ends. Probabilistic early refresh does this without coordination: each reader has a small chance of refreshing that grows as expiry approaches.

A fourth, often forgotten: serve stale on error. If the database is slow or down, returning a value that is a minute old is usually better than returning an error. Store the value with a soft expiry and a longer hard expiry.

Hot keys

A shared cache partitions keys across nodes. That works until one key is hot enough to saturate the node that owns it: a viral link, a celebrity profile, the homepage config. At roughly 100,000 operations per second per cache node, a key that gets 300,000 reads per second cannot be served by one node no matter how big the cluster is. Adding nodes does not help, because the key still lives on one.

Local caches for the hottest keys

Keep a small in-process cache with a short TTL (1 to 5 seconds). With 200 API instances and a 2-second TTL, the shared cache sees at most about 100 reads per second for that key regardless of traffic. This is the cheapest fix and handles most cases. The cost is that each instance can be a couple of seconds behind.

Replicate the key

Store copies under derived keys, link:abc#1 through link:abc#8, which hash to different nodes. Readers pick one at random; writers update or delete all eight. Use this only for keys you have detected as hot, because it multiplies write and invalidation cost.

Split the key for writes

When the hot path is writes (a counter getting thousands of increments per second), split the value itself into shards: likes:post42:0..15. Each write picks a random shard; reads sum them, ideally from a cached total refreshed every second. Counting at scale covers this in detail.

Detect hotness

All of these need you to know a key is hot. Sample requests in each API instance, track the top keys over a short window, and promote anything over a threshold into the local cache or replica set. Writing “hot-key detector: top-K over 10 s” next to the cache on your sketch is a good answer to the inevitable follow-up.

Negative caching

Misses for keys that do not exist go straight to the database every time, because there is nothing to cache. A scraper probing random short links, or a bug requesting a deleted id in a loop, can push more load onto the database than all real traffic. Cache the absence: store a “not found” marker with a short TTL (tens of seconds). Keep it short, because a key that does not exist now might be created a moment later, and a stale “not found” is a visible bug. For huge key spaces under attack, a Bloom filter of existing keys can reject most invalid lookups before they reach the cache.

Takedowns and staleness you must beat

Some data must stop being served quickly even though caches hold copies: an abusive link, a leaked document, a removed video, revoked access. The trap is that every cache layer you added for speed is now a place the takedown has to reach. Three rules make it work:

  • Bound every layer with a TTL no longer than the takedown requirement. If links must die within a minute, no cache, edge included, may hold a redirect longer than a minute. Avoid responses that browsers cache indefinitely (a permanent redirect, for example).
  • Check a small deny-list on every request that reaches your service. Takedowns are rare, so the list is tiny and can be replicated to every instance. A stale cached mapping cannot bypass it.
  • Purge actively, but do not rely on purge alone. Send purge requests to the edge and delete from the shared cache, but treat them as best effort. The TTL bound is what guarantees the deadline when a purge is lost.

The same thinking applies to private data. A response that depends on who is asking must never be cached at a shared layer keyed only by URL. If you see an edge cache in your sketch, write which responses are allowed in it.

Caching interacts with almost every other pattern. Fan-out on write is really pre-computing a cache of each user's timeline (fan-out and real-time delivery), and whether a cache is worth it at all comes down to the working-set estimate in estimates that drive decisions. For a primary source on CDN-fronted media storage, see the Haystack case study. For video streaming, the edge layer is the design; the database barely matters.

TAKE THIS TO YOUR NEXT SKETCH

  • For every cache, write down how stale it may be and what happens behind it when it is empty.
  • Default to cache-aside with delete on write plus a TTL backstop; pick write-through or write-behind only for a stated reason.
  • Set TTLs from product requirements, especially takedown deadlines, and jitter them.
  • Stop stampedes with request coalescing, refresh ahead of expiry, and serving stale on error.
  • A hot key saturates one node; use short-lived local caches first, then replicate or split the key.
  • Cache "not found" briefly so missing keys cannot hammer the database.
  • Make takedowns reliable with bounded TTLs everywhere and a deny-list checked on every request, with purge as best effort.

PRACTICE WITH THIS

Now sketch one.

OFF-SITE READING · NOT WRITTEN BY US

Further reading

Next: Case study: reading the Dynamo paper