Eliminating Redis Hot-Key Bottlenecks and Cache Stampedes with Probabilistic Early Expiration
Shafikul Islam
Backend & Cloud Infrastructure Engineer · Infrastructure & Cloud Team Lead

The Two Failure Modes of High-Traffic Redis Keys
Caching solves database load until traffic concentrates heavily on a small set of keys (such as a featured flash-sale catalog or a large enterprise tenant's configuration):
- Cache Stampede (Thundering Herd): At the exact millisecond a hot key's TTL hits 0, hundreds of concurrent worker goroutines get redis.Nil simultaneously and fire expensive SQL queries at PostgreSQL.
- Single-Shard Hot-Key Saturation: Because Redis hashes each key to a single hash slot (CRC16(key) mod 16384), 80,000 reads/sec on one key all hit a single Redis node, maxing out its single event-loop core while other cluster shards sit idle.
1. Probabilistic Early Expiration (XFetch)
Instead of waiting for the hard Redis TTL to reach zero, we store the logical recomputation delta (deltaMs) and soft expiry timestamp inside the cached struct. As the key approaches expiration, a single background request probabilistically refreshes the value before the hard TTL expires:
func ShouldRecomputeEarly(nowMs, softExpiryMs, deltaMs int64, beta float64) bool {
if nowMs >= softExpiryMs {
return true
}
randomFactor := rand.Float64()
if randomFactor <= 0 {
randomFactor = 1e-9
}
earlyWindow := float64(deltaMs) * beta * (-math.Log(randomFactor))
return float64(nowMs)+earlyWindow >= float64(softExpiryMs)
}
2. Two-Tier L1 (In-Process Memory) + L2 (Redis) Caching
To protect the Redis network hop on ultra-hot read keys, each API pod keeps a tiny 64 MB in-process L1 cache with a 2-second TTL and Redis Pub/Sub invalidation. Hot configuration reads resolve in 80 nanoseconds from local RAM, reducing Redis network commands by 78%.