LazyLayersv9.0.0
Guides

Prevent stampedes

Collapse concurrent callers to one loader call inside a process, and to one across the cluster with a Redis lease.

To prevent a cache stampede in Node.js, read through getOrSet(key, loader). Concurrent callers for the same missing key share one loader call in the process, and with Redis L2 a per-key lease lets one instance load the key while the others wait to be woken. Both are on by default. In the herd benchmark in BENCHMARKS.md, 10,000 concurrent callers on one cold key with a 20 ms loader ran it once, and all had the value within 30.8 ms.

A cache is a load absorber, and a stampede is the moment it stops absorbing. This page covers the concept, the mechanism that already handles it, and the automatic Redis coordination that applies when one process is not the whole picture.

The thundering herd

The thundering herd is a general system design failure, not a caching quirk. A single event wakes many waiters at once, all of them do the same work, and the resource they contend for collapses under a load spike it never sees during normal operation.

In a cache it looks like this. A popular key expires, a deploy starts servers with cold L1 caches, or a new key suddenly becomes hot. The next second brings 10,000 requests for it, every one of them misses, and every one of them calls your database with the identical query. Your steady state was one query per key per TTL. Your worst second is 10,000 queries, and it arrives precisely when the key is hottest.

The damage is not linear. Those 10,000 queries take connections from a bounded pool, so unrelated requests queue behind them, and the slower the origin gets the longer each caller holds its slot. That is a feedback loop, which is why a stampede tends to show up as a full outage rather than a latency bump.

Expiry is only the most common trigger. A cold deploy, a flushed store, or a newly popular key produce the same shape: many concurrent callers, one missing value.

In-flight dedupe

This is on by default. You are not switching it on, and you should not switch it off.

The first caller for a key stores its promise. Every caller that arrives while that promise is unsettled receives the same promise instead of starting a second load. When it settles, all of them resolve from one result and the entry is removed.

src/products/repository.js
import { cache } from '../cache/index.js'
import { db } from '../db.js'

export async function getProduct(id) {
  return cache.getOrSet(`product:${id}`, async ({ signal } = {}) => {
    // Runs once per cold key, no matter how many callers are waiting.
    return db.products.findById(id, { signal })
  })
}

Nothing in that code asks for dedupe. The collapse is a property of getOrSet.

What the benchmark measured

benchmarks/herd.mjs fires 10,000 concurrent getOrSet calls at one cold key, with a loader that sleeps 25 ms to stand in for a database round trip, and counts how many times the loader actually runs.

RunCallersLoader callsIn-flight reuses
Dedupe on, the default10,00019,999
Dedupe off10,00010,0000

Both runs assert that every caller received the correct value, so the collapse cannot come from dropping requests. Reproduce it yourself:

npm run build
NODE_ENV=production node benchmarks/herd.mjs

The second row is there as a control, not as a configuration you should copy. It exists so the first row means something.

Tuning the dedupe window

Tuning here means numbers. The two that matter are how long an in-flight entry stays reusable, and how many distinct keys can be tracked at once.

src/cache/index.js
export const cache = new LazyLayersCache({
  ttlMs: 5 * 60 * 1000,

  inflight: {
    // The dedupe lifetime adapts to the wait and loader budgets automatically.
    // How many distinct keys can be tracked at once. Size it to your concurrent
    // cold key count, not to your total keyspace.
    maxEntries: 10_000,
  },
})

inflight.ttlMs is derived automatically from the loader hard timeout, the distributed wait budget when locking is active, and a 50 ms margin, with a 5,000 ms minimum. Default settings produce 10,050 ms without locking and 20,100 ms with Redis locking. An explicit value still overrides this. Setting it below the time a healthy load needs can allow duplicate work. Settled promises are removed immediately.

maxEntries caps the tracking map. Past the cap, a new load still runs and still returns the right value, it simply does not register for reuse, and it emits inflight:bypass with reason maxEntries. A steady stream of those means your cold key concurrency outgrew the cap.

When one process's dedupe is not enough

In-flight dedupe is per process. Four servers each collapse their own callers to one loader call, which is four queries rather than one. Usually that is fine. It stops being fine when the loader is genuinely expensive, when it hits a rate limited third party, or when you have twenty servers rather than four.

With Redis L2, getOrSet automatically coordinates concurrent misses across instances, including misses after cache expiry. No lock configuration is required. If only L1 expires, a live L2 value refills it without invoking the loader.

src/cache/index.js
import { LazyLayersCache, RedisStore } from 'lazy-layers-cache'
import { redis } from './redis.js'
import { bus } from './bus.js'

export const cache = new LazyLayersCache({
  l2: new RedisStore(redis, { prefix: 'app:cache:' }),
  eventBus: bus,
  source: process.env.INSTANCE_ID ?? `srv-${process.pid}`,

  // Locking and renewal are automatic with Redis L2.
})

What happens on a cold or expired key

One server acquires the lock

With RedisStore's v2 key layout, the read that finds the key empty takes its lease in the same Lua script, so no other server can fill the key in between and nothing needs rechecking. Other stores acquire separately and recheck the cache before loading. Redis renews the lease while the load and cache write are in progress. The value is published and the lease released in one script when the load finishes.

The others wait to be woken

With an event bus, a waiter is woken the moment the owner is done: by the set broadcast that carries the value, or, when there is none (a tagged value, broadcastSet: false, a failed load), by a lease announcement. It then reads the key once and returns the shared value. Polling is only the reconciler, every reconcileMs (200 ms by default), for a notification that was lost.

Without a bus, waiters poll every pollMs. With RedisStore's v2 layout, each poll is one Redis round trip that reads the key and, if the owner gave up without storing it, takes the lease in the same script, so one waiter takes over at once.

In-flight dedupe lets callers within an instance share this wait. Callers on the same instance as the owner are woken directly.

Waiting has a deadline

If nothing appears within the wait budget, the cache returns an eligible stale value when fail-safe is enabled. Otherwise it throws DistributedLockTimeoutError. A contention timeout does not start an unlocked loader by default.

The default wait budget is derived from the longer of the lock TTL and the loader hard timeout, plus one poll interval. With default settings that is 10,050 ms. This allows a healthy slow loader to finish while keeping waiting bounded. Explicit waitTimeoutMs settings still take precedence.

Lock defaults

OptionDefaultWhat it controls
ttlMs10000Lease lifetime, renewed automatically by RedisStore while work is active
waitTimeoutMsDerived, initially 10050Maximum contention wait before stale fallback or an error
pollMs50How often a waiter rechecks the cache and retries acquisition, without an event bus
reconcileMs4 × pollMsWith an event bus, how often a waiter rechecks in case its notification was lost
onTimeoutthrowUse eligible stale data or throw. load explicitly restores the unlocked fallback

RedisStore renews with a token-checked Lua operation at roughly one third of the lease lifetime. A failed renewal or expired local lease aborts the loader signal and rejects with DistributedLockLostError, or returns eligible stale data. Results that arrive after detected ownership loss are discarded. Custom stores can implement renewLock(key, token, ttlMs) to support renewal. Without it, their loads must finish within the lease.

This is cache stampede protection, not an exactly-once execution guarantee. Redis failure before contention is observed still uses the existing fail-open origin path. Redis failover, process pauses and loaders that ignore their abort signal can allow overlapping origin work. Pass the supplied signal to clients that support cancellation. The lease and wait budget do not replace Redis client command timeouts.

A cold load with RedisStore costs two Redis round trips with or without the lock: one to read the key (and take its lease), one to publish the value (and release it). Stores without the combined operations take up to four with the lock.

Announcing costs nothing when nobody waits. A reader that finds the lease held leaves a mark beside it, in the same Redis script; the script that publishes and releases clears the mark and tells the owner whether there was one. The owner announces only then, and only when its set broadcast did not already wake everyone. An announcement is a del event with no keys and a leases field, which releases before 8.0 accept and ignore.

Without an event bus, losers pay up to pollMs of added latency. With one, they are woken within one bus hop of the owner finishing.

Keep one tenant from taking every origin slot

The origin gate caps how many loaders reach your database at once: 32 running and 1,024 queued keys by default, with a 1 s queue deadline. Without more, a burst of misses from one tenant fills that queue and every other tenant waits behind it. Give the gate a tenant function and waiting loads are served round-robin across tenants, in order within each one:

const cache = createCache({
  originLoad: {
    tenant: (key) => key.split(':')[0],          // 'acme:user:7' → 'acme'
    perTenant: { maxConcurrent: 8, maxQueued: 200 },
  },
})

perTenant caps the running slots and queue places a single tenant may hold, so one tenant's surge is rejected early instead of slowing everyone. A tenant function that throws puts the key in a shared default tenant. In-flight dedupe still runs first, so ten thousand callers for one key take one slot, not ten thousand.

Choosing

SituationUse
One serverIn-flight dedupe alone
Several servers, cheap loaderIn-flight dedupe alone
Several servers, expensive loaderAdd the distributed lock
Loader hits a rate limited third partyAdd the distributed lock
Many servers, hot shared keysAdd the lock, and keep broadcastSetMaxBytes set

There is a third mechanism working alongside these, and it is easy to miss. When a getOrSet loader resolves with an event bus configured, the value itself is published, and every peer writes it straight into its own L1. One server pays for the query and the rest are warm before they ever ask, which flattens the herd before it forms.

Watching the collapse

Every reuse emits an event, so the collapse is measurable rather than assumed.

src/cache/metrics.js
import { cache } from './index.js'

cache.on((event) => {
  // The herd collapsing. High counts next to low loader:start counts is health.
  if (event.type === 'inflight:reuse') metrics.increment('cache.inflight.reuse')
  // Tracking capacity exceeded. A steady stream means raise inflight.maxEntries.
  if (event.type === 'inflight:bypass') metrics.increment('cache.inflight.bypass')
  if (event.type === 'loader:start') metrics.increment('cache.loader.start')
})

Never use a cache key as a metric label. Keys are unbounded, and one high cardinality label will take down your metrics backend before it takes down your cache.

Where to next

Questions

What is a cache stampede?

A cache stampede, or thundering herd, is many concurrent requests missing the same key at once, for example when a popular key expires or after a deploy, and all sending the same query to the database. The extra load slows the origin, which widens the window and lets more callers in.

Does in-flight deduplication work across several servers?

No, it is per process: four servers each make one loader call. With Redis L2, getOrSet also takes a per-key lease, so one instance loads the key and the others wait. With an event bus they are woken when the load finishes; without one they poll every pollMs.

How many Redis round trips does a cache miss cost?

Two with RedisStore's v2 key layout, with or without the lock: one script reads the key and takes its lease when it is empty, and one publishes the value and releases the lease. 0.7.0 took seven with the lock.

Is the distributed lease an exactly-once guarantee?

No. It is stampede protection. Redis failover, process pauses and loaders that ignore their abort signal can still allow overlapping origin work, so keep loaders read-only and pass the supplied AbortSignal to your database client.

On this page