The Midnight Outage: How a Single TTL Triggered a Cascading Failure

Imagine operating an e-commerce platform processing 15,000 requests per second. To protect your PostgreSQL database cluster, you rely heavily on Redis for caching expensive product catalog payloads with a 5-minute Time-To-Live (TTL). Everything operates smoothly—until a flash sale launches. At precisely midnight, the TTL for your most popular product item expires.

In a span of 10 milliseconds, 3,000 concurrent worker threads hit Redis, receive a nil cache miss, and simultaneously attempt to recompute the object by executing complex analytical SQL queries against the primary database. The database connection pool is instantly saturated, CPU utilization spikes to 100%, query latencies balloon from 4ms to 12,000ms, and cascading timeouts trigger circuit breakers across the microservice topology.

This failure pattern is formally known as a Cache Stampede (also referred to as dog-piling or the thundering herd problem). While engineers frequently attempt to solve it using mutex locks or background cron refreshes, these conventional approaches introduce serious edge-case vulnerabilities in high-throughput distributed systems.

Anatomy of a Cache Stampede

Under a standard Cache-Aside pattern, the application flow follows a naive read-through sequence:

  1. Query Redis for key K.
  2. If K exists, return value.
  3. If K is missing, execute heavy DB query, compute value, write back to Redis with TTL, and return.

The vulnerability lies in the gap between the moment key K expires and the moment the first application instance finishes writing the newly computed payload back to Redis. If computing the object takes delta = 500ms, every single request arriving during that 500ms window will initiate an identical, heavy database computation.

Why Naive Distributed Locks (Mutexes) Fall Short

The immediate instinct for senior engineers is to introduce a distributed lock (such as Redis SET NX or Redlock) to ensure only one worker thread recomputes the cache key while others wait or retry.

async function getProductCatalog(productId) {
  const cacheKey = `product:${productId}`;
  let data = await redis.get(cacheKey);
  
  if (data) return JSON.parse(data);

  const lockKey = `lock:${cacheKey}`;
  const acquired = await redis.set(lockKey, 'locked', 'NX', 'PX', 2000);

  if (acquired) {
    try {
      data = await db.queryProductCatalog(productId);
      await redis.set(cacheKey, JSON.stringify(data), 'EX', 300);
      return data;
    } finally {
      await redis.del(lockKey);
    }
  } else {
    // Wait and retry strategy
    await sleep(50);
    return getProductCatalog(productId);
  }
}

While this prevents database overload, it creates severe latency bottlenecks under heavy traffic:

  • Lock Contention & Worker Saturation: Hundreds of incoming HTTP request threads become blocked in sleep-retry loops, consuming web application thread pool memory and increasing tail latency (p99).
  • The Stampede on Lock Expiry: If the worker executing the database query experiences a long Garbage Collection (GC) pause or network jitter exceeding the lock TTL (e.g., 2000ms), the lock expires prematurely. Multiple waiting threads then acquire the lock simultaneously, causing a secondary stampede.
  • Single Point of Failure: Lock management overhead adds extra network round-trips to Redis for every cache miss, degrading throughput.

Enter Probabilistic Early Expiration (The XFetch Algorithm)

To eliminate both database stampedes and distributed lock contention, researchers (Vattani et al., 2013) published a landmark paper introducing Optimal Probabilistic Cache Expiration, widely implemented via the XFetch algorithm.

Instead of waiting for a key to reach its hard TTL expiration, XFetch probabilistically decides whether to recompute the key early whenever it is read by a client. The closer the key gets to its hard expiration, and the longer the computation time (delta) takes, the higher the mathematical probability that an incoming request will trigger an asynchronous, early recomputation.

The XFetch Formula

An early recomputation is triggered if the following inequality evaluates to true:

- delta * beta * ln(rnd()) > (ttl - now)

Where:

  • delta: The time (in milliseconds) it took to compute the value during the last update.
  • beta: An aggressively configurable constant multiplier (beta > 0, default is 1.0). Higher beta values cause early refreshes to happen further in advance of the TTL.
  • rnd(): A pseudo-random floating-point number uniformly drawn from the open interval (0, 1].
  • ttl: The absolute unix timestamp (in milliseconds) when the key hard-expires.
  • ln(rnd()): The natural logarithm of rnd(). Since 0 < rnd() <= 1, ln(rnd()) is always negative or zero, making - delta * beta * ln(rnd()) a positive value.

Production Code Implementation

To implement XFetch, we store the cached payload alongside two key pieces of metadata inside Redis: the computation duration (delta) and the absolute hard expiration timestamp (ttl).

interface CacheEnvelope<T> {
  value: T;
  delta: number; // Execution time in ms
  ttl: number;   // Epoch timestamp in ms
}

async function getWithXFetch<T>(
  redis: RedisClient,
  key: string,
  fetchFn: () => Promise<T>,
  ttlSeconds: number,
  beta: number = 1.0
): Promise<T> {
  const raw = await redis.get(key);
  const now = Date.now();

  if (raw) {
    const envelope: CacheEnvelope<T> = JSON.parse(raw);
    const timeRemaining = envelope.ttl - now;
    
    // Probabilistic early expiration check
    const probabilisticThreshold = -envelope.delta * beta * Math.log(Math.random());

    if (probabilisticThreshold < timeRemaining) {
      // Cache hit: Return value immediately without recomputing
      return envelope.value;
    }
    
    // Probabilistic trigger hit! Recompute early asynchronously or inline
    // Trigger non-blocking background recomputation to avoid blocking current request
    recomputeAndCache(redis, key, fetchFn, ttlSeconds).catch((err) => {
      console.error(`Background XFetch refresh failed for key ${key}:`, err);
    });

    return envelope.value;
  }

  // Hard Cache Miss: Recompute synchronously
  return await recomputeAndCache(redis, key, fetchFn, ttlSeconds);
}

async function recomputeAndCache<T>(
  redis: RedisClient,
  key: string,
  fetchFn: () => Promise<T>,
  ttlSeconds: number
): Promise<T> {
  const startTime = Date.now();
  const data = await fetchFn();
  const delta = Date.now() - startTime;
  const ttlEpoch = Date.now() + (ttlSeconds * 1000);

  const envelope: CacheEnvelope<T> = {
    value: data,
    delta: delta,
    ttl: ttlEpoch
  };

  // Set with a buffer on Redis TTL so key doesn't get evicted before envelope ttl
  await redis.set(key, JSON.stringify(envelope), 'EX', ttlSeconds + 60);

  return data;
}

How XFetch Behaves Under Load

Let us analyze the mathematical dynamics during production traffic:

  1. Far from Expiration (Large timeRemaining): Math.log(Math.random()) yields values typically between -0.1 and -4.0. If delta = 200ms, probabilisticThreshold ranges between 20ms and 800ms. If 200 seconds remain before TTL, the condition evaluates to false 100% of the time. Zero overhead incurred.
  2. Approaching Expiration (Small timeRemaining): When timeRemaining drops to 150ms, a single incoming request out of hundreds will randomly sample a high -ln(rnd()) multiplier, causing probabilisticThreshold to exceed 150ms. That single request kicks off an asynchronous background refresh.
  3. Self-Healing Convergence: Once the background refresh completes and updates Redis with the fresh payload and new TTL, subsequent requests immediately read the updated envelope, resetting the probabilistic probability back to zero.

Tuning Beta and Production Operational Guardrails

While XFetch eliminates dog-piling, fine-tuning its execution parameters is required to prevent over-computation:

  • Setting Beta: For high-traffic keys where data computation is very expensive, set beta = 1.5 or 2.0 to favor earlier background refreshes. For lightweight queries, keep beta = 1.0.
  • Decoupling Redis TTL from Envelope Expiration: Always set the native Redis TTL (e.g., EX) slightly longer than the internal envelope TTL (e.g., ttlSeconds + 60). This guarantees that even if a key passes its soft TTL, the old value remains accessible in Redis to serve concurrent readers while background workers finish refreshing.
  • Combining with Background Singleflight: If your application experiences extreme concurrency (e.g., 50,000 req/sec per node), combine XFetch with an in-memory singleflight group (in Go or Node) on the local process node to ensure that even background probabilistic updates execute exactly once across threads on the same host instance.

Key Takeaways

  • Cache Stampedes are Architectural Risks: Relying on hard TTL expiration with standard Cache-Aside will inevitably cause database connection pool exhaustion during peak traffic events.
  • Distributed Mutexes introduce Tail Latency: Lock-based approaches introduce sleep-retry loops, lock timeout edge cases, and high thread pool overhead under load.
  • Probabilistic Early Expiration (XFetch) eliminates lock contention: By evaluating mathematically when to refresh keys before hard expiration, XFetch guarantees smooth, zero-downtime cache updates with zero lock overhead.
  • Operational Alignment: Store computation delta alongside payload metadata and ensure Redis hard TTL exceeds internal envelope expiration to achieve seamless stale-while-revalidate performance.