Cache stampede prevention helps stop many users from asking the database for the same data at once when the cache expires. This keeps the system fast and avoids overload.
Cache stampede prevention in Redis
SET key value NX PX milliseconds GET key DEL key
SET key value NX PX milliseconds sets a key only if it does not exist and sets expiration in milliseconds.
This helps create a lock to prevent multiple processes from regenerating cache at the same time.
SET lock_key 1 NX PX 5000
GET cache_key
DEL lock_key
This example shows how to prevent cache stampede by using a lock key. Only one process sets the lock and regenerates the cache. Others wait and retry.
GET user:123 -- If cache miss -- SET lock:user:123 1 NX PX 3000 -- If SET returns OK, regenerate cache and SET user:123 with new data DEL lock:user:123 -- Else wait and retry GET user:123
Always set a short expiration on the lock key to avoid deadlocks.
Other processes should wait and retry to get the cache instead of regenerating it.
This method reduces load on your database during high traffic.
Cache stampede prevention stops many requests from hitting the database at once.
Use Redis SET with NX and PX options to create a lock.
Only one process refreshes the cache while others wait.