Hot Keys and Thundering Herd

Handling the one key everyone wants at once: hot partitions, cache stampedes, request coalescing and key splitting.

What is it?

Sharding and caching assume load spreads evenly across keys. Real traffic doesn't. A celebrity posts, a product goes viral, a match ends, and one key suddenly gets thousands of times more traffic than the rest.

Two related failure modes follow:

- Hot key / hot partition: one key (or one shard holding it) gets far more traffic than a single node can handle, even though the cluster as a whole has spare capacity. Adding more shards doesn't help, because the key lives on one of them. - Thundering herd / cache stampede: a popular cache entry expires (or a cache restarts), and thousands of requests miss at the same moment. All of them hit the database to rebuild the same value, and the database falls over.

The fixes come in a few families: coalesce duplicate work (single-flight), refresh early so popular entries never fully expire, spread hot keys across nodes (salting, replication, local caches), and smooth timing with jitter.

Explain like I'm 10

A bakery sells out of its famous bread at noon. If 200 customers each run to the kitchen to bake a new loaf, the kitchen jams. Better: one baker bakes while everyone else waits for that loaf, and the baker starts the next batch a little before the shelf empties.

Examples

Single-flight: one rebuild per key, everyone shares the result

const inFlight = new Map<string, Promise<unknown>>();

async function getWithSingleFlight<T>(key: string, load: () => Promise<T>): Promise<T> {
  const cached = await cache.get<T>(key);
  if (cached !== undefined) return cached;

  const existing = inFlight.get(key);
  if (existing) return existing as Promise<T>; // join the rebuild already running

  const rebuild = load()
    .then(async (value) => {
      await cache.set(key, value, { ttlSeconds: 300 });
      return value;
    })
    .finally(() => inFlight.delete(key));

  inFlight.set(key, rebuild);
  return rebuild;
}

Coalesces concurrent misses within one process (like Go's singleflight). Across many servers you still get one rebuild per server, which is usually fine; use a short distributed lock if it isn't.

Probabilistic early expiration (XFetch)

// entry = { value, expiresAt, recomputeMs }  (recomputeMs: how long the last rebuild took)
function shouldRefreshEarly(entry: CacheEntry, beta = 1.0): boolean {
  // -Math.log(random) is a positive, exponentially distributed number.
  // Requests near expiry, for expensive values, are more likely to refresh.
  const earlyByMs = -entry.recomputeMs * beta * Math.log(Math.random());
  return Date.now() + earlyByMs >= entry.expiresAt;
}

Each reader independently rolls the dice. As expiry approaches, one request (usually) refreshes the value in the background before it actually expires, so there is never a moment when everyone misses.

Key salting for a hot write counter

const SPLITS = 16;

// Writes spread over 16 keys, likely on different shards
function incrementLikes(postId: string) {
  const shard = Math.floor(Math.random() * SPLITS);
  return store.incr("likes:" + postId + ":" + shard);
}

// Reads gather and sum (cache the sum briefly for hot posts)
async function getLikes(postId: string) {
  const keys = Array.from({ length: SPLITS }, (_, i) => "likes:" + postId + ":" + i);
  const counts = await store.mget(keys);
  return counts.reduce((sum, count) => sum + Number(count ?? 0), 0);
}

Splitting turns one hot key into N cooler ones. Writes get cheaper, reads get more expensive, so only split keys you know are hot.

How it works

Detecting hot keys. You can't fix what you can't see. Sample requests per key at the proxy or client, keep top-k with a Count-Min Sketch, and alert on per-shard skew (one node at 90% CPU while others idle). Redis offers --hotkeys (with an LFU eviction policy) and many managed stores publish per-partition metrics.

Read-hot keys. - Local (in-process) cache with a short TTL (1–5 s). Thousands of app servers each hold a copy, so the shared cache sees one request per server per TTL instead of every user request. - Replicate the key: store copies as key#1..key#N on different nodes and read a random one. Writes must update all copies. - CDN or edge caching for public content.

Write-hot keys. - Salting / splitting: write to key#random(N) and aggregate on read. - Buffer and batch: accumulate increments in memory or a queue and flush every second, turning 10,000 writes into one. - Isolate known hot entities on dedicated partitions.

Cache stampede. - Request coalescing (single-flight): within a process, only one caller rebuilds a key; others await the same promise. Across processes, a short-TTL lock (SET key NX PX) lets one server rebuild while others serve stale data or wait briefly. - Stale-while-revalidate: keep serving the old value past its soft TTL while one request refreshes it in the background. Requires a hard TTL longer than the soft one. - Probabilistic early expiration (XFetch): each read refreshes early with a probability that rises as expiry nears. - TTL jitter: add ±10–20% randomness so keys written together don't expire together. - Warm caches before cutover after a deploy or cache-cluster restart.

Thundering herd beyond caches. The same pattern hits when a service recovers and every client retries at once, or when cron jobs all fire at :00. Fix with exponential backoff with jitter, retry budgets, and spreading scheduled work.

Without coalescing                    With single-flight

1000 requests --miss--> DB x1000      1000 requests --miss--> 1 loader --> DB x1
                                                     999 wait <---- shared result

Hot partition                         Salted key

likes:42 -> shard 3 (100% CPU)        likes:42:0  -> shard 1
           shards 1,2,4 idle          likes:42:1  -> shard 4
                                      ...
                                      likes:42:15 -> shard 2   (sum on read)

Why does it exist?

Popularity follows a power law: a small number of keys get most of the traffic, and the extremes arrive suddenly. Horizontal scaling helps only when load spreads across keys. Hot-key and stampede techniques handle the cases where it doesn't, which are exactly the moments (launches, viral events, outages) when failure is most visible.

When to use it

- Social feeds, celebrity profiles, viral posts, live-event scoreboards. - Flash sales and ticket drops on a single product or event. - Any expensive cached value (a homepage, a config blob) read by every request. - Global counters: likes, views, inventory. - After deploys or cache restarts, when many keys are cold at once.

When not to use it

- Don't salt every key "just in case". It multiplies read cost and adds complexity. Detect hot keys first, then treat those. - Local caches are wrong for data that must be immediately consistent (balances, permissions just revoked) unless you can accept TTL-long staleness. - Probabilistic early refresh matters for expensive or very popular entries; for cheap, cold keys plain TTLs are fine.

Common mistakes

  • Adding shards to fix a hot key. The key still lives on one shard; you need to split, replicate or cache it.

  • Setting the same TTL on keys populated together, so they all expire in the same second.

  • Implementing single-flight but not clearing the in-flight entry on failure, so one error poisons the key until restart.

  • Retrying without jitter after an outage, so recovering services are knocked over again by synchronized retries.

  • Using a distributed lock for rebuilds without a timeout, so a crashed holder blocks the key forever.

Practice exercises

  1. Easy:

    Explain the difference between a hot key and a cache stampede, with one example of each.

  2. Medium:

    A homepage payload takes 2 seconds to build and is read 50,000 times per second. Design caching so that expiry never causes a database spike.

  3. Hard:

    Design the like counter for posts where a celebrity post can receive 200,000 likes per second. Cover write path, read path, consistency of the displayed count and how you detect which posts need special handling.

Interview questions

What is a hot key?

A single key receiving disproportionate traffic, so the node or partition holding it is overloaded even though the rest of the cluster has spare capacity.

What is a cache stampede?

When a popular cache entry expires or the cache is cold, many concurrent requests miss at once and all hit the backing store to recompute the same value, often overloading it.

What is request coalescing (single-flight)?

Deduplicating concurrent requests for the same key so only one does the expensive work and the others wait for and share its result.

Why add jitter to TTLs?

Entries written at the same time with the same TTL expire at the same time, creating periodic stampedes. Random jitter spreads expirations out.

How does probabilistic early expiration work?

Each read refreshes the value early with a probability that rises as expiry approaches and as recompute cost grows (XFetch: refresh if now − recomputeTime·β·ln(rand) ≥ expiry). Usually one request refreshes before expiry, so there's no mass miss.

How do you handle a key that is hot for reads?

Cache it close to the caller: in-process caches with short TTLs, replicate it as several keys on different nodes and read one at random, or put it behind a CDN. Choose based on how stale it can be.

How do you handle a key that is hot for writes?

Split it into N sub-keys and aggregate on read, or buffer increments and flush in batches. Both trade read cost or freshness for write throughput.

What is stale-while-revalidate and what's its trade-off?

Serve the expired value while one request refreshes it in the background. Latency and backend load stay flat, at the cost of serving slightly stale data for a short window.

How would you detect hot keys in production?

Sample per-key request counts at clients or proxies, track top-k with a sketch, and watch per-shard CPU, QPS and latency skew. Alert when one shard diverges, and feed detected keys into automatic local caching or splitting.

A cache cluster restarts and the database immediately saturates. How do you prevent this next time?

Warm the cache before taking traffic, restart nodes gradually, use request coalescing and serve-stale on misses, rate-limit or shed load to the database, and have clients retry with exponential backoff and jitter. Consider a replicated cache so one node's loss doesn't empty everything.