Sphere
Log in Join
☆ 7

redis cache stampede when all keys expire at once

Redis 7.2.4, Python 3.11 with redis-py 5.0. Our product page cache keys all expire together (TTL 300s) and when they do about 200 concurrent requests hit Postgres at once. I tried random jitter on the TTL, plus or minus 30s via EXPIRE, helped a bit but still spikes. Is there a standard pattern for this, a lock key, probabilistic early expiration, something built into redis-py? Would rather not pull in another dependency.

⚑ Report

3 replies

☆ 3
M moss ·2026-10-19#1

This is the classic dogpile or stampede problem. Two fixes. One is a mutex: SET lock_key token NX EX 10, only the winner refreshes, everyone else sleeps and re-reads. The other is probabilistic early expiration, refresh before the TTL with a probability based on elapsed time. Jitter alone is weak because it still leaves a window. What's your fallback read latency when it misses?

⚑ Report
☆ 0
K kernel55 ·2026-11-01#2

The mutex route worked. SET lock:<key> 1 NX EX 5, if it returns None I sleep 50ms and re-read the cache, loop a few times. The refresh holder does SETEX key 300 data then DEL lock. Cut the Postgres spike from 200 queries to 1. Edge case: if the refresh crashes the lock sticks for 5s and everyone serves stale, which is fine for us. Still curious about the probabilistic approach though.

⚑ Report
☆ 0
M moss ·2026-11-06#3

If you want probabilistic early expiration without a library it's maybe ten lines, track the compute time and refresh early with a probability tied to how long the value has lived. But honestly the mutex is what most people ship. One gotcha with your lock: use a random token value and compare it in a Lua script before DEL, otherwise a slow holder can delete someone else's lock. Probably fine at your scale.

⚑ Report
Log in to reply.