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.
List and explain the key operational metrics you would monitor for cache health and performance. For each metric state what action you would take if it trends poorly.
Sample Answer
Direct answer
The core cache health metrics are hit ratio, eviction rate, and tail latency (p95/p99, 95th/99th percentile); each one answers a different question, and a regression in any of them should trigger a specific, different response.
Structured elaboration
- Hit ratio: hits divided by total requests. A sustained drop is the earliest, most sensitive signal that something is wrong (undersized cache, a cold cache after a deploy, or a bug in cache-key construction); it should page or alert before the resulting latency/database-load impact becomes user-visible.
- Eviction rate: how often items are being evicted to make room for new ones. A high eviction rate on a workload whose working set should fit comfortably usually means the cache is undersized relative to demand; the action is to increase capacity or investigate why the working set grew unexpectedly.
- Tail latency (p95/p99): because a miss can be an order of magnitude slower than a hit, tail latency for cache operations directly reflects the hit ratio and the underlying origin's own latency; track it separately from average latency, since averages hide the exact experience a meaningful fraction of users have.
- Memory usage: absolute memory consumption and headroom before hitting the configured limit; combined with eviction rate, this tells you whether you are evicting because of genuine memory pressure or because of a misconfigured limit.
- What action to take when each regresses: a hit-ratio drop triggers investigating recent deploys, key-format changes, or a genuine traffic-pattern shift; a rising eviction rate triggers a capacity review; rising tail latency (with a stable hit ratio) points at the origin or the network path, not the cache itself.
Worked example
A service with a stable 90 percent hit ratio and healthy p99 latency deploys a change that accidentally alters the cache key format (e.g., adding a new query parameter to the key without updating existing entries). Hit ratio drops to near zero for that endpoint's traffic instantly. Because hit ratio is watched as a leading indicator, this is caught and rolled back within minutes; without it, the team would only notice once database load and p99 latency alerts fired, by which time real user impact has already occurred.
Trade-offs and pitfalls
Watching only aggregate, cluster-wide metrics can hide a problem localized to one shard or one hot key; pair cluster-wide dashboards with the ability to drill into per-shard or per-key detail. Alerting on a single noisy data point rather than a sustained trend produces alert fatigue; use a rolling window (e.g., 5-minute average, sustained for 2+ consecutive windows) before paging.
One Redis key (for example '/homepage') receives 80% of read traffic causing latency and CPU spikes on cache nodes. Propose at least five mitigation strategies at the application, cache, and CDN layers, and discuss operational trade-offs and monitoring signals to detect hot keys.
Sample Answer
Direct answer
A hot key overwhelms a single cache node because most partitioning schemes route one key to exactly one node, so no amount of horizontal scaling helps until you either split the key's traffic across multiple nodes or absorb the read load closer to the client than the cache node itself.
Structured elaboration
- Detection: monitor per-key or per-shard request rate (not just aggregate cluster metrics, which can look healthy even while one node is saturated); a sudden CPU or latency spike on one specific node while others stay idle is the signature of a hot key or hot shard.
- Key splitting: replace a single hot key with N sub-keys (
item:123:0throughitem:123:N-1), hash requests across the sub-keys, and aggregate on read if needed (for a counter, sum the sub-key values). This spreads the load across N nodes instead of concentrating it on one. - Local (L1) caching in front of the shared cache: an in-process cache on each application instance, with a short time-to-live (TTL) of a few seconds, absorbs most repeated reads for a hot key before they ever reach the shared cache node, at the cost of a small amount of staleness.
- Read replication: if the hot key is read-heavy, adding read replicas for that specific shard (or replicating the hot key specifically) spreads read traffic across multiple nodes; this does not help write-heavy hot keys.
- Request coalescing: if the hot key's value is expensive to (re)compute, ensure only one in-flight computation happens at a time (see the stampede-defense pattern) rather than every read independently recomputing.
- Client-side / proxy-side routing awareness: if using a proxy (e.g., Twemproxy) or client-side consistent hashing, confirm the routing layer itself is not adding overhead disproportionate to the hot key's share of traffic.
Worked example
A single Redis key holding a homepage configuration payload receives 80 percent of a service's read traffic and is pinned to one node by the cluster's hashing; that node's CPU spikes into the 90s while every other node in the cluster sits near idle, even though the cluster's aggregate utilization looks fine. Splitting into 10 sub-keys (homepage:config:0 .. homepage:config:9), each application instance picking a sub-key at random per request, spreads that traffic across up to 10 nodes; combined with a 2 to 5 second local in-process cache in front of Redis, the effective read rate hitting any single Redis node for this content drops by roughly two orders of magnitude.
Trade-offs and pitfalls
Key splitting adds real complexity for anything that needs a consistent view across the split (a counter needs an aggregation step; a config payload needs all sub-keys to agree, which reopens an invalidation-consistency question). A local L1 cache trades staleness for load reduction; make sure the TTL is short enough that the staleness is acceptable for that specific piece of data. Detecting hot keys after the fact from customer complaints is much more expensive than catching them from per-key metrics; invest in that visibility before you need it, not during the incident.
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.
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.
Explain the differences between Least Recently Used (LRU) and Least Frequently Used (LFU) eviction policies. For an in-memory cache storing user session objects that are frequently accessed soon after login then rarely, which policy is more appropriate and why?
Sample Answer
Direct answer
Least Recently Used (LRU) evicts based on recency of access and fits workloads where "recently touched" predicts "will be touched again soon"; Least Frequently Used (LFU) evicts based on access count and fits workloads where a stable set of items is popular over a long time, even if not accessed in the last few seconds.
Structured elaboration
- LRU mechanics and fit: LRU tracks the order items were last accessed and evicts the item that has gone the longest without a touch. It fits access patterns with strong temporal locality: a session object, for example, is heavily accessed right after login and then goes cold; LRU naturally keeps the currently-active sessions warm and evicts the ones nobody has touched recently.
- LFU mechanics and fit: LFU tracks how many times each item has been accessed (often with some decay over time to avoid permanently favoring old-but-once-popular items) and evicts the least-accessed item. It fits patterns with a stable long-tail of popular items that get accessed periodically but not necessarily continuously, such as a small set of perennially popular catalog items that get read constantly, interspersed with occasional cold reads of rare items; a pure LRU cache would wrongly evict a genuinely popular item just because it happened not to be touched in the last few seconds.
- LRU's weak spot: a single burst of one-time scans (e.g., a batch job reading every record once) can flush an LRU cache of genuinely hot items, because the scan makes every item "recently used" once, pushing out items that are accessed far more often over time.
- LFU's weak spot: new items start at zero frequency and can be evicted immediately even if they would become popular, because they have not yet accumulated enough hits to compete with established items (this is sometimes mitigated with a decay factor or a frequency-boosted admission window).
Worked example
For user session objects that are heavily read right after login and then rarely touched again: LRU is the right default, because the access pattern IS recency-driven, and LFU would keep old, no-longer-relevant sessions around simply because they accumulated a lot of hits while they were active. For a product catalog with seasonal hot items plus a long tail of rarely-viewed products: LFU (or a hybrid) does better, because a genuinely popular item accessed every few minutes should survive occasional bursts of one-time-scan traffic on unrelated items that would otherwise flush it from an LRU cache.
Trade-offs and pitfalls
LFU requires more bookkeeping (a counter per item, often with decay logic) than LRU's simple access-order list, so it costs more memory and CPU per operation; do not reach for LFU unless the access pattern genuinely benefits from it. Neither pure policy handles every real workload well, which is why production caches (Redis's allkeys-lfu, or an adaptive scheme like W-TinyLFU) increasingly blend recency and frequency signals rather than using either in isolation.
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.