
Master distributed caching in system design interviews: cache-aside, write-through, probabilistic early expiration, and cache stampede mitigation rubrics.
Most distributed backends operate comfortably until a sudden traffic spike or cache node eviction exposes a slow SQL query beneath an otherwise resilient API layer. In senior and staff system design interviews, candidates frequently jump to the whiteboard and declare "we will just put Redis in front of the database" without modeling cache invalidation races or failure domain cascading. When evaluation committees review candidate leveling dossiers, treating distributed caching as a magical latency cure without explaining cache invalidation mechanics or stampede defenses is a primary driver of downleveling.
Distributed caching improves read throughput and isolates persistent datastores by storing serialized precomputed records in volatile high-speed memory clusters, but requires deliberate synchronization protocols, eviction policies, and stampede containment strategies to prevent cascading database outages.
Before committing to a caching pattern on a system design whiteboard, senior engineers evaluate four operational boundaries:
| Caching Pattern | Read Path Mechanics | Write Path Mechanics | Consistency Guarantee | Primary Failure Domain |
|---|---|---|---|---|
| Cache-Aside (Lazy Loading) | App checks cache; on miss, queries DB and populates cache | App writes directly to DB; invalidates or updates cache entry | Eventual consistency; stale reads possible during race conditions | Cache stampede on TTL expiration of high-QPS keys |
| Write-Through | App reads directly from cache; misses populate cache | App writes to cache; cache synchronously writes to DB | Strong consistency for cached reads; zero stale data | Increased write latency; requires dedicated cache storage plugin |
| Write-Behind (Write-Back) | App reads directly from cache | App writes to cache asynchronously; cache flushes batches to DB | Eventual consistency; high risk of data loss on cache crash | In-flight data loss if Redis or Memcached node crashes before flush |
| Refresh-Ahead | App reads from cache; cache auto-reloads expiring keys | App writes to DB; background worker monitors access frequency | High availability for predictable reads; low latency | Unnecessary compute overhead if predicted key traffic drops abruptly |
Cache-aside delegates cache coordination directly to application workers, whereas write-through requires the cache layer to synchronously mediate database persistence.
In cache-aside architecture, the application server acts as the primary coordinator. When a client executes a read request, the service inspects Redis or Memcached. If the key exists (cache hit), the serialized payload returns immediately. If the key is absent (cache miss), the application queries the relational database, writes the result into the cache with a specified Time-to-Live (TTL), and returns the payload to the client.
[Cache-Aside Read Flow]
Client ---> App Server ---> (1. Check Cache) ---> Redis
| |
| (2. Cache Miss: Query DB) | (Cache Hit: Return Data)
v v
PostgreSQL <--- (3. Populate Cache) <---- App
The greatest advantage of cache-aside is architectural resilience: if the distributed cache cluster crashes, the application can degrade gracefully by falling back directly to primary database replicas.
However, write operations in cache-aside introduce concurrency races. To update an existing record, the application should write to the database first and then delete (invalidate) the cached key, rather than attempting to update the cached value in place. Deleting the key forces the next read request to fetch fresh data, preventing race conditions where two concurrent writes overwrite each other in an out-of-order sequence.
In contrast, write-through architectures route all client writes directly into the cache. The caching system itself synchronously writes the updated record to the underlying database before returning HTTP 200 OK to the client. This guarantees that data is never stale, but incurs double-write latency and requires tight infrastructure coupling between the cache and datastore engines.
You can cross-reference our System Design Interview Architecture Guide for structuring these trade-off matrices during your opening interview minutes.
A cache stampede occurs when a high-throughput key expires simultaneously for thousands of concurrent requests, overwhelming the persistent datastore with redundant recalculations.
Consider an e-commerce platform where a product catalog record serves 20,000 queries per second with a 60-second TTL. At second 61, the cached key expires. Within a single 50-millisecond window, hundreds of incoming application threads detect a cache miss. Every single thread independently issues a complex SQL join query to PostgreSQL to rebuild the cached payload.
[Thundering Herd Failure Scenario]
Incoming Traffic (20,000 QPS)
|
v
[Cached Key Expires at T=60s]
|
+---> Thread 1: Miss ---> Query DB \
+---> Thread 2: Miss ---> Query DB |---> PostgreSQL Connection Pool Exhaustion
+---> Thread 3: Miss ---> Query DB |---> CPU Spikes to 100%
+---> Thread N: Miss ---> Query DB / ---> Cascading 504 Gateway Timeouts
This sudden surge exhausts database connection pools, drives CPU utilization to 100%, and creates high latency ripples that trigger upstream circuit breakers.
Staff and principal candidates must demonstrate mastery of the three industry-standard solutions to prevent cache stampedes:
When a worker encounters a cache miss, it attempts to acquire a short-lived distributed lock (for example, using Redis SET key value NX PX 5000). Only the single worker that acquires the lock queries the database and repopulates the cache. All other concurrent workers wait briefly or return a stale cached value until the lock holder completes the refresh.
Instead of waiting for a hard TTL to expire, read requests dynamically calculate whether to refresh the key ahead of expiration based on read frequency and computation cost. As detailed in the academic research behind the XFetch algorithm, the application computes:
// Illustrative Probabilistic Early Refresh Logic
function shouldRefreshEarly(remainingTTL, computeCostDelta, beta = 1.0) {
// If remaining TTL is less than a probabilistic factor of compute cost, trigger refresh
const randomValue = Math.random();
return -computeCostDelta * beta * Math.log(randomValue) >= remainingTTL;
}
If the probabilistic threshold is crossed, a single worker thread refreshes the cached record in the background while continuing to serve the existing cached value to concurrent users.
For predictable hot keys (such as home page feeds or trending product lists), scheduled cron workers or streaming event consumers recompute and refresh cached values long before their expiration timers elapse, eliminating client-triggered database recomputations entirely.
Cache eviction policies determine which records are purged from RAM when storage consumption reaches hard operational thresholds.
In distributed caches like Redis, memory is finite and expensive. When memory utilization reaches maxmemory, the system must evict keys based on configured algorithmic policies:
Evicts keys that have not been accessed for the longest duration. LRU is the industry default for most web workloads because recent access is the strongest statistical predictor of future access. Redis approximates LRU by sampling a configurable number of random keys (typically 5 to 10) and evicting the oldest key among the sample, avoiding the memory overhead of maintaining global linked lists.
Evicts keys with the lowest total access frequency counts, regardless of when they were last touched. LFU prevents a sudden batch scan of historical records from evicting hot, frequently requested items from the working set.
Evicts keys with the shortest remaining TTL values among those configured with expiration deadlines (volatile-ttl). Keys without an explicit expiration are retained indefinitely.
During an interview, explicitly explain memory sizing math: if your active user working set comprises 50 million records, each averaging 1.5 kilobytes of serialized JSON, your cache cluster requires at least 75 gigabytes of pure memory, plus an additional 25% buffer for hash table overhead and Redis replication buffers. You can pair this with our guide on Consistent Hashing and Database Sharding to show how memory partitions scale horizontally across shard nodes.
Interview loops frequently test whether candidates understand the critical distinctions between cache penetration, cache breakdown, and cache avalanche failure modes.
Junior candidates frequently conflate these three failure mechanisms. Precision in defining and resolving each pattern separates senior engineers from junior candidates:
Failure Mode Comparison:
1. Cache Penetration: Requests for NONEXISTENT keys bypass cache -> hits DB repeatedly.
Solution: In-memory Bloom Filter or caching null values with short TTL.
2. Cache Breakdown: A SINGLE ultra-hot key expires -> thundering herd hits DB.
Solution: Distributed mutex lock or probabilistic early expiration (XFetch).
3. Cache Avalanche: MANY keys expire simultaneously or entire cache node dies.
Solution: Add random jitter to TTLs (+/- 10%) and multi-node Redis Sentinel/Cluster.
When malicious actors or misconfigured scrapers query random IDs that do not exist in the database (e.g., GET /users/nonexistent_uuid), every query misses the cache and hits the persistent database.
To eliminate this vulnerability, engineers deploy a Bloom filter in front of the cache. A Bloom filter is a space-efficient probabilistic data structure that deterministically confirms whether an element definitely does not exist in the dataset, dropping invalid queries before they touch either the cache or the database.
When thousands of keys are batch-loaded into Redis at midnight with an identical 24-hour expiration timer, every single key expires precisely at midnight tomorrow, causing an avalanche of database traffic.
Senior engineers prevent this by introducing randomized TTL jitter:
// Applying randomized TTL jitter to prevent synchronized key expiration
const baseTTLSeconds = 86400; // 24 hours
const jitterSeconds = Math.floor(Math.random() * 3600); // Random offset up to 1 hour
const finalTTL = baseTTLSeconds + jitterSeconds;
await redis.set(`user:${userId}`, JSON.stringify(userData), 'EX', finalTTL);
By scattering key expirations across a continuous time window, database read traffic remains a steady baseline rather than an unmanageable spike.
Reliable cache invalidation requires decoupling write execution from cache synchronization using transactional Change Data Capture.
The classic trap in cache maintenance is updating the database and immediately attempting to update the cache within the same application process:
// Fragile Application-Level Dual Write
async function updateUserProfile(userId, updates) {
await db.query("UPDATE users SET name = $1 WHERE id = $2", [updates.name, userId]);
// What happens if the network drops or the process crashes right here?
await redis.del(`user:${userId}`);
}
If the application node experiences an out-of-memory crash or network partition immediately after executing the SQL update, the cache key is never deleted. The cache now serves stale data to users until the key natural TTL expires.
To guarantee eventual consistency at scale, modern architectures rely on Change Data Capture (CDC) pipelines using tools like Debezium and Apache Kafka:
App Writes ---> PostgreSQL Primary
|
(WAL Log Stream)
v
Debezium CDC Connector
v
Kafka Topic
v
Cache Invalidation Consumer ---> Redis DEL user:{id}
The database Write-Ahead Log (WAL) acts as the single source of truth. The CDC worker consumes committed transaction logs and issues invalidation commands to Redis asynchronously. If the invalidation worker temporarily fails, Kafka message offsets ensure that every cache invalidation is eventually processed with zero dropped events.
For senior engineers preparing for architectural screens, review our breakdown on Technical Screen Signal Rubrics and explore active backend leadership positions on The Job Craft Job Board. In our companion career playbook, discover how to protect your compensation and equity during organizational restructuring in Tech Layoff Severance Playbook.
Direct takeaways and practical clarifications from this guide.