Caching Strategies and Distributed Caching Questions
Using caches to reduce latency and load: cache-aside, read-through, write-through, and write-behind patterns, TTLs, eviction policies, and distributed caches such as Redis or Memcached. Covers cache invalidation, stampede and thundering-herd protection, and the consistency tradeoffs of caching. Focuses on where and how to cache across tiers.
At extreme scale, a single cache miss for a hot key can overload the origin. Propose a comprehensive defense-in-depth strategy to prevent stampedes: singleflight, background regeneration, early recompute, probabilistic TTLs, prewarmed hot key paths, and rate limiting. Explain how to orchestrate these across many app instances.
Sample Answer
Direct answer
At extreme scale you cannot rely on a single stampede defense. Combine request coalescing (only one request repopulates a hot key while others wait), background/proactive refresh before expiry, probabilistic early expiration, jittered time-to-live (TTL) values, and origin rate limiting as a last-resort backstop, coordinated so all application instances agree on who is allowed to refresh a given key at once.
Structured elaboration
- Request coalescing (singleflight): on a cache miss, the first request acquires a short-lived lock (e.g.,
SETNXin Redis) for that key and fetches from origin; concurrent requests for the same key either block briefly on a notification channel (pub/sub or polling with backoff) or serve a stale value if one exists. This bounds concurrent origin load per key to roughly one in-flight fetch, regardless of instance count, because the lock lives in the shared cache, not in any one process. - Probabilistic early expiration: instead of a hard expiry, each read close to TTL end recomputes with a small, increasing probability (a common formula is P(refresh)=e−β⋅(texpiry−tnow)/δ where δ is the time it took to compute the value and β tunes aggressiveness). This spreads refreshes across many requests instead of concentrating them at the exact expiry instant.
- Jittered TTLs: add randomized jitter (e.g., base TTL plus/minus 10 to 20 percent) so keys written around the same time do not all expire in the same millisecond, which is what turns an ordinary cache miss into a correlated stampede across thousands of keys at once (a cache avalanche).
- Background/prewarmed refresh: a scheduled worker (or the request that detects "close to expiry") refreshes hot keys proactively so the TTL rarely actually lapses for high-traffic keys; this trades a small amount of continuous background load for eliminating stampede risk on the hottest paths.
- Origin rate limiting as a backstop: even with the above, cap concurrent origin requests per key (or per origin endpoint) so a defense-in-depth failure degrades gracefully into serving stale data or a fast error instead of taking the origin down.
- Orchestrating across many app instances: the lock, the "who refreshes next" decision, and the notification of waiters must live in the shared cache (Redis) or a coordination service, not in in-process state, because coalescing only works if every instance agrees on a single winner per key.
Worked example
Say a hot key normally takes 200 ms to recompute and serves 5,000 requests per second (RPS) at peak. Without any defense, if it expires with no coalescing, the next ~1,000 requests in that 200 ms window (5,000 RPS times 0.2 s) would all miss and hit the origin simultaneously; a database that comfortably serves single-digit concurrent queries per second for that expensive query falls over. With coalescing, exactly 1 request recomputes and the other ~999 either wait ~200 ms for the notification or receive the previous (slightly stale) value immediately; origin load for that key stays at 1 concurrent request regardless of RPS.
Trade-offs and pitfalls
A lock that never expires on a crashed refresher permanently blocks that key; always set a lock TTL slightly longer than the expected recompute time, plus a fallback path that lets a waiter give up and fetch directly after a bounded wait. Serving stale-while-refreshing is a correctness trade-off, not a free win: it is the right default for read-heavy, staleness-tolerant data, and the wrong default for a low-latency-but-must-be-fresh field like an account balance. Jitter alone does not help an already-hot key that is legitimately read far more than others; that is a hot-key sharding problem, not a stampede problem, and needs a different fix (splitting the key, adding a replica-backed local cache).
Design a multi-region caching strategy for a global application that requires sub-50ms read latency worldwide but strong consistency for user profile writes. Compare active-active replicated caches with conflict resolution, a global master for writes with local read caches, and CRDT-based approaches. Recommend an approach and justify trade-offs for latency, consistency, and operational complexity.
Sample Answer
Direct answer
There is no design that gives you both sub-50ms global reads and strong consistency for every write; you choose where the compromise sits. For most globally-distributed services the right default is regional read caches with a single-writer region per key (or per user) plus asynchronous replication, escalating to active-active with conflict resolution only for the specific keys that genuinely need multi-region writes.
Structured elaboration
- Global master with local read caches: writes always go to one authoritative region (chosen per key, e.g., the user's home region); that region's cache is updated synchronously, and other regions' caches are populated by asynchronous replication or event-driven invalidation. Reads in the writer's own region are strongly consistent; reads elsewhere are eventually consistent with a bounded lag (typically under a few seconds for a well-tuned replication pipeline). This is the simplest model to reason about and is the right default unless a specific workload proves it insufficient.
- Active-active with conflict resolution: every region can accept writes to the same key; conflicts are resolved with last-write-wins (using synchronized clocks or hybrid logical clocks), version vectors, or application-specific merge logic. This removes the single-writer bottleneck but pushes real complexity into conflict resolution and makes the failure modes harder to reason about; reserve it for keys where availability during a regional partition matters more than avoiding conflicts (e.g., a shopping cart, where a merge is acceptable).
- CRDT-based approaches: conflict-free replicated data types (structures with a mathematically well-defined merge function, such as a grow-only counter or a last-writer-wins register) let every region write locally and merge automatically without coordination. They are the cleanest fit when the data shape is naturally a CRDT (counters, sets, simple registers) but do not generalize to arbitrary application state.
- Choosing the read-latency-vs-consistency point per requirement: a common pattern is to segment data by freshness requirement. Authentication and permission state gets synchronous, single-region-authoritative reads (correctness matters more than latency). Profile pictures, preferences, and feed content get regional caches with eventual consistency (latency matters more, and staleness of a few seconds is invisible to users).
Worked example
For a service needing sub-50ms p95 reads worldwide with a single global-master design and 150ms average inter-region round-trip time: a user in Singapore reading data whose write-authoritative region is US-East would need a cross-region hop on every uncached read, blowing the 50ms budget by 3x. The fix is not "make replication faster" but "make the region the user reads from also the region their writes update" (their home region is the writer), with cross-region only used for failover. Under active-active with a 5-second bounded staleness target, replication lag has to be monitored per-region-pair and alerted when it exceeds roughly half the staleness budget (2.5s), leaving headroom for the merge/apply step.
Trade-offs and pitfalls
The most common design mistake is picking one consistency model for the whole service instead of per data class; forcing strong consistency on data that does not need it (e.g., a "last seen" timestamp) burns your entire latency budget for no user-visible benefit. Active-active without a clear conflict-resolution policy invites silent data loss (the losing write of a last-write-wins resolution simply disappears); make sure product owners have explicitly signed off on what "conflict" means for each data type before choosing this model. CRDTs remove coordination cost but restrict your data model; retrofitting CRDTs onto an existing schema is usually more work than designing around single-writer-per-key from the start.
Explain the HTTP Cache-Control directives stale-while-revalidate and stale-if-error. For an API endpoint that requires low latency but can tolerate slightly stale responses during origin outages, propose Cache-Control values and explain how a CDN and browsers will behave in normal operation vs origin failure.
Sample Answer
Direct answer
stale-while-revalidate lets a client serve an expired cached response immediately while fetching a fresh copy in the background, and stale-if-error lets it keep serving that stale copy if the fresh fetch fails, trading a small amount of guaranteed freshness for consistently low latency and resilience to brief origin outages.
Structured elaboration
stale-while-revalidate:Cache-Control: max-age=60, stale-while-revalidate=30means the response is fresh for 60 seconds, and for an additional 30 seconds after that, a client (or content delivery network, CDN) can serve the stale copy immediately while triggering a background revalidation request; the NEXT request after that window gets the freshly revalidated copy.stale-if-error:stale-if-error=300tells the client/CDN that if the origin is unreachable or returns an error during revalidation, keep serving the stale copy for up to 300 seconds rather than surfacing the error to the user; this converts a brief origin outage into a slightly-stale-but-working experience instead of a hard failure.- When to recommend these: an API endpoint needing low latency but able to tolerate slightly stale responses during origin outages (news feeds, non-critical dashboards, catalog listings) is a strong fit; both directives explicitly trade a bounded amount of staleness for availability and latency, which must be an acceptable trade for the specific data.
- Behavior in normal operation vs. origin failure: in normal operation, the client mostly experiences fast responses with background-refreshed freshness (never blocking on a slow origin fetch on the critical path); during an origin failure, the same mechanism seamlessly extends the "acceptable stale window," so users experience continuity rather than an outage.
- Implementing with cache-aside: cache-aside can approximate the same behavior in application code (check cache; if within the stale-but-usable window, return immediately and kick off an async refresh; if the refresh fails, keep serving the existing value) even without a content delivery network that natively supports these headers.
Worked example
An API returning a news feed sets Cache-Control: max-age=30, stale-while-revalidate=60, stale-if-error=3600. Most requests within the first 30 seconds get a guaranteed-fresh response; requests between 30 and 90 seconds after the last fetch get an immediate stale response while a background revalidation happens; if the origin is down, the client keeps serving that stale response for up to an hour rather than failing outright, giving the origin a full hour to recover before user-facing errors would appear.
Trade-offs and pitfalls
Setting stale-if-error too long risks masking a real, ongoing outage from users (and from monitoring that relies on user-facing errors as a signal) for far longer than intended; pair a generous stale-if-error window with independent origin-health monitoring, not just user-facing symptoms. These directives are a poor fit for data where even a brief staleness window during revalidation is unacceptable (e.g., a live auction price); apply them selectively, not as a blanket default across every endpoint.
Explain and compare strategies to partition (shard) cache data across multiple cache nodes. Discuss rebalancing costs, techniques to reduce key movement, how to mitigate hot shards, and failover behavior when nodes are added or removed.
Sample Answer
Direct answer
Consistent hashing places both cache nodes and keys on a conceptual ring (by hashing each to a point on the ring) and routes a key to the next node clockwise from it, so adding or removing a node only remaps the keys between it and its neighbor, not the entire keyspace the way naive modulo hashing would.
Structured elaboration
- Why modulo hashing fails at scale: routing a key with
hash(key) % Nmeans every node-count change (N) reshuffles almost every key's destination node, since the modulo result changes for nearly all keys; that means a near-total cache flush (and a stampede of misses to the origin) on every scale-out or node failure. - Consistent hashing's improvement: only the keys that fell between the added/removed node and its next neighbor on the ring need to move; on average, adding the Nth node to a ring of N nodes remaps roughly 1/N of the keyspace, not close to 100 percent.
- Virtual nodes: mapping each physical node to many points on the ring (e.g., 100 to 200 virtual nodes per physical node) smooths out the otherwise-uneven distribution you'd get from a small number of random hash points, and makes the fraction of keys remapped on a node change proportional to that node's actual share of capacity rather than being lumpy.
- Alternatives: rendezvous hashing (highest-random-weight) computes, for each key, a weighted score against every node and picks the highest, which achieves similar minimal-remapping properties without needing an explicit ring structure. A proxy layer (client-side hashing vs a routing proxy like Twemproxy) changes WHERE the hashing decision is made but not the underlying algorithm choice.
- Hot shards: consistent hashing distributes keys evenly in aggregate but does not know that some keys are read far more than others; a node can still become hot if it happens to own a popular key, which is a separate problem from rebalancing cost (see hot-key mitigation).
- Failover behavior: when a node fails, its portion of the ring is picked up by its neighbor (or, with virtual nodes, spread across several neighbors); this is graceful for read-through/cache-aside caches (a "miss" for a remapped key just refetches from origin) but can look like data loss for a cache that was the system of record for anything.
Worked example
A cluster grows from 10 nodes to 11. Under naive modulo hashing, roughly 91 percent of keys change their target node (1−10/11), effectively invalidating almost the whole cache at once. Under consistent hashing with virtual nodes, only the keys that fall in the ring segment now owned by the new node move, roughly 1/11≈9% of the keyspace, leaving the other 91 percent of cached entries untouched and avoiding a stampede.
Trade-offs and pitfalls
Too few virtual nodes per physical node produces an uneven distribution (some nodes end up owning noticeably more of the ring than others by chance); 100+ virtual nodes per physical node is a common starting point to smooth this out. Consistent hashing solves REBALANCING cost, not hot-key load; do not expect it to fix a single overloaded key. Client-side hashing requires every client to agree on the exact same ring state, which becomes an operational hazard during a rolling deploy where old and new client versions might briefly disagree on routing; a proxy-side approach centralizes that decision at the cost of an extra network hop.
Design a high-availability and failover strategy for Redis used as a critical cache: discuss replication, Redis Sentinel vs Redis Cluster choices, AOF vs RDB persistence trade-offs, replica synchronization, split-brain avoidance, and an operational runbook for failover testing and recovery.
Sample Answer
Direct answer
For high availability (HA), Redis Sentinel monitors a primary/replica set and automates failover for a single logical dataset, while Redis Cluster shards data across many primaries (each with its own replicas) and handles failover per-shard, so the right choice depends on whether you need horizontal scale (Cluster) or just automated failover for a dataset that fits on one node (Sentinel).
Structured elaboration
- Sentinel: a set of Sentinel processes monitor the primary and its replicas, and on primary failure, elect a replica to promote and reconfigure clients (via Sentinel's own service-discovery protocol) to point at the new primary. Best fit when your dataset comfortably fits on one primary and you mainly need automated failover, not sharding.
- Cluster: data is split across up to 16,384 hash slots distributed among primary nodes, each with its own replica(s); failover happens per-shard, and the cluster continues serving unaffected shards during a single shard's failover. Necessary once your dataset or throughput exceeds what a single primary can handle.
- Persistence trade-offs: append-only file (AOF) gives stronger durability (replays every write, minimal data loss on crash) at higher disk input/output (I/O) cost; RDB (point-in-time snapshots) is cheaper but can lose writes since the last snapshot on a crash. Many production setups use both, AOF for durability with periodic RDB snapshots for faster full restores.
- Split-brain avoidance: in a network partition, an isolated primary that keeps accepting writes while a new primary is elected on the other side of the partition creates two diverging datasets; Sentinel's quorum requirement (a majority of Sentinels must agree before promoting) and Redis's own
min-replicas-to-writesetting (refuse writes if too few replicas are connected) both reduce, though do not fully eliminate, this risk. - Failover runbook: verify which node is now primary before assuming failover completed correctly, confirm replica lag has caught up (or accept the data-loss window if it has not), and run a smoke-test write/read before declaring the cluster healthy again.
Worked example
A primary node fails; Sentinel's quorum of 3 monitoring processes agree (2 of 3 required) and promote the most up-to-date replica within a few seconds, well inside a target of under 30 seconds for automated failover. Clients using Sentinel-aware libraries automatically discover the new primary; clients hardcoded to the old primary's address keep failing until manually updated, which is why Sentinel-aware client libraries (or a proxy layer) are a hard requirement for this design to actually work end-to-end.
Trade-offs and pitfalls
A quorum requirement that is too small (e.g., 1 of 3) makes split-brain more likely under a network partition; too large a quorum (requiring all Sentinels to agree) can make failover fail to trigger at all during a partial partition. Persistence is not a substitute for replication: RDB/AOF protect against process crashes and restarts, not against a full node/disk loss, which is what replication protects against.
Unlock Full Question Bank
Get access to all Caching Strategies and Distributed Caching interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.