Distributed Cache Architectures: Stale-While-Revalidate, Cache Stampede Protection, and Redis Tag Invalidation
How to build high-concurrency caching tiers: probabilistic early expiration (XFetch), distributed mutex locks, and targeted cache-tag purging.
Caching is trivial until a hot key expires under high traffic, triggering a Cache Stampede (Thundering Herd) that overwhelms backend databases. Modern distributed caching architectures avoid synchronous cache misses by combining Stale-While-Revalidate patterns, probabilistic early recomputation (the XFetch algorithm), and Redis tag invalidation sets.
THE PRODUCTION PROBLEM STATEMENT
When a popular cached item (like a viral product page or homepage feed) expires under 10,000 requests per second, thousands of requests simultaneously find a cache miss and execute the identical expensive database query, crashing the primary database within milliseconds.
How Does Probabilistic Early Expiration (XFetch) Work?
Rather than waiting for a key to strictly hit its TTL, the XFetch algorithm computes a probabilistic decision based on the remaining TTL, the delta time it takes to compute the value, and a randomness constant.
As the key nears expiration, a single lucky client probabilistically triggers a background refresh while still serving the cached value immediately to all other clients, completely preventing stampedes.
import Redis from 'ioredis';
interface CacheItem<T> {
value: T;
delta: number; // Duration to compute value in milliseconds
expiry: number; // Unix timestamp
}
export async function xfetch<T>(
redis: Redis,
key: string,
ttlSeconds: number,
computeFn: () => Promise<T>,
beta: number = 1.0 // Randomness scaling factor
): Promise<T> {
const raw = await redis.get(key);
const now = Date.now();
if (raw) {
const item = JSON.parse(raw) as CacheItem<T>;
// XFetch probabilistic calculation:
// now - delta * beta * ln(random()) > expiry
const shouldRecompute = now - item.delta * beta * Math.log(Math.random()) > item.expiry;
if (!shouldRecompute) {
return item.value; // Cache hit!
}
// Asynchronously refresh in background without blocking current request!
refreshInBackground(redis, key, ttlSeconds, computeFn);
return item.value;
}
// Cold cache miss: compute synchronously
return await executeComputeAndSet(redis, key, ttlSeconds, computeFn);
}How to Implement Surgical Cache-Tag Purging in Redis?
Keys are indexed into Redis Sets by tags (e.g. tag:user:123). When a mutation occurs, the server fetches the tag set and deletes all associated keys in a single atomic pipeline.
This allows multi-page cache purging without broad, dangerous KEYS * or SCAN commands that lock Redis.
// Anti-Pattern: Triggers stampede when key expires under high load
let data = await redis.get(key);
if (!data) {
data = await db.heavyQuery(); // 5,000 concurrent requests hit DB!
await redis.set(key, data, 'EX', 60);
}// Recommended: Only ONE worker refreshes cache; others get stale value
const data = await xfetch(redis, key, 300, () => db.heavyQuery());[PROBABLE CAUSE] Using KEYS * in production to find keys to invalidate, which blocks the single-threaded Redis event loop.
[VERIFIED RESOLUTION] Store key names in dedicated Redis Sets keyed by cache tag, and purge using SMEMBERS with UNLINK (non-blocking delete).
redis.unlink(...keys)Frequently Asked Questions & Technical Inquiries
Direct, practical answers to common architectural and debugging questions.
DEL synchronously frees memory on the main thread, blocking commands. UNLINK unbinds the key immediately in O(1) time and reclaims memory asynchronously in background threads.
Faisal Askari
Verified AuthorSoftware Engineer & Full-Stack Developer
Faisal Askari is a software engineer with deep expertise in web systems architecture, the JavaScript runtime ecosystem, and client-side performance engineering. Over years of hands-on production engineering, he has designed and shipped enterprise dashboards, high-converting digital interfaces, and specialized full-stack applications.
High-Concurrency Full-Stack Architecture
Scaling backend services, database clusters, or caching layers for high-traffic products?
Resilient Full-Stack Architecture: Idempotent APIs, Optimistic UI, and Cache Invalidation
Engineering robust distributed state between client and server: idempotency keys, safe optimistic rollbacks, exponential backoff with jitter, and cache coherence.
Server-Sent Events (SSE) vs WebSockets over HTTP/2: Choosing the Right Real-Time Streaming Architecture
Why HTTP/2 multiplexing made Server-Sent Events the modern standard for LLM token streams and live telemetry over complex WebSockets.