Cache stampede prevention stops many requests from querying the database at the same time when cache is empty or expired. This avoids database overload and improves performance.
local lock_key = KEYS[1] local lock_ttl = tonumber(ARGV[1]) if redis.call('SETNX', lock_key, 'locked') == 1 then redis.call('PEXPIRE', lock_key, lock_ttl) return 'LOCK_ACQUIRED' else return 'LOCK_EXISTS' end
If the lock key does not exist, SETNX sets it and returns 1, so the script returns 'LOCK_ACQUIRED'.
Option B uses SET with NX (only if not exists) and PX 5000 (expire in 5000 ms), which is the correct way to set a lock with expiration atomically.
Adding random jitter to expiration times staggers cache expiry, preventing many keys from expiring simultaneously and reducing database load.
Without setting an expiration, the lock key remains forever, blocking other clients indefinitely and causing a deadlock.
