# Cache stampede and the thundering herd (https://layerscache.com/docs/learn/cache-stampede)

> A cache stampede, or thundering herd, is many requests missing one key at once. See the math and five fixes in TypeScript, from coalescing to TTL jitter.



A **cache stampede**, also called the **thundering herd** or the **dogpile effect**, happens when many requests miss the same cache key at the same time and each of them loads it from the database, instead of one request loading it for everyone. The usual trigger is a popular key expiring. The stampede is the load spike that follows.

**Level:** ten to a hundred · &#x2A;*You need:** [The cache-aside pattern](/docs/learn/cache-aside-pattern) and [Redis cache in Node.js](/docs/learn/redis-cache-nodejs)

"Thundering herd" first described an operating system problem: many processes sleeping on one event all wake when it fires, but only one can use it. In caching the name stuck for a different cause with the same shape. Many requests are waiting on one missing key, and all of them go to the origin.

```mermaid
sequenceDiagram
  participant A as Caller 1
  participant B as Caller 2
  participant C as Caller 3
  participant D as Database
  alt Without coalescing
    A->>D: load product 42
    B->>D: load product 42
    C->>D: load product 42
    D-->>A: value
    D-->>B: value
    D-->>C: value
  else With coalescing
    A->>D: load product 42
    B->>A: wait for the same load
    C->>A: wait for the same load
    D-->>A: value
    A-->>B: same value
    A-->>C: same value
  end
```

## How big can a cache stampede get? [#how-big-can-a-cache-stampede-get]

The number of loads running at once is the request rate for the key times the load time. Take a key read 2,000 times a second with a 100 ms query. When it expires, every request that arrives before the first load finishes also misses.

2,000 reads per second × 0.1 s ≈ 200 concurrent loads, where steady state was one load every TTL.

The spike feeds itself. Those 200 queries take connections from a pool of a few dozen, so unrelated requests queue behind them. The database slows down, the load time grows, and more requests pile in. At 500 ms per load, the same key puts 1,000 queries in flight.

## What are cache penetration, breakdown and avalanche? [#what-are-cache-penetration-breakdown-and-avalanche]

Operations teams use several names for neighbouring failures. They are easy to mix up.

| Term                               | What happens                                    | Main fix                           |
| ---------------------------------- | ----------------------------------------------- | ---------------------------------- |
| Stampede, thundering herd, dogpile | Many requests miss one key together             | Coalescing and a lease             |
| Cache breakdown                    | A single hot key expires and the herd follows   | The same fixes, plus early refresh |
| Cache avalanche                    | Many keys expire together, or the cache is down | TTL jitter, stale serving          |
| Cache penetration                  | Requests for keys that do not exist always miss | Negative caching                   |

**Negative caching** stores the "not found" answer for a short time, such as 10 seconds, so a missing ID does not reach the database on every request. Without it, someone who requests random IDs can bypass your cache completely.

## Fix 1: coalesce requests inside one process [#fix-1-coalesce-requests-inside-one-process]

**Request coalescing**, called **singleflight** in Go, means concurrent callers for one key share a single in-flight load. Store the promise, and give it to everyone who asks before it settles.

```ts title="single-flight.ts"
const inflight = new Map<string, Promise<unknown>>()

export function singleFlight<V>(key: string, load: () => Promise<V>): Promise<V> {
  const running = inflight.get(key) as Promise<V> | undefined
  if (running) return running

  const promise = load().finally(() => inflight.delete(key))
  inflight.set(key, promise)
  return promise
}
```

```ts title="users.ts"
import { Redis } from 'ioredis'
import { singleFlight } from './single-flight.ts'
import { db, type User } from './db.ts'

const redis = new Redis(process.env.REDIS_URL ?? 'redis://localhost:6379')

export async function getUser(id: string): Promise<User | null> {
  const key = `user:${id}`
  const cached = await redis.get(key)
  if (cached !== null) return JSON.parse(cached) as User

  return singleFlight(key, async () => {
    const user = await db.users.find(id)
    if (user) await redis.set(key, JSON.stringify(user), 'EX', 300)
    return user
  })
}
```

This is the cheapest fix and it removes most of the herd. Its limit is the process: six servers still start six loads for the same key.

## Fix 2: take a distributed lock or lease in Redis [#fix-2-take-a-distributed-lock-or-lease-in-redis]

To get one load across the fleet, the first server to miss writes a lock key in Redis with `SET key token NX PX 5000`. `NX` means "only if the key does not exist" and `PX 5000` expires it after 5 seconds. The other servers see the lock is taken and wait for the value to appear.

```ts title="lease.ts"
import { randomUUID } from 'node:crypto'
import { setTimeout as sleep } from 'node:timers/promises'
import { Redis } from 'ioredis'

const redis = new Redis(process.env.REDIS_URL ?? 'redis://localhost:6379')
const RELEASE = `
  if redis.call('get', KEYS[1]) == ARGV[1] then
    return redis.call('del', KEYS[1])
  end
  return 0`

export async function loadOnce<V>(key: string, load: () => Promise<V>): Promise<V> {
  for (let attempt = 0; attempt < 100; attempt++) {
    const cached = await redis.get(key)
    if (cached !== null) return JSON.parse(cached) as V

    const token = randomUUID()
    const won = await redis.set(`lock:${key}`, token, 'PX', 5000, 'NX')
    if (won === 'OK') {
      try {
        const value = await load()
        await redis.set(key, JSON.stringify(value), 'EX', 300)
        return value
      } finally {
        await redis.eval(RELEASE, 1, `lock:${key}`, token) // only delete our own lock
      }
    }
    await sleep(50) // someone else is loading, check again soon
  }
  return load() // gave up waiting, load directly
}
```

This is a **lease**: the lock expires on its own, so a crashed server cannot block the key forever. It is not **exactly-once**. If the load takes longer than 5 seconds, the lease expires and a second server starts loading. A failover of Redis can also drop the lock. For a cache fill that costs one extra query, which is fine. It is not fine for work that must never run twice. Redlock, the algorithm that spreads a lock over several Redis servers, tries to make locks stronger, but you do not need it here: a load that runs twice should be safe to repeat, so a single-instance lease is enough.

## Fix 3: refresh before the key expires [#fix-3-refresh-before-the-key-expires]

If a hot key never expires in front of a user, there is no herd. **Refresh-ahead** reloads a key in the background when part of its TTL is gone, for example after 80%. The simple version is a fixed threshold.

**Probabilistic early expiration**, or **XFetch**, spreads that choice randomly. Vattani, Chierichetti and Lowenstein describe it in "Optimal Probabilistic Cache Stampede Prevention" ([VLDB 2015](https://www.vldb.org/pvldb/vol8/p886-vattani.pdf)). Each reader rolls a weighted die. The closer the key is to expiry, and the longer it took to compute, the more likely this reader recomputes it early.

```ts title="xfetch.ts"
// deltaMs is how long the last load took. beta = 1 is the paper's default.
export function shouldRefreshEarly(expiresAt: number, deltaMs: number, beta = 1): boolean {
  const gap = -deltaMs * beta * Math.log(Math.random()) // always positive
  return Date.now() + gap >= expiresAt
}
```

Store `expiresAt` and `deltaMs` next to the value. On a hit, call `shouldRefreshEarly`. If it returns true, start one reload and still return the current value.

## Fix 4: serve stale while you revalidate [#fix-4-serve-stale-while-you-revalidate]

**Stale-while-revalidate** returns the expired value at once and refreshes it in the background. Readers never wait on the origin. The name comes from an HTTP `Cache-Control` extension (RFC 5861), and the idea applies to any cache.

```ts title="swr.ts"
import { singleFlight } from './single-flight.ts'
import { db, type User } from './db.ts'

type Entry = { value: User; freshUntil: number; staleUntil: number }
const entries = new Map<string, Entry>()

function reload(id: string): Promise<User> {
  return singleFlight(`user:${id}`, async () => {
    const value = await db.users.find(id)
    const now = Date.now()
    entries.set(`user:${id}`, { value, freshUntil: now + 60_000, staleUntil: now + 300_000 })
    return value
  })
}

export async function getUser(id: string): Promise<User> {
  const entry = entries.get(`user:${id}`)
  const now = Date.now()
  if (entry && now < entry.freshUntil) return entry.value
  if (entry && now < entry.staleUntil) {
    reload(id).catch(() => {}) // one background reload, errors ignored
    return entry.value
  }
  return reload(id)
}
```

The cost is that some readers get data up to one stale window old. Pick a window your product can live with.

## Fix 5: add jitter to TTLs [#fix-5-add-jitter-to-ttls]

A deploy or a batch job often writes many keys at the same moment, all with the same TTL. They expire together, and the **cache avalanche** begins. **TTL jitter** gives each key a slightly different lifetime.

```ts title="jitter.ts"
export function withJitter(ttlSeconds: number, fraction = 0.1): number {
  const factor = 1 + (Math.random() * 2 - 1) * fraction // 0.9 to 1.1
  return Math.round(ttlSeconds * factor)
}

// redis.set(key, value, 'EX', withJitter(300))
```

## Where the hand-written version breaks [#where-the-hand-written-version-breaks]

Each fix above solves one case. Together they need a lease that is renewed while a slow load runs, a way to wake waiters instead of polling, errors that reach every waiter, a timeout, and a fallback when Redis itself is down. That is a library's worth of code with several race conditions, and you have to test all of them under load.

## The same idea with getOrSet [#the-same-idea-with-getorset]

In lazy-layers-cache the first two fixes are on by default. Callers in one process share a single loader call, and with Redis as L2 a per-key lease lets one server load while the others wait. You write the same call whether you run one server or twenty.

```ts title="products.ts"
const product = await cache.getOrSet(`product:${id}`, () => db.products.find(id), {
  earlyRefresh: 0.8, // reload in the background after 80% of the TTL
  staleWhileRevalidate: true, // serve an expired value while one reload runs
  ttlJitter: 0.1, // scale each TTL by 0.9 to 1.1
  distributedLock: { ttlMs: 5_000 }, // tune the Redis lease
})
```

Fixes 3, 4 and 5 are options you turn on per call. The lease is renewed while the load runs, and missing values are remembered for 10 seconds by default, which covers cache penetration.

In a recorded run, 1,200 concurrent callers on 6 servers asked for 20 cold keys, and the origin ran 20 loads, one per key. See [prevent stampedes](/docs/guides/stampede-protection) for the benchmark and the lease settings, [batches and freshness](/docs/guides/batches-and-freshness) for the three freshness options, and [failure handling](/docs/guides/failure-handling) for what a waiter gets when the one load fails. The lease is stampede protection, not an exactly-once guarantee, so keep loaders read-only.

Next lesson: [Distributed cache system design](/docs/learn/distributed-cache-system-design).

## Further reading [#further-reading]

* [Vattani, Chierichetti and Lowenstein, Optimal Probabilistic Cache Stampede Prevention, VLDB 2015](https://www.vldb.org/pvldb/vol8/p886-vattani.pdf): the paper behind probabilistic early expiration.
* [Cloudflare, Sometimes I cache](https://blog.cloudflare.com/sometimes-i-cache/): builds the cache lock and the lock-free probabilistic version step by step.
* [Nishtala et al., Scaling Memcache at Facebook, NSDI 2013](https://www.usenix.org/conference/nsdi13/technical-sessions/presentation/nishtala): leases limit herds, with a measured peak of 17K queries per second falling to 1.3K.
* [Go singleflight](https://pkg.go.dev/golang.org/x/sync/singleflight): a duplicate function call suppression mechanism, the Go name for request coalescing.
* [RFC 5861, stale-while-revalidate and stale-if-error](https://www.rfc-editor.org/rfc/rfc5861): the HTTP extensions that let a cache serve a stale response.


## Questions

### What is a cache stampede?

A cache stampede is many requests missing the same cache key at the same moment and all running the same expensive load against the database. It usually starts when a popular key expires. The extra load slows the database, which keeps the key missing for longer and lets more requests pile in.

### What is the thundering herd problem?

The thundering herd problem is when one event wakes many waiting workers and they all contend for the same resource. The term comes from operating systems, where many processes wake for one event. In caching it means many requests missing one key and all querying the origin. The cache version is also called a stampede or dogpile.

### How do you prevent a cache stampede?

Let one caller load the value while the others wait for it. Share one in-flight promise per key in each process, and take a Redis lease so only one server loads. Then reduce expiry spikes with early refresh, stale-while-revalidate and TTL jitter, so a hot key rarely expires in front of a user.

### What is the difference between a cache stampede and a cache avalanche?

A stampede is many requests for one key. A cache avalanche is many different keys expiring at about the same time, or the whole cache going down, so a wave of misses hits the database together. TTL jitter helps against the first kind of avalanche, and request coalescing handles each hot key.

### What is request coalescing or singleflight?

Request coalescing, called singleflight in Go, makes concurrent callers for the same key share one in-flight load instead of each starting their own. The first caller starts the work and stores its promise, and the rest receive that promise. It works inside one process, so a fleet still needs a lease.

### Is a Redis lock enough to stop a stampede?

It stops most of one, but a lease is not exactly-once. If the loader outlives the lease, or Redis fails over, two servers can load at once. For cache fills that costs one extra query, which is acceptable. Do not rely on the same lock for work that must never run twice.