How do you handle cache invalidation, cache stampedes and other caching pitfalls?
HardConceptCaching
Answer
Invalidation keeps cached data acceptably fresh, while stampede protection stops many requests from hitting the database at once when a popular entry expires. Both rely on careful write ordering, expiry and request coordination.
- Invalidation: update the database first, then delete (rather than update) the cache entry, with a TTL as a safety net. Deleting reduces the chance of concurrent writers leaving an older value cached.
- Stampede (thundering herd): let one request rebuild the entry using a lock or request coalescing while others wait or receive the stale value; refreshing hot keys shortly before expiry also helps.
- Avalanche: add random jitter to TTLs so that many keys do not expire together.
- Penetration: for keys that do not exist, cache the negative result briefly or check a Bloom filter first.