Measuring Redis cache stampede, penetration, and avalanche fixes
Reproducing Redis cache stampede, penetration, and avalanche locally and measuring DB hits with mutex, PER, null caching, Bloom filters, and TTL jitter.
Even with a Redis cache in place, sudden database spikes usually happen at the exact moment the cache is empty. I reproduced cache stampede, penetration, and avalanche locally and counted actual database queries before and after each defense strategy.
Tested with Spring Boot 4.0.2, Kotlin 2.2.21, Java 21, Spring Data Redis 4.0.2 (Lettuce 6.8.2), Redis 8.4.0, PostgreSQL 17.6, and HikariCP 7.0.2 (pool size 10) on a 12-core, 32GB RAM workstation (Windows + Docker Desktop/WSL2). Each scenario was run three times.
Background
Our main feed displays a “popular items” list computed by an aggregation query and cached in Redis. Under normal traffic, the cache hit rate stayed high and the database was quiet. During peak hours, though, HikariCP connection-wait warnings spiked briefly every time the cache TTL expired.
Breaking those spikes down, the empty-cache failure modes fell into three familiar categories:
| Failure mode | Why the cache misses | Primary defenses |
|---|---|---|
| Stampede | One hot key expires under concurrent traffic | Mutex lock, PER |
| Penetration | Requests look up keys that don’t exist in the DB either | Null caching, Bloom filter |
| Avalanche | Many keys expire at the same timestamp | TTL jitter |
To make the numbers reproducible, I added pg_sleep(0.1) to the database query to fix recomputation cost at 100ms, and tracked actual database hits with an AtomicInteger inside the loader method.
Stampede: mutex lock vs. PER
First, I simulated 200 concurrent requests hitting a hot key right after it expired:
| Strategy | DB queries (3 runs) | p50 | p99 |
|---|---|---|---|
| Naive cache-aside | 200 / 200 / 200 | 1,079ms | 2,039ms |
| Redis mutex | 1 / 1 / 1 | 125ms | 138ms |
With naive cache-aside, all 200 requests went straight to PostgreSQL. Because the HikariCP pool only held 10 connections, those 100ms queries serialized into 20 batches, pushing p99 past 2 seconds. With a Redis mutex (SET NX PX), only the single lock winner hit the database while the other 199 polled Redis every 20ms. The Lua unlock script that checks the lock token before deleting is the same pattern I covered in my post on distributed locks and transaction boundaries.
A mutex protects the database, but waiting threads still stall for the full recomputation duration. Next, I ran a sustained load test—32 threads querying continuously for 12 seconds against a 2-second TTL—to compare the mutex against PER (Probabilistic Early Recomputation):
| Strategy | DB queries (3 runs) | Requests > 50ms (3 runs) | Max latency |
|---|---|---|---|
| Naive cache-aside | 160 / 160 / 160 | 160 / 160 / 160 | ~410ms |
| Redis mutex | 5 / 5 / 5 | 160 / 160 / 160 | ~130ms |
| PER (β = 1) | 18 / 18 / 21 | 18 / 18 / 21 | ~105ms |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
"type": "bar",
"data": {
"labels": ["200-request burst", "12s sustained load"],
"datasets": [
{ "label": "Naive cache-aside", "data": [200, 160], "backgroundColor": "#f7768e" },
{ "label": "Redis mutex", "data": [1, 5], "backgroundColor": "#7aa2f7" },
{ "label": "PER", "data": [null, 18], "backgroundColor": "#9ece6a" }
]
},
"options": {
"plugins": { "title": { "display": true, "text": "DB queries during cache stampede (median of 3 runs)" } }
}
}
Naive cache-aside triggered 5 expirations × 32 threads = 160 database queries. The mutex cut database hits to 5 (one per expiration), yet all 32 threads still waited on each expiration—so the slow-request count matched naive cache-aside. PER sent more queries to the database (18–21), but only the single request doing the early refresh experienced the 100ms latency.
Under the hood, PER uses the XFetch algorithm. Along with the cached value, you store its recomputation time (delta) and logical expiration timestamp. On every read, if now - delta * beta * ln(rand) >= expiry, that caller recomputes the value before it actually expires. Because ln(rand) is negative, the probability of an early refresh rises as expiration approaches or as delta grows. Keeping the physical Redis TTL longer than the logical expiry lets other callers keep reading the slightly older value while the refresh runs.
Penetration and avalanche
To reproduce cache penetration, 16 threads queried 100 nonexistent IDs 10 times each. Without protection, all 1,000 requests hit PostgreSQL. Caching missing results under a __NULL__ sentinel for 30 seconds dropped DB hits to 112 / 115 / 119. The extra 12–19 queries above 100 happened because concurrent threads hit the first miss for the same missing ID at the same time—a mini stampede inside penetration.
Null caching doesn’t stop random ID scans or crawlers that never repeat the same missing ID, so I tested a Bloom filter alongside it. Redis 8 bundles Bloom filters out of the box, letting you call BF.RESERVE without installing extra modules. I inserted 100,000 existing IDs and queried 100,000 nonexistent IDs:
| Target false-positive rate | Memory | Actual false positives | Existing IDs found |
|---|---|---|---|
| 1% | 137,976 B | 522 (0.52%) | 100,000 / 100,000 |
| 0.1% | 197,888 B | 55 (0.055%) | 100,000 / 100,000 |
When a Bloom filter returns false, the key is guaranteed not to exist; a true result may be a false positive. Zero existing IDs were missed.
To reproduce cache avalanche, I preloaded 1,000 keys with an identical 5-second TTL and had 16 threads read random keys for 12 seconds. Peak database hits per 250ms bucket reached 425 / 470 / 492 with a fixed TTL. Adding ±20% TTL jitter lowered the peak to 153 / 135 / 141. Total database queries stayed roughly equal (~1,020 in both runs)—jitter doesn’t reduce total work, it flattens the spike.
1
2
3
4
5
6
7
8
9
10
11
12
13
{
"type": "line",
"data": {
"labels": ["3.0s", "3.25s", "3.5s", "3.75s", "4.0s", "4.25s", "4.5s", "4.75s", "5.0s", "5.25s", "5.5s", "5.75s", "6.0s", "6.25s"],
"datasets": [
{ "label": "Fixed 5s TTL", "data": [0, 0, 0, 0, 0, 142, 369, 425, 87, 0, 0, 0, 0, 0], "borderColor": "#f7768e" },
{ "label": "5s TTL with ±20% jitter", "data": [0, 0, 26, 70, 136, 153, 110, 121, 132, 138, 92, 46, 1, 0], "borderColor": "#7aa2f7" }
]
},
"options": {
"plugins": { "title": { "display": true, "text": "DB queries per 250ms bucket (Run 1)" } }
}
}
Even with a fixed TTL, expirations spread across 4.25s–5.0s simply because preloading 1,000 keys sequentially took that long.
Implementation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// build.gradle.kts
plugins {
kotlin("jvm") version "2.2.21"
kotlin("plugin.spring") version "2.2.21"
id("org.springframework.boot") version "4.0.2"
id("io.spring.dependency-management") version "1.1.7"
}
dependencies {
implementation("org.springframework.boot:spring-boot-starter-data-redis")
implementation("org.springframework.boot:spring-boot-starter-jdbc")
implementation("org.jetbrains.kotlin:kotlin-reflect")
runtimeOnly("org.postgresql:postgresql")
}
1
2
3
4
5
6
7
8
9
10
11
12
# src/main/resources/application.yml
spring:
data:
redis:
host: localhost
port: 6379
datasource:
url: jdbc:postgresql://localhost:5432/app
username: app
password: ${DB_PASSWORD}
hikari:
maximum-pool-size: 10
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// src/main/kotlin/com/example/cache/StampedeCache.kt
package com.example.cache
import org.springframework.data.redis.core.StringRedisTemplate
import org.springframework.data.redis.core.script.RedisScript
import org.springframework.stereotype.Component
import java.time.Duration
import java.util.UUID
import java.util.concurrent.ThreadLocalRandom
import kotlin.math.ln
fun interface Loader { fun load(id: Long): String? }
@Component
class StampedeCache(private val redis: StringRedisTemplate) {
private val unlockScript = RedisScript.of(
"if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) end return 0",
Long::class.java,
)
// Mutex: only one thread hits the DB on miss; others wait briefly and re-read Redis
fun mutex(id: Long, ttl: Duration, loader: Loader): String? {
val key = "item:$id"
redis.opsForValue().get(key)?.let { return it }
val lockKey = "lock:$key"
val token = UUID.randomUUID().toString()
repeat(100) {
if (redis.opsForValue().setIfAbsent(lockKey, token, Duration.ofSeconds(3)) == true) {
try {
redis.opsForValue().get(key)?.let { return it } // double-check
val v = loader.load(id) ?: return null
redis.opsForValue().set(key, v, ttl)
return v
} finally {
redis.execute(unlockScript, listOf(lockKey), token)
}
}
Thread.sleep(20)
redis.opsForValue().get(key)?.let { return it }
}
return loader.load(id) // fallback once retry budget is exhausted
}
// PER (XFetch): stores "value|recomputeMs|logicalExpiryEpochMs"
fun per(id: Long, ttl: Duration, loader: Loader, beta: Double = 1.0): String? {
val key = "item:per:$id"
redis.opsForValue().get(key)?.let { raw ->
val (value, delta, expiry) = raw.split('|').let { Triple(it[0], it[1].toLong(), it[2].toLong()) }
val rnd = ThreadLocalRandom.current().nextDouble().coerceAtLeast(1e-12)
if (System.currentTimeMillis() - delta * beta * ln(rnd) < expiry) return value
}
val start = System.currentTimeMillis()
val v = loader.load(id) ?: return null
val delta = System.currentTimeMillis() - start
val expiry = System.currentTimeMillis() + ttl.toMillis()
redis.opsForValue().set(key, "$v|$delta|$expiry", ttl.plusSeconds(10)) // keep physical TTL longer
return v
}
// Null caching: cache missing IDs briefly with a sentinel marker
fun withNullCaching(id: Long, ttl: Duration, loader: Loader, nullTtl: Duration = Duration.ofSeconds(30)): String? {
val key = "item:$id"
when (val cached = redis.opsForValue().get(key)) {
NULL_MARK -> return null
null -> Unit
else -> return cached
}
val v = loader.load(id)
redis.opsForValue().set(key, v ?: NULL_MARK, if (v == null) nullTtl else jittered(ttl))
return v
}
companion object {
const val NULL_MARK = "__NULL__"
// TTL jitter: randomize within ±ratio of the base TTL
fun jittered(base: Duration, ratio: Double = 0.2): Duration {
val spread = (base.toMillis() * ratio).toLong()
return base.plusMillis(ThreadLocalRandom.current().nextLong(-spread, spread + 1))
}
}
}
Choosing a strategy—and when not to use one
| Scenario | Recommended defense |
|---|---|
| Expensive recomputation where DB protection comes first | Mutex (accept caller wait latency) |
| Predictable recomputation cost and strict tail-latency targets | PER |
| Repeated lookups for the same missing IDs | Null caching (short TTL) |
| Random ID scans or scraper traffic | Bloom filter + null caching |
| Keys preloaded in bulk by a batch job | TTL jitter |
Each technique has clear boundaries where it hurts more than it helps. If traffic is low enough that concurrent misses at expiration rarely happen, mutex locks and PER add moving parts for no real gain. PER relies on a reasonably steady delta; if query time fluctuates wildly, early recomputation triggers either too often or too late. Null caching can hide newly created records until the sentinel expires, so you must evict the key on insert. Standard Bloom filters don’t support deletion, meaning domains with frequent deletes accumulate false positives unless you periodically rebuild the filter.
Production pitfalls and checklist
If the mutex lock TTL (
3sin this example) is shorter than actual recomputation time, the lock expires mid-query and a second caller hits the database anyway. Set it too long, and a crashed lock holder stalls waiting threads until expiration. Size the lock TTL comfortably above your recomputation p99, and track fallback invocations after the wait budget expires using custom business metrics so fallbacks don’t turn into a second stampede.
- Have you measured the recomputation cost and peak concurrency of your hot keys?
- Are hot keys protected by either a mutex lock or PER?
- Does null caching use a short TTL and evict the key when a record is created?
- Do batch-loaded or warmed-up keys include TTL jitter?
- Can you view cache miss rate and DB query counts alongside key expiration spikes on the same dashboard?