Cache Pitfalls: Stampede, Penetration, and Avalanche
Diagnose and prevent systemic cache failures including thundering herds, malicious non-existent queries, and cascading mass expirations.
Caches shield relational databases and internal microservices from crushing traffic volumes. When functioning normally, a 95% cache hit ratio reduces database query volume by a factor of twenty.
However, this heavy reliance makes systems vulnerable when the cache fails to intercept incoming traffic. A single expired key or an intentional malicious probe can cause queries to cascade directly into your persistent storage layer, driving CPU utilization to 100% and causing a complete service blackout.
Understanding the three classic cache failure modes—Stampede, Penetration, and Avalanche—is essential for designing resilient distributed systems.
01Cache Stampede (The Thundering Herd)
A Cache Stampede occurs when an intensely popular "hot key" expires, and thousands of concurrent client requests discover the cache miss at the exact same millisecond.
The Failure Mechanism
Imagine an e-commerce flash sale where one hundred thousand shoppers view the product details for product:flash-sale-phone.
- The cache key has a Time-To-Live (TTL) of sixty seconds.
- At the 60.001-second mark, the key expires.
- Over the next two hundred milliseconds, twenty thousand concurrent web requests query Redis for
product:flash-sale-phone. - Every request receives a cache miss.
- All twenty thousand worker threads immediately issue a heavy SQL join against the database to recalculate the product details.
- The database connection pool is instantly exhausted, query latency spikes from 10ms to 30,000ms, and the primary database crashes.
Engineering Mitigations
Modern architectures prevent cache stampedes using three proven strategies:
- Distributed Mutex (Locking with SETNX): When a cache miss occurs, the worker thread attempts to acquire a distributed lock in Redis (
SET lock:product:123 token NX EX 5). Only the single thread that wins the lock queries the database and repopulates the cache. The remaining thousands of threads wait for fifty milliseconds and retry the cache read, which now succeeds. - Probabilistic Early Expiration (The XFetch Algorithm): Instead of waiting for the key to officially expire, application workers probabilistically refresh the cache entry before its true TTL ends. The probability of triggering a background refresh increases as the key approaches its expiration time, scaled by the time it takes to compute the value.
- Stale-While-Revalidate: The caching layer serves slightly expired (stale) data to incoming users while asynchronously dispatching a single background task to recompute the fresh record.
Loading the rest of the lesson…