Redis › Caching Patterns
How would you prevent a cache stampede, where many requests simultaneously try to regenerate the same expired cache entry at once?
AdvancedAnswer
You can use a distributed lock so only one request regenerates the expired value while others wait briefly or serve a slightly stale version, or use a technique like probabilistic early expiration, where a small percentage of requests refresh the cache slightly before it actually expires, spreading out the regeneration load over time instead of all at once.
if redis.set(f'lock:{key}', 1, nx=True, ex=10):
value = database.get_data()
redis.set(key, value, ex=3600)
redis.delete(f'lock:{key}')
else:
-- wait briefly and retry, or serve stale data
passReal-world example A popular news website prevents a cache stampede on its most viewed article by using a lock so only one request regenerates the cached article content when it expires, while other simultaneous visitors briefly see the slightly older cached version.