Question #11 of 60•Caching•Medium• ~3 min read

How do you prevent Cache Stampede (Thundering Herd) in high-traffic systems?

Executive Takeaway

Understand cache expiration spikes and how to mitigate database overload using single-flight locks, cache warming, and probabilistic expiration.

Architectural Breakdown & AnalysisFAANG Aligned

A Cache Stampede occurs when a popular cache key expires, causing thousands of concurrent read requests to miss the cache and hit the database simultaneously.

Mitigation Strategies

  1. Mutex Locking (Single-Flight Pattern):

When a cache miss occurs, the application acquires a distributed lock (via Redis Redlock). Only the thread holding the lock queries the DB to refresh the cache. Other requests wait brief milliseconds and read the updated cache.

  1. Probabilistic Early Expiration (XFetch Algorithm):

As a key approaches expiration, a probability formula determines whether a read request should trigger a background cache refresh before the key officially dies.

  1. Logical Expiry with Background Refresh:

Set cache keys to never expire physically in Redis. Store a logical timestamp inside the cached object. When the logical expiry passes, serve stale data immediately while dispatching an async worker to update the cache.

TIP — Production Best Practice

Combine Single-Flight Locks with Jittered Expiry Times (e.g. TTL = 300s + random(0-30s)) to prevent synchronous cache key mass expiration.

Key Architectural Comparison

Stampede Mitigation StrategyMechanismDB Load on Cache ExpiryLatency PenaltyBest Use Case
Mutex Lock (Single Flight)Only 1 worker acquires distributed lock to compute DB value.Strictly 1 DB query.Other requests wait 50–200ms for lock release.High-cost SQL aggregations.
Probabilistic Early Expiration (XFetch)Refreshes cache asynchronously before actual TTL based on probability.Near zero DB spikes.Zero wait latency for end users.Top-read viral keys (news, product drops).
Cache Pre-WarmingScheduled cron job hydrates cache before expected traffic drops.Zero peak spikes.Zero user latency.Super Bowl ads, Black Friday sales.
Previous QuestionHow do you design and scale a distributed Rate Limiter?Next Question How do you design a distributed unique ID generator (Twitter Snowflake)?

Continue Learning on Being SDE

Explore deep-dive system architecture modules, low-level object-oriented designs, and interview cheat sheets.