
When system design interviews move past surface-level architecture boxes, interviewers rarely stop at "Where would you put Redis?" Instead, they present a cascading production failure: "Your e-commerce API caches product catalog pages in Redis with a 15-minute TTL. During a flash sale, a single flagship item receives 18,000 requests per second. At 00:15:00, the cached key expires. Within 400 milliseconds, PostgreSQL connection pools saturate at 100%, p99 latency jumps from 12 milliseconds to 9 seconds, and retry storms take down unrelated checkout endpoints. Why did adding a fast in-memory cache fail to protect the database, and how do you redesign the caching layer?"
Candidates who reply "just increase the Redis TTL to 24 hours" or "scale up the Redis cluster" miss the core failure mode tested in a redis caching strategies cache stampede interview. A cache stampede—also called a thundering herd—is a concurrency and coordination failure, not a Redis throughput bottleneck. When thousands of application workers observe the same cache miss simultaneously, every worker recomputes the expensive database query in parallel, crushing the origin store right when traffic peaks.
Handling distributed caching trade-offs with precision separates senior backend engineers from candidates who treat Redis as magic glue. For broader preparation across distributed architecture loops, anchor these patterns inside a structured technical interview preparation plan. This guide breaks down the four primary caching topologies, concurrency race conditions, cache stampede defenses, eviction policies, and a step-by-step live interview walkthrough.
Core Redis Caching Strategies Compared
Interviewers expect candidates to articulate cache aside vs write through mechanics—alongside read-through and write-behind—by tracing exact network hops, consistency windows, and failure modes.

1. Cache-Aside (Lazy Loading)
In Cache-Aside, the application code orchestrates both Redis and the primary database directly:
- Read Path: The service queries Redis (
GET product:42). On a hit, it returns the serialized payload immediately. On a miss, it queries PostgreSQL, writes the result back to Redis with a TTL (SET product:42 ... EX 900), and returns the response. - Write Path: The service writes to PostgreSQL first, then deletes (
DEL product:42) rather than updates the cached key so subsequent reads lazy-load fresh state.
Why do teams prefer DEL over SET on writes? Under concurrent updates (Worker A and Worker B updating the same row), overwriting the cache risks an out-of-order write race where Worker A finishes its database write first, pauses, and overwrites Worker B's newer cache value with stale data. Deleting the key narrows that window, though a subtle read-modify-write race can still occur if a concurrent reader caches stale pre-commit data right before the writer invalidates it.
2. Read-Through Caching
In Read-Through, the application talks only to a caching provider or proxy layer, which is responsible for fetching from the database on a miss and populating itself. Redis itself is not natively a read-through database connector without a middleware layer (such as RedisGears or a dedicated data-access proxy). Read-through simplifies application handlers and centralizes coalescing logic, at the cost of coupling cache availability tightly to the middleware proxy.
3. Write-Through Caching
In Write-Through, every write goes to the cache layer first (or through the cache middleware), which synchronously persists the update to the backing database before returning success to the caller.
- Advantage: Cached state stays strongly aligned with database state, and newly written items are immediately warm for reads.
- Trade-Off: Every write incurs two sequential network hops (
App -> Cache -> DB), increasing write tail latency and polluting Redis memory with rarely read records unless paired with strict TTLs or eviction tuning.
4. Write-Behind (Write-Back) Caching
In Write-Behind, the application writes only to Redis and receives an immediate acknowledgment. An asynchronous background worker batches dirty keys and flushes them to PostgreSQL or analytical storage on a schedule.
- Advantage: Absorbs extreme write bursts (such as view counters, IoT telemetry, or leaderboard increments) and coalesces multiple updates to the same key into a single database statement.
- Trade-Off: Introduces real durability and data-loss risk if a Redis primary fails before AOF persistence or asynchronous queue replication flushes dirty entries. Financial ledgers and order checkout state almost never belong in write-behind caches without durable write-ahead logs like Kafka.
Caching Strategy Trade-Off Matrix for System Design Interviews
Use this rubric when defending caching architecture choices in a system design interview:
| Caching Strategy | Read Path Flow | Write Path Flow | Consistency & Staleness Risk | Latency Profile | Primary Failure Mode | Best Workload Fit |
|---|---|---|---|---|---|---|
| Cache-Aside | App checks Redis; on miss, reads DB and populates Redis | App writes DB, then invalidates (DEL) cache key | Eventual; brief stale window during concurrent read/write races | Fast cache hits; cold miss pays DB + Redis round trip | Cache stampede on hot key expiration; cold-start DB load | Read-heavy catalogs, user profiles, session metadata |
| Read-Through | App reads proxy/cache; proxy loads DB on miss | App writes DB directly (often paired with invalidation) | Similar to Cache-Aside unless proxy coordinates locks | Uniform caller code; miss pays proxy + DB latency | Proxy becomes a single hop bottleneck if under-provisioned | Microservices standardizing data-access and coalescing |
| Write-Through | App reads cache; warm keys hit immediately | Cache synchronously updates DB before returning ACK | High freshness; cache and DB stay synchronized | Higher write latency (2 synchronous hops); fast reads | Unread writes consume expensive RAM; dual-write partial failures | Configuration flags, entitlement checks, low-churn lookups |
| Write-Behind | App reads hot values directly from cache | App writes Redis (ACK), async worker batches to DB | Eventual; reads reflect latest state, DB lags behind | Ultra-fast write ingestion; amortized DB I/O | Permanent data loss if Redis node crashes pre-flush | Like counters, real-time analytics, gaming telemetry |
Anatomy of Three Cache Failures: Stampede, Avalanche, and Penetration
Interviewers frequently bundle three distinct failure patterns under Redis troubleshooting questions. Naming each precisely shows deep operational fluency.

1. Cache Stampede (Hot-Key Expiration / Thundering Herd)
A cache stampede happens when one extremely popular key expires (or gets evicted) and thousands of concurrent requests miss simultaneously, triggering identical redundant database queries or heavy aggregations.
2. Cache Avalanche (Synchronized Mass Expiration)
A cache avalanche occurs when thousands of distinct keys expire at the exact same moment—for example, after warming 500,000 homepage product cards during a midnight deploy with an identical EX 3600 TTL—or when a Redis shard restarts without persistence. Unlike a single hot key, an avalanche floods the database with thousands of unique queries at once. Pairing caching boundaries with disciplined rate limiting algorithms in system design prevents retry storms from compounding the outage.
3. Cache Penetration (Non-Existent Key Flood)
Cache penetration occurs when malicious traffic or buggy clients repeatedly request keys that exist in neither Redis nor PostgreSQL (such as GET /users/-99999 or random UUIDs). Because no record exists in the database, nothing ever gets cached, so 100% of those requests punch straight through Redis into the database.
Four Production Defenses Against Cache Stampedes
When answering a thundering herd redis mitigation prompt, propose layered defenses based on traffic shape and operational complexity.
Defense 1: TTL Jitter (Stopping Cache Avalanches)
Never assign fixed uniform TTLs to bulk-loaded keys. Adding bounded random jitter spreads expirations evenly across time:
import random
def compute_ttl_with_jitter(base_ttl_seconds: int = 900, max_jitter_seconds: int = 180) -> int:
# Spread expirations across a 3-minute window to avoid synchronized avalanches
return base_ttl_seconds + random.randint(0, max_jitter_seconds)
Interview Caveat: Point out explicitly that TTL jitter solves cache avalanches (many keys expiring together), not a single hot-key cache stampede. Even with jitter, product:flagship still expires at one specific timestamp.
Defense 2: In-Process singleflight + Distributed Redis Mutex
To stop 10,000 workers from querying PostgreSQL for the same expired key, coalesce duplicate misses in two tiers:
- Per-Instance Request Coalescing (
singleflight): Inside each application pod (using Go'sgolang.org/x/sync/singleflightor an in-memory promise map in Node/Python), if 400 coroutines on the same pod ask forproduct:42concurrently, only one coroutine proceeds to Redis/DB while the other 399 await the same shared result. - Cross-Pod Distributed Lock (
SET NX PX) with Double-Check: Across 50 application pods, use an atomic Redis lock so only one pod queries PostgreSQL while peers briefly backoff and re-read Redis:
import json
import time
import uuid
def get_product_coalesced(redis_client, db_client, product_id: str) -> dict | None:
cache_key = f"product:{product_id}"
cached = redis_client.get(cache_key)
if cached is not None:
# Handle negative cache sentinel for non-existent IDs
return None if cached == "__NULL__" else json.loads(cached)
lock_key = f"lock:{cache_key}"
lock_token = str(uuid.uuid4())
# Atomic acquire with 3-second lease so crashed workers cannot deadlock readers
acquired = redis_client.set(lock_key, lock_token, nx=True, px=3000)
if acquired:
try:
row = db_client.fetch_product(product_id)
if row is None:
# Negative caching stops cache penetration with a short TTL
redis_client.set(cache_key, "__NULL__", ex=60)
return None
redis_client.set(cache_key, json.dumps(row), ex=compute_ttl_with_jitter())
return row
finally:
# Release lock only if token matches (prevents deleting another worker's lock)
lua_release = """
if redis.call("get", KEYS[1]) == ARGV[1] then
return redis.call("del", KEYS[1])
else
return 0
end
"""
redis_client.eval(lua_release, 1, lock_key, lock_token)
else:
# Wait briefly and retry cache read (avoid tight spin-loops)
time.sleep(0.03)
retry_cached = redis_client.get(cache_key)
if retry_cached is not None:
return None if retry_cached == "__NULL__" else json.loads(retry_cached)
# Fallback if lock holder timed out or failed
return db_client.fetch_product(product_id)
Notice two subtle details interviewers love: using a unique lock_token with a Lua compare-and-delete so a slow worker whose 3-second lease expired never deletes a successor's lock, and caching a "__NULL__" sentinel (ex=60) to neutralize cache penetration.
Defense 3: Probabilistic Early Expiration (XFetch Algorithm)
Even with distributed locks, waiting threads still suffer a latency bump during recomputation. The XFetch algorithm eliminates cold waits altogether by letting a single lucky request asynchronously or inline refresh a hot key slightly before its TTL reaches zero.
Each cached entry stores (value, recompute_delta_ms) alongside its logical expiration timestamp expiry:
import math
import random
import time
def should_refresh_early(expiry_ts: float, delta_ms: float, beta: float = 1.0) -> bool:
now = time.time()
delta_sec = delta_ms / 1000.0
# Probability of returning True rises exponentially as (expiry_ts - now) approaches 0
gap = -delta_sec * beta * math.log(random.random())
return (now + gap) >= expiry_ts
Because random.random() follows a uniform distribution on (0, 1], -ln(rand()) yields an exponential distribution. Only requests arriving very close to expiry_ts—proportional to how expensive delta_ms is to recompute—trigger an early refresh. One worker updates the TTL back to 15 minutes, and the herd never sees a cache miss.
Defense 4: Stale-While-Revalidate + Background Refresh
For ultra-low-latency feeds or catalog endpoints where 5-second staleness is acceptable, store a logical soft TTL inside the JSON payload (soft_expires_at = now + 300s) while setting the Redis physical TTL much longer (EX 3600). When a worker reads an entry past soft_expires_at, it immediately returns the stale payload to the client and dispatches a single deduplicated background job (or Redis Stream event) to refresh the key. Tail latency stays flat at 1–2 milliseconds even during database maintenance windows.
Redis Eviction Policies: LRU vs LFU vs volatile-ttl
A classic follow-up in a redis caching strategies cache stampede interview tests what happens when Redis maxmemory fills up before keys expire: "Suppose Redis hits 100% memory during a traffic spike. Which maxmemory-policy do you configure, and why can the wrong choice trigger a hidden stampede?"
Explain the redis eviction policies lru vs lfu trade-offs clearly:
noeviction(Default Trap): Redis rejects allSETandINCRwrites withOOM command not allowed. Useful only when Redis acts as a primary persistent queue or lock store where dropping keys causes correctness bugs—dangerous for pure caches because new hot items can never be warmed.allkeys-lru(Least Recently Used): Evicts keys that have not been accessed recently, using approximated sampling (maxmemory-samples 5by default). Weak spot: a sequential background batch job scanning millions of cold historical records touches each key once, polluting recency metadata and evicting genuinely popular keys—causing sudden cache stampedes on hot traffic.allkeys-lfu(Least Frequently Used, Recommended for Skewed Read Caches): Tracks access frequency using a 24-bit Morris probabilistic counter combined with logarithmic decay. One-off crawler scans cannot displace a hot flagship product key with a high frequency counter.volatile-lru/volatile-ttl: Restricts eviction strictly to keys that have an explicitTTLset (EXPIRE). Valuable when sharing one Redis deployment between persistent feature flags (no TTL) and ephemeral cached queries (with TTL)—though isolating critical lock/session keys onto a dedicated Redis instance is safer at scale.
Also watch for Redis Cluster hot-key skew: if a single key (product:flash_sale) receives 150,000 QPS, all traffic hashes to one Redis shard (CRC16(key) % 16384). Mitigate hot-shard saturation by pairing Redis with a local L1 in-process cache (e.g., 2-second TTL inside each app pod) or key salting/sharding (product:flash_sale#0 through #9, read randomly), mirroring the partition-skew trade-offs examined in database sharding and partitioning strategies and scaling an application to 1 million requests per second.
Interview Walkthrough: Answering a Flash-Sale Caching Prompt
Suppose an interviewer asks: "Design the caching architecture for a flash-sale inventory & product page serving 80,000 read QPS and 2,000 inventory decrement QPS. How do you prevent cache stampedes and stale overselling?"
Deliver a structured four-part answer:
- Separate Static Catalog State from Mutable Inventory: Do not cache inventory counts inside the heavy product description JSON blob. Store product descriptions, specs, and reviews in a Cache-Aside + L1 local cache (2s TTL) with XFetch early refresh and TTL jitter (
900s + rand(0..120s)). Because catalog metadata tolerates brief staleness, readers experience zero stampedes. - Route Authoritative Inventory Through Atomic Operations or Strict Write Discipline: Never rely on a 15-minute cached integer to approve checkout decrements—that causes overselling. Keep authoritative stock in PostgreSQL (or pre-allocated Redis Lua
DECRBYreservations backed by durable event logs), while syncing read-only "In Stock / Sold Out" display badges via Write-Through or event-driven invalidation. If heavy database filtering precedes caching, verify backing queries rely on proper indexes covered in PostgreSQL B-Tree vs GIN indexing optimization. - Protect the Origin Against Stampedes and Penetration: Wrap catalog miss paths in per-pod
singleflight+ distributed RedisSET NX PXlocks with a 60-second"__NULL__"sentinel for invalid product IDs. Configuremaxmemory-policy allkeys-lfuso bot crawls scanning invalid or archival IDs cannot evict hot flash-sale entries. - Plan Graceful Degradation: If Redis becomes unreachable, fail open carefully by engaging circuit breakers and concurrency semaphores in front of PostgreSQL so slow origin queries return
429/503fast rather than exhausting worker threads.
Common Mistakes Candidates Make in Redis Caching Rounds
Hiring rubrics quickly catch shallow memorization when candidates overlook operational realities. Avoid these four pitfalls:
- Using Redis
KEYS *in Production Invalidations: CallingKEYS prefix:*blocks the single-threaded Redis event loop for hundreds of milliseconds or seconds on large keyspaces, simulating a self-inflicted outage. Always maintain explicit key sets, versioned namespace prefixes (v4:product:42), or incrementalSCAN. - Ignoring Serialization and Large-Key Payload Bloat: Caching 4 MB serialized blobs under a single key saturates network interface bandwidth and blocks Redis's main thread during
GET/DEL. Compress large payloads, project only required fields, or useUNLINKinstead ofDELso Redis frees memory asynchronously in a background thread. - Assuming Redis Transactions (
MULTI/EXEC) Are Rollback-Safe: Redis does not roll back earlier commands in aMULTI/EXECblock if a later command fails at runtime; use Lua scripts (EVALSHA) when atomic read-check-modify semantics are mandatory. - Forgetting Cold-Start Warming After Failover: Deploying an empty Redis cluster into full production traffic triggers an instant cache avalanche. Warm top-K hot keys from read replicas or snapshot backups before shifting production load balancers—a checklist habit reinforced in any 7-day system design interview crash course.
Practice Redis Architecture & Failure Debugging Under Interview Pressure
Explaining singleflight, XFetch, and allkeys-lfu cleanly from static notes is only half the battle; top-tier offers come from defending latency budgets and consistency trade-offs aloud when an interviewer changes traffic constraints mid-answer.
Put these distributed caching concepts into active rehearsal:
- Test your instant technical recall across Redis, database internals, and concurrency patterns with the free 60-Second Job Blitz—no login required.
- Practice realistic voice and text system design mock interviews tailored to your target backend or staff engineering role, complete with Socratic follow-up probes and structured scoring rubrics, on totop.app Pricing & Plans.
Practice Staff Backend Engineer Questions Live with AI Mock Interviews
Turn any job description across Engineering, DevOps, Data, Marketing, Sales, Finance, or HR into a personalized test and live voice or text AI mock interview on totop.app, or test your speed right now in the 60-Second Staff Backend Engineer Blitz.
Play 60s Staff Backend Engineer Blitz (Free, No Login) | Start 14-Day Free Trial | Browse All Interview Guides