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.
Explain cache hit, miss, and eviction. Describe the metrics you would monitor to understand cache health in a production system and how you would measure them. Given a cache that receives 100k requests/min and returns 80k hits, calculate the hit rate and discuss implications for capacity sizing and SLOs.
Sample Answer
Direct answer
A cache hit is a read served from the cache; a miss is a read that had to go to the origin; the hit ratio is hits divided by total requests, and it is the single most important summary number for whether a cache is doing its job.
Structured elaboration
- Hit ratio formula: hit ratio=hits+misseshits. It should be tracked as a rolling metric (e.g., per minute) rather than a single lifetime number, since it reacts to traffic pattern changes, deploys, and cache flushes.
- Eviction: when the cache is full and a new item needs room, an eviction policy (least-recently-used, LRU; least-frequently-used, LFU; and others) picks an existing item to remove; eviction rate is a separate signal from hit ratio and matters because a high eviction rate on an undersized cache is a common root cause of a lower-than-expected hit ratio.
- Measuring it in production: most cache clients and cache servers (e.g., Redis's
INFOcommand) expose hit/miss counters directly; export them to your metrics system and alert on a sustained drop, not a single noisy data point. - What the number implies for capacity sizing: a hit ratio well below what the workload's theoretical repeat-read rate suggests usually means the cache is too small (working set does not fit, so useful entries get evicted before they are reused again) rather than a fundamental mismatch between the workload and caching.
- What it implies for service-level objectives (SLOs): because a miss is typically an order of magnitude or more slower than a hit, the hit ratio directly predicts your p95/p99 latency distribution; a drop in hit ratio should be treated as a leading indicator of a latency SLO breach, not just a cache-health curiosity.
Worked example
A cache receiving 100,000 requests per minute returns 80,000 hits. Hit ratio is 80,000/100,000=0.80, or 80 percent. If a hit takes 2ms and a miss takes 150ms, the blended average latency is 0.80×2ms+0.20×150ms=1.6ms+30ms=31.6ms. If the hit ratio drops to 60 percent with the same per-hit and per-miss costs, blended latency rises to 0.60×2+0.40×150=1.2+60=61.2ms, roughly doubling despite "only" a 20-point hit-ratio drop, which is why hit ratio is such a sensitive early-warning signal.
Trade-offs and pitfalls
A hit ratio number without context is misleading: 80 percent is excellent for a highly diverse, long-tail workload and mediocre for a workload with a small, stable, highly-repeated key set that should be closer to 99 percent. Always compare against the workload's own historical baseline and theoretical ceiling, not a generic industry number.
For a system containing user consent and privacy-sensitive fields, discuss TTLs, explicit purge, versioned keys, and event-driven invalidation for ensuring regulatory correctness. Compare these strategies and recommend a design that minimizes legal risk while balancing latency and cost.
Sample Answer
Direct answer
For consent and privacy-sensitive fields, favor explicit invalidation and versioned keys over a passive time-to-live (TTL), and treat a long TTL as a direct legal-risk decision, not just a performance tuning knob, because a stale consent state can mean processing data the user has explicitly withdrawn permission for.
Structured elaboration
- TTL alone is insufficient: a TTL bounds staleness but does not guarantee it; a user withdrawing consent expects that to take effect promptly, and "eventually, within the TTL window" is not a defensible position if that window is, say, an hour.
- Explicit purge on consent change: a consent withdrawal should trigger immediate, explicit invalidation of the cached consent state (and ideally, propagate to every system that reads it), rather than relying on the next natural TTL expiry.
- Versioned keys: bump a version on consent change so any cached read of the OLD version becomes unreachable immediately, avoiding a race where a slow, in-flight read repopulates the cache with the just-withdrawn consent state after the invalidation (the same race pattern seen elsewhere in this topic, here with legal consequences instead of just a UX inconvenience).
- Event-driven invalidation for regulatory correctness: propagate consent changes as events to every downstream consumer that might have cached consent state, since a consent decision often needs to be honored by multiple systems (advertising, analytics, data processing pipelines), not just the primary service.
- Recommended design minimizing legal risk while balancing latency and cost: a short TTL (as a safety-net backstop, not the primary mechanism) combined with event-driven, explicit invalidation on any consent change gives near-immediate correctness for the common case while still self-healing if an invalidation event is somehow lost, rather than choosing one mechanism alone.
Worked example
A user withdraws marketing-communications consent; an event fires immediately, invalidating their cached consent state across every consuming service (the marketing service, an analytics pipeline, a personalization engine) within roughly the propagation latency of the event system (typically well under a second), rather than each of those systems independently waiting out its own TTL (which, if inconsistently configured across systems, could mean some honor the withdrawal in seconds and others in minutes).
Trade-offs and pitfalls
Treating regulatory correctness as "just another caching performance trade-off" and choosing a TTL purely for latency/cost reasons is a serious mistake; involve legal/compliance stakeholders in defining the acceptable staleness window for consent data, do not decide it unilaterally as an engineering optimization. Relying purely on event-driven invalidation with no TTL backstop reintroduces the risk that a lost event produces unbounded (rather than bounded) staleness, which is a worse regulatory posture than a short, explicit TTL ceiling.
What is a cache stampede or thundering herd problem and how can it affect reliability? Name and briefly describe at least four practical prevention techniques.
Sample Answer
Direct answer
A cache stampede (also called a thundering herd) happens when a popular cache entry expires or is invalidated and many concurrent requests for that same key all miss at once, sending a burst of simultaneous load to the origin that it was never sized to absorb directly.
Structured elaboration
- Why it happens: caching's whole benefit is deduplicating repeated work; a stampede is exactly the moment that deduplication briefly stops working, because every one of the concurrent requests independently decides "I need to recompute this" at the same instant.
- Why it is dangerous: the origin (a database, an expensive computation, a third-party API) is usually sized assuming the cache absorbs most traffic; a stampede can multiply its load by the number of concurrent requesters for that one key, which for a genuinely hot key can be thousands of requests in a fraction of a second.
- Prevention techniques (name and describe at least four): locking (only the first requester acquires a lock and recomputes, others wait or serve stale data), request coalescing/singleflight (deduplicate concurrent identical fetches into one in-flight request), jittered expirations (randomize time-to-live, TTL, slightly so many keys written together do not expire at the exact same instant), and background/proactive refresh (recompute before expiry so the cache rarely actually goes empty for a hot key).
Worked example
A homepage configuration cached with a 60-second TTL, read 5,000 times per second, expires at exactly the 60-second mark with no protection: in the recomputation window (say 200ms), roughly 1,000 requests (5,000 times 0.2s) would all miss simultaneously and hit the origin. With locking or coalescing, exactly one of those 1,000 requests recomputes; the rest wait briefly or receive the prior value.
Trade-offs and pitfalls
Jitter alone does not fully solve a single very-hot key's stampede risk (it helps most when MANY keys expire together, i.e., a cache avalanche); locking or coalescing is needed for a single key read at very high concurrency. A lock without a timeout can deadlock the system if the process holding it crashes mid-recompute.
Design a caching architecture for expensive analytics queries where results can be up to 5 minutes stale. Consider materialized views, result caching layers, cache invalidation on upstream changes, multi-tenancy isolation, and eviction strategies for large result sets.
Sample Answer
Direct answer
Analytics and business intelligence (BI) queries tolerate minutes of staleness in exchange for large latency and cost wins, so lean on materialized views and result caching aggressively, choosing the caching granularity (whole report, per-tile, per-query-result) based on how the dashboard is actually consumed.
Structured elaboration
- Materialized views: precompute and store the results of expensive aggregations on a schedule (or triggered by upstream data changes), so a dashboard read is a fast lookup against already-computed results rather than a live, expensive query against raw data.
- Result caching layers: cache the results of specific, frequently-run queries (a query-result cache keyed by the query and its parameters) for dashboards where the underlying data does not change often enough to justify a full materialized-view pipeline.
- Cache granularity: report-level caching (the whole dashboard's output) is simplest but coarse (any change forces a full recompute); tile-level (each widget/chart cached independently) allows partial invalidation when only some underlying data changed; query-result-level is the finest grain, useful when many different reports share underlying queries.
- Invalidation strategies for BI: time-to-live (TTL) is often sufficient here, since most BI use cases genuinely tolerate a bounded staleness window (minutes, sometimes hours); event-based invalidation (triggered by an upstream data-pipeline completion) is worth the added complexity specifically for dashboards where "as fresh as the last data load" matters more than a fixed time window; manual invalidation (an explicit refresh button) suits ad-hoc analysis tools where users want on-demand control.
- Cache warming/pre-computation: for dashboards viewed at predictable times (a morning operations review, a weekly business report), precomputing results just before that predictable access window avoids making the first viewer of the day pay the full, uncached computation cost.
- Balancing freshness, latency, and cost: the right TTL and caching granularity should map directly to how the business actually uses the dashboard, an operational dashboard checked continuously wants near-real-time and can justify more compute cost; a monthly strategic report tolerates hours of staleness and should be cached aggressively to save cost.
Worked example
A BI platform serving semantic-layer queries: for a query-result cache keyed by the query and its parameters, a report combining multiple underlying queries can serve most of its content from cache (queries that have not changed) while only recomputing the specific queries whose underlying data actually changed, rather than invalidating and recomputing the entire report on any single data update; this per-query granularity captures much of the tile-level caching benefit without needing the dashboard rendering layer itself to be cache-aware.
Trade-offs and pitfalls
Caching at the coarsest (whole-report) granularity for convenience, when the underlying data actually changes at different rates for different parts of the report, wastes the caching opportunity for the parts that rarely change and forces unnecessary staleness or unnecessary recomputation for the rest; choose granularity deliberately based on the actual update-rate heterogeneity within the report. Setting one TTL policy across every dashboard regardless of how it is actually used (operational versus strategic) either wastes freshness-driving compute cost where it is not needed, or under-serves freshness where it genuinely matters; tie the TTL choice to actual usage patterns.
Explain the purpose of caching in distributed systems. Define cache hit, miss, and hit ratio, and describe the typical benefits and tradeoffs of adding a cache to a service. Give concrete examples of workloads that benefit from caching (and why) and workloads where caching could be harmful.
Sample Answer
Direct answer
A cache is a fast, smaller copy of data kept close to where it is used, so repeated reads can be served without redoing expensive work (a database query, a network call, a heavy computation) every time. The core trade-off is speed and reduced load in exchange for the risk that the cached copy becomes stale relative to the real source of truth.
Structured elaboration
- What problems caching solves: latency (serving from memory or a nearby node is far faster than recomputing or fetching from a distant source), throughput/load (fewer requests reach the expensive backend), and cost (fewer database queries or external application programming interface (API) calls, which often cost money directly).
- Where caches typically live: client/browser (closest to the user, zero network cost on a hit), content delivery network (CDN) / edge (near the user but shared across many users), application in-memory (fast, but local to one process/instance), and a shared distributed cache like Redis or Memcached (shared across all instances in a region, one network hop away).
- Primary trade-offs: staleness (the cached copy may not reflect the latest write), added complexity (invalidation logic, cache-miss handling, monitoring another moving part), and memory cost (caches are not free storage).
- When caching helps: read-heavy workloads where the same data is requested repeatedly and can tolerate at least a little staleness, or where the underlying computation/fetch is expensive relative to a cache read.
- When caching is harmful: data that changes on every read (no repeated value to cache), workloads that are already write-heavy with low read repetition (cache churn without benefit), or correctness-critical data where any staleness is unacceptable and the added complexity of cache invalidation introduces more risk than the latency win is worth.
Worked example
An API endpoint that computes a dashboard aggregate over a large dataset in 800ms, requested 200 times per minute by the same handful of users, is a strong caching candidate: a 30-second time-to-live (TTL) cache serves nearly every request from cache after the first, cutting both latency (single-digit milliseconds instead of 800ms) and backend load by over 95 percent, for a staleness window most dashboard users will not notice. The same 30-second TTL applied to an account balance shown right after a deposit would be actively harmful, showing the user a stale, "wrong" number at the exact moment they are checking it.
Trade-offs and pitfalls
The most common mistake is caching by default rather than by evaluating whether the read pattern and staleness tolerance actually justify it; caching adds a second place data can be wrong (the cache disagreeing with the source of truth), and that failure mode does not exist at all if you never cache the data in the first place.
Unlock Full Question Bank
Get access to all 10 Caching Strategies and Distributed Caching interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.