Kayavak / The Backend / BE·53 Caching / Deeper
Deeper · The Backend
Caching
The questions the chapter doesn't stop for: why this exists, the model to keep in your head, what changes when an assumption does, how sure we are of each claim, and what's still open. Read it after the chapter; back to the chapter.
Why does this exist?
Caching is as old as fast memory next to slow memory (Foundations, ch07). In 1966 László Bélády described the optimal replacement policy: evict the item whose next use is furthest in the future. It needs knowledge of the future, so real caches approximate it with least-recently-used, least-frequently-used and their refinements; Caffeine's W-TinyLFU (Einziger, Friedman and Manes, 2017) estimates frequency in a small, compact sketch and comes close to optimal on many workloads.
Web-scale applications made shared caches a standard tier. Brad Fitzpatrick wrote Memcached (2003) to keep LiveJournal's database from collapsing under reads; Redis (Salvatore Sanfilippo, 2009) added data structures and persistence. A saying usually attributed to Phil Karlton holds that "there are only two hard things in computer science: cache invalidation and naming things", and most of this chapter is about the first.
The mental model
Try it yourself first: write your own model in the Mental Model Explorer, then compare.
A cache trades correctness for speed: it answers from a copy that may be stale. It works because a small share of items gets most of the requests. Decide how stale is acceptable, and what happens when the cache is empty, slow or gone.
| Question | Answer |
|---|---|
| What is it? | Keeping copies of expensive results closer to where they're needed |
| Problem it solves | Latency and load on slow or expensive sources |
| Parts | Layers (HTTP, in-process, distributed, database), patterns (cache-aside, read/write-through, write-behind), keys, TTLs, eviction, invalidation |
| How it works | Look in the cache; on a miss, compute or load, store, return; expire or invalidate when the source changes |
| Assumptions | Popularity is skewed; some staleness is acceptable; the source can survive a cold cache |
| When they change | Uniform access gives low hit rates; a cold cache after a restart sends all traffic to the database at once |
| Where it fails | Stale data after writes, stampedes on popular expired keys, caches that grow into a second database |
| Related ideas | Memory hierarchy (Foundations, ch07); HTTP caching (The Web Frontend, ch19); consistency (Distributed Systems) |
What if?
What if a very popular key expires while thousands of requests want it?
Reason it through, then open
Every one of them misses at the same moment and goes to the database to rebuild the same value: a cache stampede. The database may fall over and the cache stays empty. Single-flight (one request rebuilds, the rest wait for its result), refreshing before expiry, and jittered TTLs prevent it.
What if the cache cluster disappears?
Reason it through, then open
All reads go to the source at once. If the database was sized assuming a 95% hit rate, it suddenly sees twenty times its normal load. A cache that the system can't run without is no longer an optimisation but a dependency, and needs the capacity planning and failure handling of one.
Where the boundary is
| Aspect | TTL expiry | Explicit invalidation |
|---|---|---|
| Staleness | Up to the TTL | Until the invalidation arrives (usually short) |
| Complexity | Low | High: every write path must invalidate correctly |
| Failure mode | Stale reads for a bounded time | Missed invalidations: stale until the next one |
| Common choice | Both: invalidate on write, TTL as a safety net |
Derive it
How much a cache actually saves.
- Let a cache hit cost h, a miss cost m (the source's latency plus the cache lookup), and the hit rate be p.
- Average latency = p·h + (1 − p)·m.
- With h = 1 ms, m = 50 ms: at p = 0.9 the average is 0.9 + 5 = 5.9 ms; at p = 0.99 it's 0.99 + 0.5 ≈ 1.5 ms.
- Load on the source scales with 1 − p: going from 90% to 99% hits cuts source load tenfold.
- So the last few percent of hit rate matter far more than they look, both for latency and for how much the source must handle, and a fall from 99% to 90% (after a deploy flushes the cache, say) multiplies source load by ten.
How sure are we?
| Claim | How it's known | Where from |
|---|---|---|
| Bélády's policy is optimal | Theorem | Bélády, 1966, for a fixed sequence of requests |
| Average latency = p·h + (1 − p)·m | Model | Ignores queueing under load |
| Web request popularity is skewed (roughly power-law) | Measured | Many studies of web and CDN traffic |
| The "two hard things" quote is Phil Karlton's | Historical, uncertain | Widely attributed; no primary source |
Still open
Choosing eviction policies adaptively and keeping caches consistent with databases cheaply (change-data-capture driven invalidation, leases) remain active areas.
What would change your mind? If your access pattern were close to uniform, caching would buy little; measure the hit rate before adding a tier.
Recall
What's the average latency of a cache with hit rate p?
p × hit cost + (1 − p) × miss cost.
Why does going from 90% to 99% hits matter so much?
Source load is proportional to the miss rate, which falls tenfold.
What is a cache stampede and how do you prevent it?
Many requests rebuilding the same expired key at once; use single-flight, early refresh or jittered TTLs.
What's Bélády's optimal policy?
Evict the item whose next use is furthest in the future.
Reflect
Be honest with yourself; this stays in your browser. Anything you can't tick yet is what to revisit.