Caching & Failure Modes
From memory hierarchy latency to Cache-Aside, Write-Through, and surviving the three production cache outages: thundering herd, penetration, and avalanche.
Caching works because of two facts of physics and human behavior: RAM is orders of magnitude faster than disk, and real-world traffic follows a power law (often 80% of reads hit 1–5% of keys).
~0.5 ms
in-VPC Redis / Memcached read
5–50 ms
indexed SQL query under load
200×
fan-in spike on one hot key miss
Three caching patterns
Every caching architecture chooses who talks to the database and when the cache gets updated:
- Cache-Aside (Lazy Loading): the application checks the cache first. On a
miss, it queries the DB, writes the result into the cache with a TTL, and
returns it. On writes, the app updates the DB and invalidates (deletes)
the cache key.
- Win: only requested data consumes RAM; if the cache node dies, requests degrade to the DB rather than failing writes.
- Write-Through: every write updates the cache and the DB synchronously
before returning.
- Win: reads almost never miss and rarely see stale data. Cost: higher write latency and cold keys occupy precious RAM.
- Write-Back (Write-Behind): writes go only to the cache and return
immediately; a background worker flushes dirty entries to the DB in batches.
- Win: absorbs massive write bursts (e.g. view counters). Cost: a cache crash before flush permanently loses unpersisted writes.
note
Why delete the cache key on DB writes instead of updating it? If two concurrent writes A and B race, the cache can end up holding A while the DB holds B — permanent staleness until TTL expiry. Deleting the key forces the next reader to reload the latest committed row.
Break it: the three production cache outages
A warm cache hides your database’s true capacity limit. When the cache stops shielding the origin, traffic hits the database all at once.
1. Thundering Herd (Cache Stampede)
One ultra-hot key (a viral post, homepage config, or flash-sale item) hits its TTL and expires. In the 40ms it takes the first request to query the database, 199 more concurrent requests also miss and fire identical queries at the origin — melting the DB.
Trigger a hot-key expiry below in naive mode to watch a 200-query thundering herd overload the database, then test singleflight and TTL jitter + stale-while-revalidate.
interactive · expire the hot key under 200 concurrent requests, then test each guard
status: OVERLOAD · 200 DB queriesswitch guard mode, then expire hot key
2. Cache Penetration (missing keys)
A bug or malicious scraper requests keys that do not exist in the database
(/users/-1, random UUIDs). Because nothing exists to cache, every request
misses Redis and hits the DB directly.
- Fix 1 — Negative caching: cache a short-TTL sentinel (
"__NULL__", 30–60s) for missing keys so repeated lookups stop at Redis. - Fix 2 — Bloom filter: keep a compact Bloom filter of valid IDs in front of the cache. If the filter says “not present”, reject immediately with zero DB queries (accepting a tiny false positive rate that falls through safely).
3. Cache Avalanche (synchronized expiry)
Thousands of keys were loaded at the same time (e.g. a nightly batch job or
service restart) with the exact same TTL = 3600s. One hour later, the entire
working set expires in the same second, dropping cache hit rate from 99% to 0%.
- Fix — TTL jitter: add a random offset to every TTL (
3600 + rand(0, 300)seconds) so expirations smear evenly over time. - Fix — Stale-While-Revalidate (SWR): keep a soft logical expiry inside the cached payload earlier than the hard Redis TTL. The first reader past the soft expiry triggers one async refresh while everyone else reads the slightly stale value in 5ms.
Eviction policies when RAM fills up
When Redis reaches maxmemory, it must evict keys to accept new ones:
| Policy | Best for | Watch out for |
|---|---|---|
| LRU (Least Recently Used) | General web apps with temporal locality | One full-table scan can evict your entire hot working set |
| LFU (Least Frequently Used) | Skewed workloads with persistent hot keys | Old viral keys can linger unless frequency counters decay |
| TTL-first | Session stores & ephemeral tokens | Still needs jitter to avoid synchronized expiry cliffs |
Where this shows up in system design
- Twitter / X Home TimelinePrecomputed timeline lists live in Redis; singleflight and request coalescing protect origin fan-out stores during celebrity bursts.
- E-Commerce Product PagesCache-Aside with TTL jitter and stale-while-revalidate absorbs flash-sale traffic without melting the catalog database.
- Auth & Session StoresSub-millisecond Redis lookups validate session tokens on every API call; replicated clusters prevent a single cache node from becoming a SPOF.
- News & Trending FeedsNegative caching and Bloom filters block bots probing invalid article slugs from penetrating to origin SQL.
Check yourself: system design scenarios
interactive · pick the right caching defense for each outage
1. Flash sale homepage key expires at 12:00:00
1 hot key · periodic 60s spike · Cache-Aside
Your homepage promo banner is cached under one Redis key (`promo:home`) with a 60s TTL. Every minute on the dot, PostgreSQL CPU spikes to 100% for 3 seconds and requests time out.
Select an option to check the trade-off.
2. Scraper enumerating non-existent user profiles
non-existent keys · 50k req/s · DB saturated
An external bot is sending 50,000 req/s for random non-existent `/u/<random-id>` URLs. Redis hit rate collapsed to 5% and your primary database is saturated.
Select an option to check the trade-off.
3. Nightly warm-up job causes an outage 1 hour later
500k keys · exact 3600s TTL · 03:00 cliff
At 02:00, a batch job pre-warms 500,000 product keys in Redis, each with `EXPIRE 3600`. Every morning at 03:00, the database falls over for two minutes.
Select an option to check the trade-off.
thundering herdcaching
When a hot cache key expires and hundreds of concurrent requests simultaneously miss and hammer the origin database.
singleflightcaching
Coalescing concurrent identical cache misses inside a process so only one request queries the DB and shares the result.
false positiveprobability
Reporting that an item is present when it was never inserted; Bloom filters allow false positives but never false negatives.