Cache Stampede, Penetration & Avalanche
Stop thundering herds, fake-key floods, and synchronized TTL expirations from crashing your DB.
In plain words
If 10,000 people refresh a page the exact millisecond a cache item expires, all 10,000 rush the database together (Stampede). A single-flight lock lets only ONE person fetch while the rest wait briefly.
Think of it like…
100 customers asking the waiter if the soup is ready - instead of 100 people walking into the kitchen, one waiter checks and tells everyone.
Theory & how it works
Practical fixes in 3 lines of thinking
1. Stampede (Thundering Herd): Use a mutex/single-flight lock on cache miss so only 1 request hits the DB while others wait or get slightly stale data.
2. Penetration (Attackers querying `id=-999`): Cache null sentinel values for 30–60s or put a Bloom filter in front.
3. Avalanche (100k keys all set at boot with `TTL=3600` expire together): Always add random jitter (3600 + rand(0, 300)) to every TTL.
Key points & practical guide
Summary checklist
- Add random jitter to TTLs to prevent mass expiry avalanches
- Use single-flight / request coalescing for hot keys
- Cache negative/empty results briefly or use Bloom filters against penetration
When to use it
- Any high-traffic service backed by Redis/Memcached
Watch out for
- Hardcoding identical TTLs during batch cache warming