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.
Compare the cache-aside, read-through, write-through, and write-behind caching patterns. For each pattern describe: (a) how reads and writes flow between cache and data store, (b) a typical use case, and (c) the main advantage and drawback. Give one example service type where each pattern is a good fit.
Sample Answer
Direct answer
Cache-aside, read-through, write-through, and write-behind differ in who is responsible for populating the cache and when a write becomes durable: cache-aside puts that responsibility on the application, read-through/write-through push it into the caching layer itself, and write-behind trades immediate durability for write throughput.
Structured elaboration
- Cache-aside (lazy loading): on read, the application checks the cache; on a miss, it reads from the datastore and populates the cache itself. On write, the application writes to the datastore and either invalidates or updates the cache entry. The application owns all the logic; the cache is a dumb key-value store. This is the most common pattern because it fails gracefully (if the cache is down, reads just go straight to the datastore) and only caches what is actually requested.
- Read-through: functionally similar to cache-aside from the caller's perspective, but the cache library/layer itself knows how to fetch from the datastore on a miss, so the application only ever talks to the cache. This centralizes the fetch logic but requires a caching layer that supports it.
- Write-through: every write goes to the cache first (or simultaneously), and the cache synchronously writes through to the datastore before acknowledging. Reads are always fresh because the cache is never behind the datastore, at the cost of write latency (you pay for both writes on every request) and caching data that may never actually be read.
- Write-behind (write-back): writes go to the cache and are acknowledged immediately; the cache asynchronously flushes to the datastore in the background (often batched). This gives the best write throughput and latency, at the cost of a durability window: a crash between the acknowledged write and the flush can lose data unless the write queue itself is durable.
- Picking one, by use case: a product catalog with heavy reads and occasional updates fits cache-aside well (simple, only caches what's actually browsed). A durability-sensitive write path (a payments ledger) generally avoids write-behind's data-loss window and prefers write-through or a cache-aside pattern with synchronous invalidation.
Worked example
For a product catalog service: cache-aside is a strong default. On a product-detail read, check Redis; on miss, query the database and populate Redis with a time-to-live (TTL); on a price update, write to the database and then delete (or update) the cached entry so the next read repopulates it. This avoids caching the 90+ percent of the catalog nobody is currently browsing, unlike write-through, which would populate the cache for every single write regardless of read demand.
Trade-offs and pitfalls
Cache-aside has a well-known race: a read that misses, starts fetching from the datastore, and finishes AFTER a concurrent write has already invalidated the cache, can re-populate the cache with the now-stale value it fetched before the write. Write-through eliminates staleness but adds write latency and can cache "dead weight" (data nobody reads). Write-behind's throughput win is real but its durability trade-off must be an explicit decision, not a default; never use write-behind for data where losing the last few seconds of writes is unacceptable.
Design a monitoring dashboard and alerting strategy for a distributed Redis cache serving an internal read-heavy API. Include specific metrics to display, dashboard panels, and alert conditions that would indicate (a) cache degradation, (b) emergence of a hot key, and (c) eviction-related problems.
Sample Answer
Direct answer
Design the dashboard around the three failure modes an operator actually needs to distinguish quickly: general degradation (rising latency or falling hit ratio across the board), an emerging hot key (one node/shard diverging from the rest), and eviction-related problems (memory pressure forcing out data that should still be cached).
Structured elaboration
- Panel: cluster-wide health: aggregate hit ratio, miss ratio, and p50/p95/p99 (50th/95th/99th percentile) latency over a rolling window, with the current service-level objective (SLO) target overlaid so a degradation is visible at a glance, not just as a raw number.
- Panel: per-node/per-shard breakdown: CPU, request rate, and latency broken out by individual node, specifically because an emerging hot key looks fine in the aggregate panel but shows one node's line diverging sharply from the others; this panel is what actually catches a hot key before it becomes an incident.
- Panel: eviction and memory: eviction rate and memory usage as a percentage of the configured limit, ideally split by key class or namespace if the cache is shared across use cases, so a memory-pressure problem can be traced to which data is actually filling the cache.
- Alert conditions for degradation: hit ratio dropping below a sustained threshold (e.g., more than 15 points below the trailing 7-day baseline for more than 2 consecutive 5-minute windows) or p99 latency exceeding the SLO target for a sustained period.
- Alert conditions for a hot key: any single node's request rate or CPU exceeding a set multiple (e.g., 3x) of the cluster's median node, sustained for more than a short window (to avoid alerting on normal brief variance).
- Alert conditions for eviction problems: eviction rate rising sharply relative to its own recent baseline, especially combined with memory usage near the configured limit, distinguishing "the cache is working as intended, evicting genuinely cold data" from "the cache is thrashing, evicting data that will be needed again soon."
Worked example
A hot-key alert fires when node 7's request rate is 4x the cluster median for more than 60 seconds; the dashboard's per-node panel immediately shows node 7 as a clear outlier against otherwise-flat lines for the other nodes, letting the on-call engineer confirm within seconds that this is a hot-key event rather than a cluster-wide issue, and start the hot-key mitigation runbook instead of investigating a broader outage.
Trade-offs and pitfalls
A dashboard that only shows cluster-wide aggregates cannot distinguish a hot-key problem from general health, which is exactly the failure mode this design targets; do not skip the per-node breakdown panel to save dashboard space. Alerting on eviction rate alone without memory context conflates "healthy, expected eviction" with "the cache is undersized"; always pair eviction-rate alerting with memory-utilization context.
A distributed cache cluster shows inconsistent data across nodes after a network partition. Explain the plausible root causes and design a recovery plan that minimizes downtime and data loss. Discuss the trade-off between restoring availability quickly and reconciling consistency.
Sample Answer
Direct answer
Inconsistent data across cache nodes after a network partition means two sides of the partition may have kept accepting writes independently (split-brain) or replication simply fell behind (partial replication/stale writes); recovery has to first stop the bleeding (restore a single source of truth) before reconciling the divergence, and that choice trades availability against correctness.
Structured elaboration
- Plausible root causes: split-brain (both sides of a partition believed they were the primary and accepted writes independently, producing two diverging histories), partial replication (replication was in progress but not complete when the partition occurred, so some nodes have older data than others), and stale writes (a client wrote to a node that was, unknown to it, no longer the authoritative primary).
- Restoring availability quickly versus reconciling consistency: choosing to bring the cluster back online immediately (picking one side's data as authoritative and discarding the other's divergent writes) restores service fast but can silently lose data from the discarded side; choosing to carefully reconcile both sides first (comparing and merging where possible) is safer for correctness but extends the outage.
- A recovery plan: first, stop accepting further writes on whichever side is NOT chosen as authoritative (preventing further divergence); second, decide the authoritative side (usually the side with quorum, or the side that was serving the majority of traffic, per your topology's own quorum rules); third, reconcile or discard the non-authoritative side's diverged writes, documenting what was lost if anything; fourth, resync the non-authoritative side from the authoritative one before bringing it back into service.
- Minimizing downtime and data loss together: this is rarely a clean binary choice; a common middle ground is bringing read traffic back online quickly from the authoritative side (restoring availability for reads) while writes stay paused or degraded until reconciliation completes, rather than an all-or-nothing restoration.
Worked example
A 6-node Redis cluster splits into a 4-node majority partition and a 2-node minority partition due to a network issue; if the cluster's quorum configuration correctly prevented the minority side from accepting writes during the partition (a properly configured min-replicas-to-write or Sentinel quorum), the majority side is unambiguously authoritative and the minority side simply needs to resync from it once the network heals, with no actual data divergence to reconcile. If quorum protection was misconfigured and the minority side DID accept writes, those writes are now in conflict with the majority's history and must be explicitly reconciled or, if reconciliation is not possible, discarded and documented as lost.
Trade-offs and pitfalls
The best outcome here comes from PREVENTING split-brain in the first place (properly configured quorum requirements), not from having a great recovery plan for when it happens; a recovery plan is a backstop, not a substitute for prevention. Discarding a non-authoritative side's writes without first checking whether any of them can be safely reconciled (a value that was never touched on the authoritative side, for example) is faster but can lose more than strictly necessary; weigh the reconciliation effort against how much data is actually at stake.
Discuss how to handle cache serialization and deserialization safely and efficiently. Consider versioning serialized formats, schema evolution, backward compatibility, and lazy migration strategies during rolling upgrades.
Sample Answer
Direct answer
Cache serialization needs explicit schema versioning so that a deployment change (a field added, removed, or retyped) does not produce a runtime error or silent data corruption when new code reads an old cached format, or old code reads a new one, during a rolling upgrade.
Structured elaboration
- Versioning the serialized format: embed a schema version alongside the serialized payload (either in the value itself, or in the cache key, as covered by the key-versioning pattern) so a reader can detect which shape it is dealing with.
- Schema evolution: prefer additive, backward-compatible changes (new optional fields default sensibly if absent) over breaking changes (renaming or retyping an existing field) wherever possible, since additive changes let old and new code coexist safely without any special handling.
- Backward compatibility during rolling upgrades: during a deploy, old and new application code run simultaneously for some window; if new code writes a new schema version and old code cannot deserialize it, old-code instances will error or silently misbehave on every cache read for that key until the deploy completes, unless the new schema is designed to be backward-readable, or the version is used to explicitly route old code away from new-format entries.
- Lazy migration strategies: rather than migrating every cached entry to a new format immediately, let entries migrate lazily: on a cache miss (or an explicit read-and-rewrite), the new format is written; old-format entries simply age out via their normal time-to-live (TTL), avoiding a disruptive bulk-migration pass.
- Choosing a serialization format: a format with strong built-in support for optional/default fields (protocol buffers, for example) makes additive schema evolution far more natural than a format that requires exact structural matching to deserialize correctly.
Worked example
Adding a new optional field to a cached user-profile object: with a backward-compatible serialization format, old code (not yet aware of the new field) simply ignores it when reading a new-format entry, and new code supplies a sensible default when reading an old-format entry that lacks the field; no special versioning logic is needed at all, because the format itself tolerates the difference. Contrast with renaming an existing field, which is NOT safely backward-compatible under most formats and would require either a version-gated read path or accepting a brief window of cache misses/errors during the rolling deploy.
Trade-offs and pitfalls
Assuming a serialization format is "safe" without checking its specific behavior on missing or extra fields is a common way this bites during a rolling deploy; verify the format's actual compatibility guarantees, do not assume. Skipping explicit versioning "because most changes are additive" works until the first genuinely breaking change arrives unplanned; building the versioning mechanism in from the start costs little and avoids an emergency retrofit later.
In a system with caches, a primary database, and a search index (e.g., Elasticsearch), describe common consistency pitfalls when updating entities (for example user profile changes). Propose an ordered update workflow that minimizes stale reads across layers and supports failure recovery, and explain trade-offs involved.
Sample Answer
Direct answer
When a cache, a primary database, and a search index all hold a copy of the same entity, an update has to reach all three, and the order they are updated in determines what inconsistent intermediate state a concurrent reader might see; design the update sequence deliberately rather than firing updates to all three independently.
Structured elaboration
- The core pitfall: three independent copies means three independent chances to be out of sync at any given moment; a naive "update DB, then update cache, then update search index" sequence has a window after each step where a reader hitting a different layer sees a different, momentarily-inconsistent view of the same entity.
- An ordered update workflow: write to the primary database first (the source of truth), then propagate to the cache and search index, ideally via the same mechanism (an event derived from the database's own write, e.g., change data capture, CDC) rather than the application independently, and possibly inconsistently, updating each one itself.
- Minimizing stale reads across layers: invalidate (or update) the cache promptly after the database write; the search index, which is often inherently eventually consistent by nature (indexing takes measurable time), should be treated with a wider, explicitly acknowledged staleness tolerance rather than expected to match the database's freshness.
- Failure recovery: if the propagation to the cache or search index fails partway (the database write succeeded but the cache invalidation did not), the system needs to detect and correct that drift, either via a reconciliation job that periodically compares layers, or by treating the CDC-based propagation as the single source of truth for keeping all downstream copies in sync (so a failure there is a well-understood, monitorable gap, not a silent one).
- Trade-offs involved: driving every downstream update from the database's own change stream (rather than each application code path independently updating cache and search index) is more work to set up but eliminates entire classes of "we updated the DB and cache but forgot the search index in this one code path" bugs.
Worked example
A user profile update: the database write succeeds; a CDC-derived event then triggers both a cache invalidation and a search-index update. A reader hitting the cache immediately after the database write (before the CDC event has propagated) sees a brief stale read from the cache, bounded by the CDC pipeline's typical propagation latency (often under a second); a search query against the index during that same window might return the OLD profile data in search results for slightly longer, since indexing itself typically has its own additional latency beyond simple cache invalidation, an acceptable, well-understood difference in staleness across layers as long as it is explicit and monitored.
Trade-offs and pitfalls
Independently updating cache and search index from application code (rather than from a single CDC-derived event stream) is a common source of "we forgot this one code path" bugs, where some write paths correctly update all three layers and others silently miss one; centralizing propagation removes that class of bug at the cost of needing CDC infrastructure. Treating all downstream layers as needing the SAME freshness guarantee is usually wrong; a search index's inherent indexing latency is a different, and typically wider, staleness budget than a cache's invalidation latency, and conflating the two leads to either wasted effort over-optimizing the index or an unrealistic freshness expectation for it.
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.