Skip to content

Cache Failure Modes: Stampedes, Hot Keys and Penetration

Advanced 41 min read Part 7 of 18

How caches fail and take databases down: stampedes, penetration, avalanches and TTL jitter, hot keys, big keys, cache outages and warming and their fixes.

Summary#

A cache that absorbs 95-99% of reads also hides how weak the database behind it is. When the cache stops working for some keys, or all of them, the database can be flooded within seconds. The main failure modes are: the cache stampede (thundering herd), many requests missing the same hot key at once (fix with locking, request coalescing and early refresh); cache penetration, requests for keys that do not exist and never get cached (fix with negative caching and a bloom filter); the cache avalanche, many keys expiring together (fix with TTL jitter); hot keys that overload one cache node (replicate, cache locally, split keys); big keys that block a node; and a cache outage that sends all traffic to the database (circuit breakers, rate limits, cache warming). Design for them before they happen.

Why It Exists#

Suppose a database comfortably serves 5,000 queries per second and the cache serves 100,000 reads per second at a 98% hit ratio, so the database sees 2,000. If the hit ratio drops to 80% for a few seconds, the database sees 20,000 queries per second, four times its capacity. Queries slow down, connections pile up, timeouts trigger retries, and the outage spreads. Many large incidents started as cache problems. Knowing the failure modes and their standard fixes is part of designing any cached system. This page builds on Cache Eviction and Invalidation.

How It Works#

Thundering herd / cache stampede#

When a popular key expires or is deleted, every request that arrives before it is reloaded misses. If the key gets 10,000 requests per second and recomputing it takes 200 ms, about 2,000 requests hit the database for the same row at once, all doing the same expensive work.

Fix 1: lock-based recompute. The first request to miss takes a short-lived lock (SET key:lock NX PX 5000 in Redis) and recomputes; others either wait briefly and retry the cache, or serve a stale copy if one exists.

get(key):
  v = cache.get(key)
  if v != null: return v
  if cache.set(key + ":lock", me, NX, PX = 5000):      # I won the lock
      try:
          v = load_from_db(key)
          cache.set(key, v, EX = ttl_with_jitter())
      finally:
          cache.delete_if_owner(key + ":lock", me)      # Lua compare-and-delete
      return v
  sleep(50 ms)                                          # others wait, then retry
  return cache.get(key) or get_stale(key) or load_from_db(key)  # last resort

Fix 2: request coalescing (single-flight). Inside each application server, concurrent requests for the same key share one in-flight load: the first caller starts it and the others await the same result (Go's singleflight, Caffeine's loading cache, Nginx proxy_cache_lock). This cuts database load from "all requests" to "one per server", and combined with a distributed lock, one per cluster.

inflight = map<key, Future>
load_coalesced(key):
  f = inflight.get_or_create(key, () => async load_from_db(key))
  try: return await f                     # all callers share one DB query
  finally: inflight.remove_if_same(key, f)

Fix 3: early (probabilistic) refresh. Refresh hot keys before they expire, so they never miss under load. Either a background job refreshes known hot keys, or each request, as expiry approaches, refreshes with a probability that rises as the deadline nears (the "XFetch" approach from Vattani, Chierichetti and Lowenstein). Serving stale data while refreshing (stale-while-revalidate) has the same effect at the HTTP layer.

Stampedes, in depth#

Why the herd grows on its own. The number of requests that miss together is roughly the request rate times the reload time: 10,000 requests per second times a 200 ms reload is about 2,000 concurrent misses. But those 2,000 identical queries slow the database down, so the reload now takes 2 seconds, and the herd grows to 20,000 before the first reload finishes. The stampede feeds itself. That is why a 60-second TTL on a home-page feed can take a database down at exactly 12:01:00 even though the same query runs comfortably once a minute.

Expiry is not the only trigger. A stampede follows any event that removes a hot entry: TTL expiry, an explicit delete after a write, eviction under memory pressure, or the node holding the key failing. This matters for the choice of fix. Proactive refresh (re-computing hot keys before their TTL) prevents expiry-driven stampedes, but it does nothing when the key is deleted because the underlying data changed. For delete-driven stampedes you need coalescing or locking, or you replace delete with an in-place update for that key.

Designing the recompute lock properly.

  • Lock TTL longer than the worst recompute, but not much longer. If a recompute usually takes 200 ms and occasionally 2 seconds, a 5-second lock is reasonable. A lock that expires during a slow recompute lets a second recompute start. A lock with no expiry blocks the key forever if its holder crashes.
  • Release only your own lock. Store a random token as the lock value and release with a compare-and-delete script, so a slow holder whose lock already expired cannot delete a newer holder's lock.
  • Decide what waiters do. Waiting and polling the cache every 20 to 50 ms works, but it adds load and latency. Serving the previous value is better when one exists. A hard cap on waiting (for example 500 ms), after which the waiter reads the database itself, prevents a hung recompute from hanging every request.
-- release lock only if we still own it: KEYS[1] = lock key, ARGV[1] = my token
if redis.call('GET', KEYS[1]) == ARGV[1] then
  return redis.call('DEL', KEYS[1])
end
return 0

Keep a stale copy on purpose. The most robust stampede defence is to never be without a value. Store each entry with two times: a soft expiry (when it should be refreshed) and a hard expiry (when it must no longer be served). Set the Redis TTL to the hard expiry. A reader that finds an entry past its soft expiry returns it immediately and triggers one refresh, guarded by the lock. Readers only block when an entry is past its hard expiry or missing entirely. This gives stale-while-revalidate semantics to an application cache.

Coalescing at every layer. The same "one load, many waiters" idea exists in most proxies and CDNs. Varnish coalesces concurrent requests for the same object by default. Nginx does it with proxy_cache_lock on. CDNs call it request collapsing or collapsed forwarding, so a burst of misses for one URL at an edge becomes a single request to the origin. When you design a read path, check that each layer collapses misses, otherwise the herd reaches the next layer intact.

Choosing among the fixes.

SituationBest first fix
Hot key with TTL expiry and expensive recomputeSoft and hard expiry with background refresh
Hot key deleted on writesCoalescing per server plus a short distributed lock, or update in place
Many moderately hot keysCoalescing per server, TTL jitter
HTTP responses behind a CDNRequest collapsing plus stale-while-revalidate
Extremely hot single keyLocal in-process cache for 1 to 5 seconds on every server

Cache penetration#

Penetration is requests for keys that do not exist, in the cache or in the database: random IDs from a bot, deleted items, a bug. Each one misses the cache (there is nothing to cache) and hits the database, so an attacker can bypass the cache entirely.

  • Negative caching: cache "not found" results too, with a short TTL (30-300 seconds): SET product:999999 "__none__" EX 60. Cheap and effective; the cost is that a newly created item may appear "missing" until the TTL passes (delete the negative entry on create).
  • Bloom filter: keep a bloom filter of all valid IDs in memory (in the app or in Redis via the RedisBloom module). If it says "definitely not present", reject without touching the cache or database. Ten million IDs fit in about 12 MB at a 1% false-positive rate. It must be updated on inserts, and deletes need rebuilds or a counting variant.
  • Validate input: reject malformed IDs, and rate-limit clients that generate many misses. See Rate Limiting.

See Probabilistic Data Structures.

Penetration, in depth#

Three related problems, often confused. Some engineering literature separates three failure modes that all send requests past the cache:

  • Penetration: the key does not exist anywhere, so it can never be cached. Typical sources are scanners, bots trying sequential IDs, broken links and client bugs.
  • Breakdown (sometimes called a hot-key miss): one key that does exist, and is very hot, expires, and the herd hits the database. This is the stampede above.
  • Avalanche: many different keys miss together, covered in the next section.

The fixes differ, so naming the right one matters in a design discussion.

Negative caching done carefully.

  • Use a distinct sentinel value (__none__, or an empty marker with a type byte) so code cannot confuse "not found" with "empty list" or a failed read.
  • Use a shorter TTL than for real entries (30 to 300 seconds), because the cost of a wrong negative is that a newly created item looks missing.
  • Delete the negative entry on create. If items are created through one service, delete the key there. If many writers exist, let the CDC invalidator delete it when the row appears.
  • Bound the memory. An attacker requesting random IDs can create millions of negative entries. Store them in a separate namespace or a small dedicated cache with LRU eviction, so they cannot push out real data.
  • Cache errors differently from absences. If the database timed out, do not cache "not found". At most cache the error for a second or two, to avoid hammering a struggling backend.

Bloom filters: the maths. A Bloom filter is a bit array of m bits with k hash functions. Adding an item sets k bits. Checking an item tests the same k bits: if any is 0, the item was definitely never added; if all are 1, it was probably added. False negatives are impossible, while false positives happen with a probability that depends on m, k and the number of items n:

false positive rate p ≈ (1 - e^(-k·n/m))^k
optimal k = (m/n) · ln 2
bits needed m = -n · ln(p) / (ln 2)^2
 
n = 10 million IDs, p = 1%    ->  m ≈ 96 million bits ≈ 12 MB, k = 7
n = 10 million IDs, p = 0.1%  ->  m ≈ 144 million bits ≈ 18 MB, k = 10

Each factor of 10 reduction in false positives costs about 4.8 bits per item. A filter of 12 MB can reject 99% of nonexistent-ID requests in memory, in microseconds, before they reach the cache or the database.

Keeping the filter in sync. Every new valid ID must be added before requests for it can arrive, otherwise the filter rejects a real item. That is the one error a Bloom filter must never make in this role, because it would hide data that exists. Practical approaches: add on create in the write path, and rebuild the filter periodically from the database (a scan of 10 million IDs takes seconds to minutes). Standard Bloom filters cannot delete. Deleted IDs simply remain as harmless false positives until the next rebuild. If you need deletion, a counting Bloom filter (small counters instead of bits) or a cuckoo filter (Fan and colleagues, CoNEXT 2014) supports it, and cuckoo filters also use less space at low false-positive rates.

Where the filter lives. In-process filters are fastest but must be loaded and updated on every application server. A shared filter in Redis (RedisBloom's BF.ADD and BF.EXISTS, or hand-rolled with SETBIT and GETBIT) is updated in one place at the cost of a network hop. A large filter can also be sharded by ID range.

Other uses of the same idea. A dating app that must never re-show profiles a user already swiped on can keep a per-user Bloom filter of swiped IDs for users with very long histories. A false positive then means a profile is occasionally never shown, which is acceptable, while a false negative (re-showing a swiped profile) can never happen. The filter must be rebuilt from the swipe store if the cache holding it is lost, which is cheap per user but expensive for millions of users at once after a node failure. A web crawler can use a Bloom filter of content hashes to skip pages it has seen, though a database index on the hash is simpler and often fast enough, so a Bloom filter is worth it only when the set is huge or the check sits on a very hot path.

Validate before you look up. The cheapest defence runs before any of this. Reject IDs that fail format checks (wrong length, wrong checksum, outside the allocated range), and rate-limit clients by their miss rate rather than just their request rate. A client with a 95% miss rate is almost certainly scanning.

Cache avalanche and TTL jitter#

An avalanche is many keys expiring at the same time, so a wave of misses hits the database together. Typical causes: a batch job or cache warm-up that loaded millions of keys with the same TTL, or a deploy that changed the key format. It also covers the whole cache restarting (see outages below).

TTL jitter spreads expiry by adding randomness:

ttl_with_jitter(base = 3600):
  return base + random_int(0, base * 0.1)      # 3600-3960 s, expiries spread over 6 minutes
# or multiplicative: base * random_uniform(0.9, 1.1)

Combine with stampede protection for the hottest keys, and stagger bulk loads.

Avalanches, in depth#

Sizing the jitter. If N keys were loaded at the same moment with TTL T and no jitter, all N expire within about a second, and the miss wave is N requests per second at most, if every key is read again. With uniform jitter over a window J seconds, the expiries spread out to about N / J per second. Choose J so that this rate fits within the database's spare capacity:

N = 2,000,000 keys loaded by a warm-up job, TTL 1 hour
no jitter:          up to ~2,000,000 reloads in the same second
jitter 0 to 10%:    J = 360 s  ->  ~5,600 reloads per second
jitter 0 to 25%:    J = 900 s  ->  ~2,200 reloads per second
database spare read capacity: 3,000 per second  ->  use at least ~25% jitter, or stagger the load

Jitter only spreads expiry once. Each reload sets a fresh jittered TTL, so over a few cycles the expiries become uniformly spread even for keys loaded together.

Other ways to cause an avalanche.

  • Wall-clock expiry. "Expire at midnight" or "refresh at the top of the hour" aligns every key on the same instant by design. Add a random offset of a few minutes per key, or stagger by key hash.
  • A key-format change in a deploy. Changing product:v3 to product:v4 makes every key miss at once when the new code goes live. A rolling deploy across servers spreads this a little, but for high hit-ratio caches it is safer to read the old key as a fallback for one TTL period, or to pre-warm v4 keys before switching.
  • A flush. FLUSHALL on a production cache, or a configuration change that restarts every cache node at once, is an avalanche by another name. Protect flush commands (Redis rename-command, or ACLs that forbid them) and restart nodes one at a time.
  • Region failover. When traffic fails over from one region to another, the receiving region's cache has never seen most of the failing region's keys. Its hit ratio drops just when its load doubles. Keep caches warm in the standby region by replicating hot keys or mirroring a fraction of reads.

Retries turn a dip into an avalanche. When the database slows down, clients time out and retry. Without care, every retry adds load to an already overloaded system. Three rules keep retries safe: retry with exponential backoff (wait 100 ms, then 200, 400 and so on), add jitter to the waits so clients do not retry in synchronised waves, and limit the total with a retry budget (for example, retries may add at most 10% to normal traffic). Retried operations must be idempotent, which is easy for reads and needs idempotency keys for writes.

Hot keys#

A hot key is one key receiving a huge share of traffic: a celebrity's profile, a flash-sale product, a global config. In a sharded cache, that key lives on one node, and a single Redis node handles roughly 100k-200k simple operations per second; network bandwidth can saturate first if the value is large. One hot key can overload one node while the others idle.

Fixes:

  • Local (in-process) cache with a short TTL (1-5 seconds) for known hot keys: each app server answers from memory, cutting cache traffic by orders of magnitude.
  • Replicate the key: store copies under several keys (product:123#0 ... #7) on different nodes and read a random one; writes update or delete all copies.
  • Read replicas of the cache shard (Redis replicas) with reads spread across them.
  • Key splitting for writes to hot counters: split into N sub-counters and sum on read.
  • Detect hot keys with sampling or tools (redis-cli --hotkeys with LFU, proxy-level metrics) so you can react automatically.

See Distributed Caching and Pattern: Scaling Reads.

Hot keys, in depth#

The capacity arithmetic. A single Redis node serves on the order of 100,000 to 200,000 simple operations per second on one core, and its network interface caps bytes per second. A key read 300,000 times per second exceeds the node's command capacity on its own. A 10 KB value read 100,000 times per second needs about 1 GB per second of outbound bandwidth, close to the 1.25 GB per second limit of a 10 Gbit interface, before any other key is served. Hot keys are therefore a throughput problem on one node, even when the cache's overall hit ratio is perfect. A celebrity's profile key during a major event is the textbook case, with a single key receiving millions of requests per second.

Detecting them. You cannot fix hot keys you do not see.

  • redis-cli --hotkeys reports the most frequently accessed keys, but it needs an LFU eviction policy, because it reads the LFU counters.
  • Client-side sampling: log one in every 1,000 cache operations with the key and aggregate them in a streaming job or a top-K sketch. This catches hot keys within seconds and works with any cache.
  • Per-node metrics: one node with far higher CPU or network use than its peers is the signature of a hot key or a big key on that node.
  • Some managed Redis services and cache proxies can report hot keys, and some can cache them automatically.

Fix 1: a local cache in each server. Keep the hottest keys in process memory for 1 to 5 seconds. With 1,000 application servers and a 2-second local TTL, the shared cache sees about 500 requests per second for that key, regardless of whether users send 10,000 or 10 million. The cost is up to 2 seconds of extra staleness, and memory on every server, so local caching should be limited to a small, detected hot set rather than every key.

Fix 2: copies of the key on several nodes. Store N copies under suffixed keys (user:celebrity#0 to user:celebrity#7) that hash to different nodes, and have each read pick a random suffix. Read capacity for the key grows by N. Writes must update or delete all N copies, so this suits keys that are read far more than written. A variant chooses N dynamically: normal keys have one copy, and detected hot keys are fanned out.

Fix 3: replicas or redundant caches. Spread reads across Redis replicas of the shard that holds the key (accepting replica lag), or run several independent cache clusters behind a load balancer, each able to serve any key. With N independent caches, a hot key's load splits N ways. The trade-off is that each cache misses independently, so a cold or invalidated key costs N database reads instead of one, which is small compared with the load avoided.

Fix 4: rate limiting the abuser. Sometimes a "hot key" is one client in a loop, such as a buggy mobile release polling every 100 ms or a scraper. Per-client and per-key rate limits stop it at the edge. The right fix then is in the client, not the cache.

Hot write keys. Counters such as likes or views on a viral post concentrate writes on one key. Two standard fixes:

  • Split the counter. Keep N sub-counters (likes:post:9#0 to #15), increment a random one, and sum them on read (or cache the sum for a second). Write capacity grows by N.
  • Aggregate before writing. Each application server accumulates increments in memory for 1 second and sends one INCRBY with the total. With 500 servers this caps writes to the key at about 500 per second, whatever the click rate. The cost is up to a second of lost counts if a server crashes.

Big keys#

A big key is a single value or collection that is very large: a 10 MB JSON blob, or a hash or list with millions of elements. Problems:

  • Reading or writing it uses a lot of network bandwidth and time; on single-threaded Redis, one slow command blocks every other request on that node.
  • Deleting a huge key with DEL can block for seconds (use UNLINK, which frees memory in the background).
  • Migration and replication of the key are slow and can cause failovers.

Fixes: keep values small (tens of KB at most, ideally under 10 KB), split collections into buckets (followers:42:0..99), compress large values, page through collections (HSCAN, ZRANGE with limits) instead of fetching all, and find big keys with redis-cli --bigkeys or memory analysis.

Big keys, in depth#

Why one key can hurt everyone. Redis executes commands one at a time on a single main thread (I/O threads in newer versions help with sockets, not with command execution). A command that takes 50 ms delays every other command queued behind it on that node by 50 ms. Big keys produce exactly these commands:

  • GET of a 10 MB string means 10 MB copied into the output buffer. At 10 Gbit that is about 8 ms on the wire alone, plus serialisation in the client.
  • HGETALL, SMEMBERS or ZRANGE 0 -1 on a collection with millions of members is O(n) and can run for hundreds of milliseconds.
  • DEL on a hash with 10 million fields frees each field synchronously and can block for seconds. UNLINK (or lazyfree-lazy-user-del yes, so DEL behaves like UNLINK) hands the freeing to a background thread.
  • Expiry and eviction of a big key can also free it synchronously unless the lazy-free options for expiry and eviction are enabled.

Operational side effects. Resharding a Redis Cluster moves keys between nodes one at a time with MIGRATE, which is atomic per key, so a 500 MB key blocks both source and target while it moves. Replicas receive big writes through the replication output buffer, and a buffer that exceeds its limit disconnects the replica, which then needs a full resync. Big keys also make memory usage uneven across nodes, so one node can hit maxmemory while the rest have space.

Finding them. redis-cli --bigkeys scans the keyspace and reports the largest key per type by element count. redis-cli --memkeys and MEMORY USAGE key report bytes. For a full picture without loading production, analyse an RDB snapshot offline with an RDB parsing tool, which lists every key with its size.

Fixing them.

  • Bucket collections. Split followers:42 into 100 buckets by hashing each follower ID modulo 100 (followers:42:0 to followers:42:99). Membership checks touch one bucket, and a full read pages through buckets.
  • Page instead of fetching all. Use HSCAN, SSCAN and ZRANGE with limits, and design the API so clients ask for a page, never everything.
  • Compress values. JSON compresses 3 to 10 times with zstd or gzip, at a small CPU cost in the client.
  • Store blobs elsewhere. Put large documents and images in object storage or a CDN and cache only metadata and a URL.
  • Enforce limits. Add a value-size check in the cache client library that logs or rejects values over, say, 100 KB. A limit in code catches big keys in review rather than in an incident.

Cache outage overloading the database#

If the whole cache cluster fails or restarts empty, every read goes to the database. At a 98% hit ratio, database traffic jumps 50x. Defences, from the application inward:

  • Circuit breaker and fallback: if the cache is down, do not wait on timeouts for every request; fail fast and serve degraded content (defaults, stale data from a local cache) for non-critical features.
  • Rate limit or shed load to the database: let through only what it can handle, queue or reject the rest, rather than letting it collapse.
  • Replicated, highly available cache: replicas with automatic failover (Redis Sentinel or Cluster, ElastiCache Multi-AZ), spread across zones.
  • Persistence for warm restarts where useful (Redis RDB snapshots), though restoring large datasets takes time.
  • Size the database for a realistic degraded hit ratio, not for zero misses.

See Resilience Patterns.

Cache outages, in depth#

Do the arithmetic before the outage does it for you. Database load is total read traffic times the miss ratio. With 100,000 reads per second:

Cache stateHit ratioDatabase reads per second
Healthy98%2,000
One of 10 nodes lost, keys rehashedabout 88%about 12,000
Cluster restarted cold0% at first100,000

If the database can serve 5,000 reads per second, losing a single node already overloads it. Decide in advance which of three postures you are designing for: the database can absorb a full outage (rare at scale, expensive), the system degrades gracefully (shedding and fallbacks keep the critical path alive), or the cache is as available as the database (replicated, multi-zone, with fast failover). Most large systems choose the second and third together.

Timeouts on cache calls. A cache that is slow rather than down is worse than one that is down, because every request waits for the timeout. Set cache timeouts far below the request budget: 10 to 50 ms for a Redis call in the same zone, against a typical 1 to 2 ms response. Without that, a sick cache node holds application threads for seconds, and the application tier fails along with it.

Circuit breakers around the cache and the database. A circuit breaker watches calls to a dependency. When failures pass a threshold, it opens, and calls fail immediately without being attempted. After a cool-down it goes half-open and lets a few test calls through. If they succeed it closes, otherwise it opens again.

Around the cache, an open breaker means "skip the cache and use the fallback path" without waiting for timeouts. Around the database, an open breaker protects it while it recovers. When a database restarts, a firehose of queued requests and retries can keep its first instance from ever becoming healthy. The breaker, together with load shedding, gives it room to come back. Breakers fail fast, reduce load on the struggling dependency, test recovery automatically and keep user-facing latency predictable.

Graceful degradation, decided per feature. For each cached read, decide in advance what happens when both the cache and a safe amount of database capacity are unavailable:

  • Serve a stale copy from a local cache or a secondary store (product details, profiles).
  • Serve a default or a reduced page (recommendations replaced by a static best-seller list).
  • Drop the feature temporarily (view counts, "people also bought").
  • Keep it exact and accept errors (checkout, payments), protected by priority so these requests get the database capacity that remains.

Load shedding by priority. Put a concurrency limit in front of the database (in the data-access layer or a proxy such as a connection pooler) and rank requests: checkout and login first, browsing second, background jobs last. When the limit is reached, low-priority requests are rejected immediately instead of queueing. Rejecting 30% of browse traffic quickly is far better than serving 100% of everything slowly until the database falls over.

Failover inside the cache tier. Replicated Redis (Sentinel, Redis Cluster or a managed Multi-AZ service) promotes a replica when a primary fails, typically within seconds to tens of seconds, depending on detection timeouts. During that window, writes to the failed shard fail and reads either fail or go to replicas. Replication is asynchronous, so the last writes before the failure can be lost. That is fine for a cache, but it is one more reason not to use the cache as the only copy of important data.

Meta's gutter pool. The memcache paper describes a different approach to node failure. Instead of rehashing a failed node's keys onto the remaining nodes, which would shift its load onto them and cause a wave of misses everywhere, clients that get no response retry against a small, dedicated gutter pool, roughly 1% of the cluster's servers. Gutter entries expire quickly, so stale data does not linger, and the database is shielded from most of the failed node's traffic. The paper reports that the gutter pool cut client-visible failures by about 99%.

Cache warming#

A new or restarted cache is cold: hit ratio near zero. Warming fills it before or while taking traffic:

  • Preload the known hot set (top products, home page data) from the database or from an analytics list before sending traffic.
  • Shadow traffic: mirror a portion of real reads to the new cache cluster before switching.
  • Gradual traffic shift: move 5%, 20%, 50%, 100% of traffic to the new cluster, letting it warm naturally.
  • Copy from the old cluster during migrations (Netflix has described tooling for EVCache that warms new replicas from existing ones).

Warm slowly enough not to overload the database during the warm-up itself.

Warming, in depth#

What warming can and cannot fix. Warming fills a cache before traffic needs it. It prevents misses caused by emptiness: a new cluster, a restarted node, a new region, a key-format change. It does not prevent stampedes caused by invalidation. A key deleted because its data changed is empty again the moment it is deleted, however well the cache was warmed, so delete-driven stampedes still need coalescing or locks.

Deciding what to warm. Warm the hot set, not everything. Take the top keys by request count over the last few hours, from access logs, client-side sampling or LFU counters on the existing cluster. Under a skewed (Zipf-like) distribution, the top 1% of keys often carry most of the reads, so warming a small fraction of the keyspace recovers most of the hit ratio.

Warming at a safe rate. A warmer reads from the database, so it can cause the very overload it is meant to prevent. Budget it:

hot set to warm:            1,000,000 keys
database spare capacity:    2,000 reads per second (leave headroom for live traffic)
warm-up time:               1,000,000 / 2,000 = 500 seconds, about 8 minutes
with 10 keys per query:     about 50 seconds

Batching (fetch many keys per query) and reading from a replica rather than the primary both shorten the warm-up without hurting live traffic.

Ways to warm.

  • Preload from the database using the hot-key list, rate-limited as above.
  • Copy from an existing cache. Read the hot keys from the old cluster or a healthy replica and write them into the new one. This puts no load on the database at all. Netflix has described cache-warming tooling for EVCache that populates new replicas from data in existing ones, which made scaling and replacing cache clusters routine.
  • Restore from a snapshot. Load a recent Redis RDB file into the new node. The data is somewhat stale, so pair it with short TTLs or CDC catch-up.
  • Shadow reads. Mirror a fraction of live reads to the new cluster, letting it fill naturally while the old cluster still serves users.
  • Gradual cutover. Shift 1%, 5%, 25%, then 100% of traffic, watching the database at each step.

Cold starts after deploys. In-process caches are empty on every new instance. Rolling deploys replace instances a few at a time, so the shared cache and the database see a small, steady extra load. Deploying all instances at once empties every local cache simultaneously, and the hottest keys then stampede the shared cache. Keep deploys rolling, or warm local caches at startup before the instance passes its readiness check.

Summary of failure modes#

FailureTriggerFix
StampedeHot key expires or is deletedLock-based recompute, coalescing, early refresh, serve stale
PenetrationRequests for nonexistent keysNegative caching, bloom filter, input validation, rate limits
AvalancheMany keys expire togetherTTL jitter, staggered loads
Hot keyOne key gets huge trafficLocal cache, key replicas, cache read replicas
Big keyHuge values or collectionsSplit, compress, page, UNLINK
Cache outageCluster down or coldHA cache, circuit breakers, load shedding, warming

Worked incident: a flash sale#

The setup. An online shop runs a flash sale at 10:00. Normal traffic is 20,000 reads per second at a 98% hit ratio, so PostgreSQL serves about 400 reads per second and can handle about 6,000. Marketing expects 10 times normal traffic for the first ten minutes. The sale's 50 products were added to the catalogue at 09:55.

How it goes wrong without preparation.

  1. 09:59:59, penetration. Bots poll the sale product IDs before they are visible, and earlier requests had negative-cached them as "not found" with a 5-minute TTL. At 10:00 real users see "product not found" for several minutes. This is a negative-caching bug, not a load problem.
  2. 10:00:00, avalanche. A warm-up job loaded all 50 sale products at 09:55 with an identical 5-minute TTL. They all expire at 10:00:00, exactly when traffic jumps to 200,000 reads per second.
  3. 10:00:01, stampede. Each sale product gets about 4,000 reads per second. Every one of them misses, and the product query, which joins prices and stock, takes 30 ms and then 300 ms as the database saturates.
  4. 10:00:03, hot key. The sale landing page key gets 60,000 reads per second and saturates its Redis node, so every other key on that node becomes slow.
  5. 10:00:05, retries. Application timeouts fire and clients retry immediately. Database load passes 20,000 queries per second, and connection pools are exhausted.
  6. 10:00:30, metastable state. Even after the first burst passes, the cache cannot refill because the loads keep timing out. The site stays down until traffic is shed manually.

The same sale, prepared.

RiskPreparation
Negative entries for new itemsDelete negative entries when products are created or published, and keep negative TTLs at 30 seconds
Synchronised expiryWarm sale keys with jittered TTLs and soft and hard expiry, and refresh them in the background during the sale
Stampede on sale productsCoalescing per server plus a refresh lock, serving the stale copy while refreshing
Hot landing pageA 2-second in-process cache on every server, plus copies on 8 Redis nodes
RetriesExponential backoff with jitter and a retry budget in the client library
Database protectionConcurrency limit with priority, so checkout gets capacity first and browsing degrades
VerificationA load test at 15 times normal traffic the week before, including a test that kills one Redis node mid-test

The general lesson. The failure modes rarely come alone. One trigger, such as synchronised expiry, produces a stampede, which produces slow queries, which produce retries, which keep the cache from refilling. The defences work best in layers, so that each failure mode is stopped close to where it starts.

Game days. Rehearse the failures. Kill a cache node during a load test, flush a staging cache under traffic, add 200 ms latency to cache calls, or replay a bot scan of random IDs. Measure the database's peak load and the time to recover. A cache failure plan that has never been tested is a guess.

Correctness failures: when the cache serves the wrong data#

Load failures are loud. Correctness failures are quiet and often worse, because the cache confidently serves data that is wrong, or that belongs to someone else.

  • Key collisions and missing key parts. If a response depends on the user, locale, tenant, currency or feature flag but the key omits it, one user's version is served to everyone. With personal data this is a data leak. On Christmas Day 2015, during a traffic surge, a caching configuration change on Valve's Steam store caused account pages to be cached and shown to other users. The rule: either include every input that changes the output in the key, or mark the response as uncacheable (Cache-Control: private or no-store for anything personal at shared caches).
  • Serialisation mismatches during deploys. New code writes a value in a new format, and old code that is still running during the rolling deploy reads it and fails, or worse, misreads it. Version the key or the value format (product:v4), and make readers tolerate unknown fields.
  • Web cache poisoning. A shared cache keys on the URL but the origin's response also depends on an unkeyed header, such as X-Forwarded-Host. An attacker sends a request with a malicious header value, the poisoned response is cached, and every later visitor receives it. James Kettle's research at PortSwigger ("Practical Web Cache Poisoning", 2018) showed this against many real sites. Defences: make sure every input that affects the response is in the cache key or stripped before the origin sees it, and use Vary correctly.
  • Web cache deception. The reverse trick: an attacker gets a victim to visit a URL such as /account/settings/x.css. The origin ignores the suffix and returns the private account page, and the CDN caches it because it "looks static". Cache only by explicit rules and content types the origin declares, never by file extension alone.
  • Caching errors. A transient 500 or an empty result from a timed-out query gets cached for the full TTL and turns a one-second blip into an hour of broken pages. Cache error responses for seconds at most, or not at all.

Monitoring cache failure modes#

SignalDetectsExample alert
Hit ratio per key prefixAvalanches, key-format bugs, broken invalidationDrop of 2 points over 5 minutes
Misses per second against database capacityAny miss surgeMisses above 50% of the database's spare read capacity
Per-node CPU and network compared with the cluster medianHot keys and big keysOne node at 3 times the median
Slow log entries and command latency at p99Big keys, blocking commandsp99 above 5 ms on any node
Lock wait time and coalesced waitersStampedes in progressWaiters per key above 1,000
Negative-cache hit rate and miss rate per clientPenetration and scannersA client with over 90% misses
Evictions and memory fragmentationUndersized cacheEvictions of keys read within the last minute
Database queries per second and connection pool useThe impact of all of the abovePool above 80% for 2 minutes

The most useful single chart overlays cache misses per second with database queries per second and latency. In nearly every cache incident, the first line jumps and the other two follow within seconds.

Pair dashboards with runbooks. For each alert, write down the first three actions: which keys to inspect, how to enable local caching or key copies for a hot key, how to raise negative-cache TTLs during a scan, and how to turn on load shedding. During an incident, a prepared action takes seconds, while an improvised one takes minutes the database may not have.

Failures in caches you do not control#

Some caches sit outside your servers, so you cannot flush them when something goes wrong. Their failure modes need prevention, because there is no cure afterwards.

  • Browser and mobile caches. If a release ships a response with Cache-Control: max-age=31536000 by mistake, for example on an HTML page or an API response, every client that fetched it keeps the wrong copy for a year, and no purge reaches them. Only content-hashed assets should get long lifetimes. Give HTML and API responses short lifetimes or no-cache (which means "revalidate before use"), so a mistake heals in minutes.
  • Service workers. A buggy service worker can serve a cached, broken app shell indefinitely, because it intercepts the request that would have fetched the fix. Browsers re-check the service worker script itself at least every 24 hours, and a "kill switch" version of the worker that clears caches and unregisters itself is the standard remedy, but it should be prepared before it is needed.
  • Mobile apps with embedded caches. Old app versions can keep caching under rules you have since changed. Put cache policy in server responses (headers or a config endpoint) rather than hard-coding it in the client, so the server can change behaviour for every version.
  • DNS caches. Resolvers and clients cache DNS answers for the record's TTL, and some ignore low TTLs. A failover that changes DNS records takes effect gradually over minutes, and some clients keep connecting to the old address for much longer. Plan DNS-based failover with TTLs of 60 seconds or less, set well before the incident, and keep the old endpoint answering (even with a redirect) during the transition.
  • Third-party CDN behaviour. CDNs differ in how they treat Vary, query strings, cookies and error responses. A response cached differently from what you expected can be served from hundreds of edges at once. Test cache keys and headers in staging against the real CDN configuration, and know the purge commands and their propagation times before you need them.

The common principle: the further a cache is from your control, the shorter its default lifetime should be, and the more its behaviour should be driven by headers or configuration that you can change centrally.

When to Use It#

  • Any cache in front of a database that cannot survive the full read load on its own.
  • Systems with skewed popularity (social, e-commerce, news) where hot keys are certain.
  • Public endpoints where attackers or crawlers can request arbitrary IDs.
  • Before launches, migrations and flash sales.

When NOT to Use It#

  • Small systems where the database could handle all reads anyway; simple TTLs are enough.
  • Do not add distributed locks for keys that are cheap to recompute; coalescing per server suffices.
  • Do not negative-cache for long periods where new items must appear immediately.

How to Implement It#

  1. Model the worst case: database load at hit ratios of 90%, 50% and 0%; know the database's real capacity.
  2. Jitter every TTL and stagger bulk loads.
  3. Coalesce misses per server; add a distributed lock or lease for very expensive keys; serve stale on refresh.
  4. Negative-cache misses with short TTLs; add a bloom filter for ID spaces attackers can scan.
  5. Detect and handle hot and big keys: local caches, replicas, size limits in code review.
  6. Make the cache HA across zones; add circuit breakers and database rate limits.
  7. Warm new clusters with preload, shadow traffic or gradual shifts.
TechnologyFits when
Redis SET NX PX, Redlock-style leasesLock-based recompute
Go singleflight, Caffeine, Nginx proxy_cache_lockRequest coalescing
RedisBloom, Guava BloomFilterPenetration protection
Redis Cluster/Sentinel, ElastiCache Multi-AZHA caches
Resilience4j, Envoy circuit breakingFail fast when the cache is down

Trade-offs#

FixGainCost
Locking / leasesOne recompute per keyWaiting requests, lock handling
CoalescingSimple, in-processOne load per server, not per cluster
Early refresh / stale servingNo miss storms on hot keysSlight staleness, extra loads
Negative cachingBlocks repeat missesNew items invisible until TTL
Bloom filterBlocks unknown IDs cheaplyMust stay in sync; false positives
TTL jitterSpreads expiryLess predictable TTLs
Local hot-key cacheHuge read offloadSeconds of staleness per server
Soft and hard expiryReaders never wait on hot keysStores extra metadata, serves bounded stale data
Hot-key copies across nodesRead capacity grows with copiesWrites and deletes fan out to every copy
Load shedding by priorityCritical paths survive overloadSome users see errors or reduced pages

Common Pitfalls#

  • Setting the same TTL on millions of keys loaded at once.
  • Locks without expiry, so a crashed recompute blocks a key forever.
  • Assuming the database can survive a cache restart because "it did in staging".
  • Caching nothing for missing IDs, letting scanners hit the database directly.
  • Storing huge collections in one key and blocking Redis on reads or deletes.
  • Negative-caching "not found" for new items without deleting the entry on create.
  • Retrying at every layer with no budget, so an overload multiplies itself.
  • Using a cache timeout as long as the request timeout, so a slow cache stalls every thread.
  • Warming a new cluster faster than the database can serve the warm-up reads.

Real-World Examples#

Meta's memcache paper describes leases to prevent thundering herds and stale sets, and "gutter" servers that take over for failed cache nodes so their load does not fall onto the databases.

Netflix has described EVCache, its memcached-based cache, replicating data across availability zones and warming new clusters from existing replicas to avoid cold-cache load on backends.

Marc Brooker's AWS Builders' Library article on timeouts, retries and backoff with jitter is a standard reference for retry design. The OSDI 2022 study of metastable failures in distributed systems analyses real incidents in which retries and cold caches sustained an outage after the trigger had passed.

In the Interview#

Failure modes in an interview#

Raise them yourself. As soon as you add a cache to a design, spend thirty seconds on what happens when it misbehaves. Interviewers often test caching by asking about its failure modes, and naming them unprompted shows you understand the trade-off, not just the benefit.

Use the right names, with one fix each.

  • "A hot key expiring is a stampede. I'd coalesce misses per server and refresh the key before expiry, serving the stale value meanwhile."
  • "Random IDs from scrapers are penetration. I'd negative-cache misses for 60 seconds and validate IDs, plus a Bloom filter if the ID space is huge."
  • "Bulk-loaded keys with the same TTL cause an avalanche, so TTLs get 10 to 20% jitter."
  • "A celebrity key overloading one Redis node is a hot key. I'd add a 2-second local cache and spread copies across nodes."
  • "If Redis is down, the database sees 50 times its load, so there are timeouts, a circuit breaker and priority load shedding, and the cache is replicated across zones."

Quantify the blast radius. "At 98% hits the database sees 2,000 queries per second. With a cold cache it would see 100,000, which it cannot serve, so warming and shedding are required, not optional." One line of arithmetic makes the rest of the discussion concrete.

Senior-level extras. Mention retry budgets and jitter, metastable failures (a system that stays down after the trigger is gone), the gutter-pool idea, and testing all of this with game days. Interviewers at senior levels often probe exactly these cascades.

Deep Dive: Probabilistic early expiration and metastable failuresShow

XFetch. Each cached item stores its value, the time it took to compute (delta) and its expiry. On each read, the client recomputes early if now - delta * beta * ln(random()) >= expiry, with beta around 1. Because ln(random()) is negative, the left side is "now plus a random amount scaled by compute time", so recomputation is likely only very close to expiry, and expensive items start refreshing earlier. Under load, exactly one or a few requests refresh before the deadline, with no locks.

Metastable failures. A system can stay broken after the trigger is gone. A brief cache outage drops the hit ratio, the database slows, requests time out and are retried, the cache never refills because loads keep timing out, and the system stays down until load is removed. Research on metastable failures (Bronson et al., 2021; Huang et al., 2022) highlights caches and retries as common causes. Fixes: retry budgets, load shedding, and warming paths that do not depend on the overloaded component.

Gutter pools. Instead of rehashing a failed node's keys onto the remaining nodes (moving load and causing misses), clients send them to a small dedicated pool with short TTLs, which limits load on the database and on other nodes.

Deep Dive: Why overload is non-linear, and how retries amplify itShow

Utilisation and waiting time. A simple queueing model (M/M/1: random arrivals at rate λ, one server with service rate μ) gives the mean time in the system as W = 1 / (μ - λ). Writing utilisation as ρ = λ / μ, that is W = (1/μ) / (1 - ρ). At 50% utilisation, requests take twice the bare service time. At 90% they take 10 times as long, at 99% 100 times. Real databases have many servers (cores, connections), which flattens the curve at moderate load, but the wall near 100% remains. This explains why a database that is "fine" at 60% utilisation collapses quickly when a cache dip pushes it to 95%. Load rises a little, but latency rises a lot.

From latency to concurrency. Little's law (L = λW, the average number of requests in the system equals the arrival rate times the time each spends there) turns that latency into connections and threads. At 5,000 queries per second and 2 ms each, 10 queries are in flight. If latency grows to 200 ms at the same rate, 1,000 are in flight. That exceeds a typical connection pool, so requests queue in the application, which times them out, which triggers retries.

Retry amplification. If each layer of a call chain retries up to r times on failure, a request that fails at the bottom of a chain of d layers can generate up to (r + 1)^d attempts at the bottom. With 3 layers each retrying 3 times, that is 64 database calls for one user request. During an overload most calls fail, so the amplification is close to that worst case, and the extra load arrives exactly when the system has no spare capacity. Defences:

  • Retry at one layer only, usually the outermost or the one closest to the failing dependency, and make the others fail fast.
  • Retry budgets. Allow retries only while they stay under a fixed fraction of successful requests, for example 10%, implemented with a token bucket that refills on successes. In an overload the bucket empties and retries stop on their own.
  • Exponential backoff with jitter. Marc Brooker's AWS Builders' Library article on timeouts, retries and backoff shows that "full jitter" (wait a random time between 0 and the exponential cap) spreads retries best and minimises total work under contention.
  • Deadlines that propagate. Pass the remaining time budget down the call chain, so lower layers do not keep working on requests the user has already abandoned.

Metastability, formally. A system is metastable when it has two stable states under the same load: a good one, where the cache is warm and the database is lightly used, and a bad one, where the cache is cold and the database is saturated by misses and retries. A trigger, such as a cache node failure, moves the system from good to bad. The bad state persists after the trigger is gone because of a sustaining effect, here "misses cause slow loads, and slow loads time out before filling the cache". Bronson and colleagues (HotOS 2021) and Huang and colleagues (OSDI 2022) describe this pattern across many production incidents and stress that the sustaining effect, not the trigger, is what to remove. For caches, the sustaining effects to break are retries without budgets, loads with timeouts shorter than their own duration under load, and warming paths that depend on the overloaded database.

Putting numbers together. A database at 40% utilisation with a 98% cache hit ratio has about 2.5 times headroom. A drop to a 95% hit ratio multiplies misses by 2.5, which puts it at 100%. A cache's hit ratio is therefore part of the database's capacity plan. Alert on hit ratio drops of one or two points, not only on cache errors.

Key Takeaways#

  • A cache hides database weakness; failures in the cache can multiply database load 10-50x in seconds.
  • Stop stampedes with lock-based recompute, request coalescing and early refresh or stale serving.
  • Stop penetration with negative caching and bloom filters; stop avalanches with TTL jitter.
  • Handle hot keys with local caches and replicated copies; split big keys and avoid blocking commands.
  • Plan for cache outages with HA, circuit breakers, load shedding and gradual warming.
  • Herd size is request rate times reload time, and it grows as the database slows. Keep a stale copy with soft and hard expiry.
  • Warming fixes empty caches, not invalidation stampedes. Those need coalescing, locks or in-place updates.
  • Size TTL jitter from the arithmetic: N keys over a J-second window gives N / J reloads per second.
  • Treat the hit ratio as part of database capacity, and keep retries budgeted, backed off and jittered.