Redis & Caching (50 Qs)•Part 2: Core Architecture & Implementation (Mid-Level)
What is Cache Penetration, Cache Breakdown, and Cache Avalanche?
senior LevelMost AskedCode ExampleSystem Design
In Simple Words: The 3 classic high-scale caching failure scenarios:
- Cache Penetration: Queries request keys that do not exist in both cache and DB (e.g. malicious requests for
id = -999). Every request bypasses the cache and hammers the database.- Fix: Cache null objects with short TTL (
SET id:-999 null EX 60), or use a Bloom Filter.
- Fix: Cache null objects with short TTL (
- Cache Breakdown (Thundering Herd): A single extremely hot key (e.g. celebrity tweet) expires, causing thousands of concurrent requests to hit the database simultaneously to rebuild the cache.
- Fix: Mutex distributed lock on cache miss, or logical expiration (background refresh).
- Cache Avalanche: Thousands of keys are configured with the exact same TTL and expire at the same second, overwhelming the database.
- Fix: Add random jitter to TTLs (
TTL = 3600 + Math.random() * 300).
- Fix: Add random jitter to TTLs (
text
Caching Catastrophes:
1. Penetration: Non-existent key ──► [Miss] ──► [Miss in DB!] ──► (DB Overload)
2. Breakdown: Hot key expires ──► 10,000 requests hit DB concurrently!
3. Avalanche: 100,000 keys expire at 00:00:00 ──► Entire DB crashes!