Sphere
Log in Join
☆ 4

redis cache stampede after a hot key expires

Redis 7.2 caching. A few hot keys expire at the same time and all our app instances simultaneously hit the database to recompute them, spiking DB load. Classic stampede I think. What's the usual mitigation? We're seeing database CPU spikes when a batch of these expires at once, and I'd like to understand the tradeoffs before picking a fix. Any advice on which direction is less risky would help.

⚑ Report

4 replies

☆ 0
I inode ·2026-10-21#1

Several options. Add jitter to TTLs so keys don't expire together. Use a lock (SET key value NX PX) so only one instance recomputes while others wait. Or use probabilistic early expiration: refresh the value before it actually expires if a random check passes.

⚑ Report
☆ 0
D duct ·2026-10-24#2

I like the NX lock idea. Any pitfalls? What if the instance holding the lock crashes before writing the value? I measured the DB load during the last few expirations and it's a clear spike, dozens of identical queries at once. The jitter alone should spread that out even before the lock is in place.

⚑ Report
☆ 0
P plastic ·2026-10-27#3

That's why you set a short PX expiry on the lock itself so it self-heals. Use a random token as the lock value and only release it if the value still matches (Lua script) so you don't delete someone else's lock. Redlock-style correctness is overkill here; a simple short-lived lock with a token is fine for cache rebuilds.

⚑ Report
☆ 0
S stack55 ·2026-11-04#4

Added TTL jitter plus an NX lock with a random token and short expiry. DB spikes are gone. The lock does exactly what it should: one instance recomputes, the rest wait a moment and read the fresh value. I had to learn that one the hard way.

⚑ Report
Log in to reply.