0
0
Redisquery~5 mins

Cache stampede prevention in Redis

Choose your learning style9 modes available
Introduction

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.

When many users request the same data that is stored in cache and the cache expires.
When you want to avoid slowing down your website because of many database requests at the same time.
When you want to keep your server healthy by reducing sudden heavy loads.
When you want to improve user experience by keeping responses fast even during high traffic.
When you use Redis as a cache and want to manage cache expiration smartly.
Syntax
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.

Examples
Try to set a lock key that expires in 5 seconds only if it does not exist.
Redis
SET lock_key 1 NX PX 5000
Get the cached data if it exists.
Redis
GET cache_key
Delete the lock key to release the lock after cache is refreshed.
Redis
DEL lock_key
Sample Program

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.

Redis
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
OutputSuccess
Important Notes

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.

Summary

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.