Caching (System Design #12)
A product page is read 50,000 times a minute and changes twice a day. Without a cache, every one of those reads hits the database, and the database — which is also handling writes, joins, and reports — becomes the bottleneck. With a cache, 99% of reads never touch the database. Caching is the single highest-leverage performance tool in system design, and the single easiest to get wrong.
The hard part is not storing a value; it is deciding when that value is too old. This chapter covers where caches live, the four write strategies, eviction, invalidation, and the failure modes that turn a cache from a savior into an outage.
Why caching works
Caching exploits locality: real workloads repeat. A small number of items get most of the reads (Zipf-like). The metric that matters is the hit rate:
\[ \text{origin load} = \text{requests} \times (1 - \text{hit rate}) \]
A 95% hit rate cuts origin load 20×. A 50% hit rate barely helps and adds a network hop. This is why the hit rate — not the cache size — is the number to watch. A cache that misses half the time is a slow proxy.
The trade is always freshness for speed. You are deliberately serving a copy that may be stale. Decide per data set how stale is acceptable; that answer drives the TTL and the strategy.
Where caches live
Every layer can cache, and they compose:
| Layer | Caches | Example |
|---|---|---|
| Client | rendered responses, assets | browser cache, service worker |
| CDN/edge | static assets, media, some APIs | CloudFront, Cloudflare |
| Web server / reverse proxy | responses, fragments | Nginx, Varnish |
| Application | computed objects, DB rows | Redis, Memcached, in-process |
| Database | query results, pages | buffer pool, materialized views |
The rule is cache as close to the user as correctness allows, because that removes the most work. Immutable assets cache at the client and CDN forever; personalized data caches in the app tier with short TTLs. Keep authoritative copies only in the database.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
b/.style={draw, thick, rounded corners=3pt, minimum width=1.55cm, minimum height=0.68cm, align=center, font=\rmfamily\small},
a/.style={->, thick}]
\node[b, fill=gray!10] (u) at (-4.6,0) {user};
\node[b, fill=blue!10] (b1) at (-3.0,0) {browser};
\node[b, fill=orange!16] (cdn) at (-1.2,0) {CDN};
\node[b, fill=green!12] (app) at (0.9,0) {app cache};
\node[b, fill=yellow!22] (db) at (3.0,0) {database};
\draw[a] (u) -- (b1); \draw[a] (b1) -- (cdn); \draw[a] (cdn) -- (app); \draw[a] (app) -- (db);
\node[font=\rmfamily\small, text=black!60, anchor=north] at (-0.8,-0.55) {closer to the user = more work removed};
\end{tikzpicture}
Write strategies
Four patterns govern how the cache and the database stay in sync.
Cache-aside (lazy loading). The application owns the logic: read the cache; on a miss, read the database, store it, return it. Writes go to the database and invalidate the cache entry.
def get_user(uid, cache, db):
if (hit := cache.get(uid)) is not None: # fast path
return hit
row = db.read(uid) # miss: slow path
cache.set(uid, row, ttl=300) # fill for next time
return row
def update_user(uid, patch, cache, db):
db.update(uid, patch)
cache.delete(uid) # invalidate; next read repopulates
Cache-aside is the default: simple, resilient (a cache outage degrades to the database, not to a crash), and works for most read-heavy data.
Write-through. Every write goes through the cache to the database synchronously; the cache always holds the latest value. Reads are always fast and fresh, but every write pays cache + database latency, and the cache is on the critical write path.
Write-behind (write-back). The write hits the cache and is flushed to the database asynchronously. Extremely fast writes, but a crash before flush loses data. Use only where the write is reconstructible or loss is tolerable (counters, analytics).
Refresh-ahead. The cache proactively refreshes entries before they expire, so hot reads never see a miss. Great for predictable hot data; wastes work refreshing entries nobody reads again.
| Strategy | Read latency | Write latency | Risk |
|---|---|---|---|
| Cache-aside | fast on hit | database only | stale reads on missed invalidation |
| Write-through | always fresh | cache + DB | write path coupling |
| Write-behind | fast | fastest | data loss on crash |
| Refresh-ahead | no misses on hot | background | wasted refreshes |
\begin{tikzpicture}[font=\rmfamily, >=stealth,
b/.style={draw, thick, rounded corners=3pt, minimum width=1.6cm, minimum height=0.68cm, align=center, font=\rmfamily\small},
a/.style={->, thick}]
\node[b, fill=green!12] (app) at (-3.4,0) {app};
\node[b, fill=orange!16] (c) at (-0.9,0) {cache};
\node[b, fill=blue!10] (db) at (1.6,0) {database};
\draw[a] (app) -- node[above, font=\scriptsize] {1 read} (c);
\draw[a] (c) to[bend left=22] node[below, font=\scriptsize] {2 miss} (app);
\draw[a] (app) -- node[above, font=\scriptsize] {3 read} (db);
\draw[a] (db) to[bend left=22] (app);
\node[font=\rmfamily\small, text=black!60] at (0,-1.0) {4 fill, then serve};
\end{tikzpicture}
Eviction and TTL
A cache is finite; something must go when it fills.
- TTL — a fixed lifetime. Simple and predictable; the entry is fresh-enough for that window regardless of access.
- LRU (least recently used) — evict the item not accessed for the longest time. Good when recency predicts reuse.
- LFU (least frequently used) — evict the least-accessed item. Good when popularity is stable; slow to adapt to changing trends.
- Admission control — do not cache everything; protect against flooding the cache with one-hit items (a long-tail scan) that evict genuinely hot data.
TTL plus LRU is the common combination: TTL bounds staleness, LRU bounds memory.
Invalidation: the genuinely hard problem
There are only two hard things in computer science: cache invalidation and naming things.
Because the cache is a copy, every write to the source must eventually invalidate or update the copy. Options, from simplest to most complex:
- TTL expiry — let it go stale for at most the TTL. Simplest; a bounded staleness window.
- Explicit invalidation — delete or update the key on write. Correct, but you must find every key affected (denormalized copies multiply this).
- Versioned keys — embed a version in the key (
user:42:v7); a write bumps the version, and old keys age out. Avoids deletes. - Write-through/behind — the cache is updated as part of the write, so it never holds stale data (at other costs).
The classic bug is a race: reader misses, reads the old value from the database, then a writer updates the database and invalidates the cache, then the reader writes its stale value into the cache. The cache now holds stale data until TTL. Mitigations: delete-then-write ordering, short TTLs on race-prone keys, or versioned keys.
Failure modes: stamps, avalanches, and hot keys
- Cache stampede / thundering herd. A hot key expires and a thousand concurrent requests all miss and hit the database at once. Fix with a per-key lock (one request recomputes, the rest wait or serve stale), or by refreshing ahead.
- Cache avalanche. Many keys expire at the same instant (same TTL), collapsing the origin. Fix by jittering TTLs.
- Hot key. One key absorbs enormous traffic and saturates a single cache node. Fix by sharding the key into copies (
key:1..N), or caching in-process on each app server. - Cache as source of truth. If the cache holds the only copy, a flush is data loss. Always keep the authority in durable storage.
def get_with_lock(key, cache, db):
if (v := cache.get(key)) is not None:
return v
lock = cache.lock(f"lock:{key}", ttl=5)
if lock.acquire(blocking=False): # one winner recomputes
try:
v = db.read(key); cache.set(key, v, ttl=300 + random_int(0, 60))
return v
finally:
lock.release()
return cache.get_stale(key) or db.read(key) # others: stale or wait
The TTL jitter (+ random 0..60) prevents synchronized expiry; the lock prevents a stampede on a single key. Both are cheap and prevent real outages.
Pitfalls
- No invalidation plan. “It will expire eventually” is fine only if you accept the staleness window and size it deliberately.
- Low hit rate. A cache that misses often adds a hop without saving work. Measure the hit rate and fix the key/TTL design.
- Synchronized TTLs. Same-expiry keys cause avalanches. Always jitter.
- Treating the cache as durable. A flush or eviction must never lose data. The database is the truth.
- Caching personalized data in a shared cache. Serving one user’s data to another is a security incident. Partition by user/tenant or mark
private. - Ignoring thundering herds. A popular key expiring under load can take down the database. Lock or refresh ahead.
Why is the hit rate more important than cache size? What is a cache stampede, and how do you prevent it?
ASolution
Origin load depends on the miss rate, so a larger cache with a poor hit rate still forwards most requests downstream. A stampede is many concurrent requests missing on the same just-expired hot key and all hitting the database; prevent it with a per-key lock (one recompute) and TTL jitter, or by refreshing ahead.
Next: Asynchronism: Queues and Back Pressure (System Design #13) — handling spikes without falling over.