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.
How do you decide whether to introduce a cache for a given service endpoint? Describe the signals and measurements you would collect, the tests you would run (load, latency, profiling), and the criteria that justify adding an in-process cache, a shared cache (Redis), or a CDN. Include considerations for cost, operational complexity, and correctness.
Sample Answer
Direct answer
Decide whether to add a cache by measuring the actual read pattern (how often the same value is requested, how expensive it is to produce, and how much staleness is tolerable), not by defaulting to caching every endpoint; a cache with a low repeat-read rate or zero staleness tolerance is a cost with no real benefit.
Structured elaboration
- Signals to collect: request rate for the same key/query (does the same data actually get read repeatedly, or is nearly every read unique), the cost of producing the value (a fast, cheap lookup gains little from caching even if repeated), and the data's staleness tolerance (how quickly must a change be visible).
- Tests to run: a load test comparing latency and backend load with and without a proposed cache, and a profile of the actual query/computation to confirm it is genuinely a meaningful cost worth caching against.
- Criteria for choosing a cache tier: an in-process cache fits data that is cheap to duplicate per instance and does not need cross-instance consistency; a shared cache (Redis) fits data that benefits from being consistent across instances or too large to duplicate per instance; a content delivery network (CDN) fits public, non-personalized content that benefits from being close to users geographically.
- Cost: weigh the infrastructure and operational cost of adding a caching layer (a new dependency to monitor, secure, and keep available) against the actual load/latency benefit measured above; a marginal benefit may not justify the added complexity.
- Operational complexity: caching adds invalidation logic, a new failure mode (cache unavailable), and another thing to monitor; these costs are real even when the caching decision is otherwise sound, and should be weighed explicitly.
- Correctness: if the data's staleness tolerance is effectively zero (a value that must always reflect the absolute latest state, with no acceptable delay), caching adds risk without benefit, since any caching mechanism introduces at least a small window of potential staleness.
Worked example
An endpoint returning a real-time stock quote, requested uniquely per symbol per user with essentially no repeat reads within any meaningful window, and requiring zero staleness tolerance: this fails on both the "does the same value get read repeatedly" test and the "can staleness be tolerated" test, making it a poor caching candidate regardless of how expensive the underlying computation is. Contrast with a product description, read thousands of times per hour by different users for the same handful of popular items, changing rarely: this passes both tests clearly.
Trade-offs and pitfalls
Caching by default, without measuring the actual read-repetition rate, either wastes cache capacity on data that gets no benefit or, worse, introduces a staleness risk on data that could not tolerate it; always start from measurement, not habit. The decision is not binary per endpoint; the same service can have some data that benefits enormously from caching and other data (even on the same page) that should never be cached, and treating the whole endpoint uniformly misses that nuance.
Describe how HTTP caching works using Cache-Control, ETag, and Last-Modified headers. Explain how a CDN and a Service Worker might interact with those headers and describe a conditional GET flow including a 304 response. Provide one example where a Service Worker should bypass CDN semantics.
Sample Answer
Direct answer
HTTP caching is coordinated through response headers: Cache-Control tells any cache (browser, content delivery network, CDN) how long and under what conditions a response can be reused, and ETag/Last-Modified let a client revalidate a possibly-stale cached copy cheaply via a conditional request instead of re-downloading the full response.
Structured elaboration
- Cache-Control: directives like
max-age=<seconds>(how long the response is fresh),no-cache(must revalidate before use, but can still be stored),no-store(never cache at all), andprivate/public(whether shared caches like a CDN may store it) give fine-grained control over caching behavior. - ETag: an opaque identifier (often a hash) for a specific version of a resource; a client that has a cached copy sends
If-None-Match: <etag>on its next request. - Last-Modified: a timestamp-based alternative to ETag; a client sends
If-Modified-Since: <timestamp>. - Conditional GET / 304 flow: the client's cached copy has expired (its
max-ageelapsed) but might still be valid; instead of re-fetching the full body, it sends a conditional request withIf-None-MatchorIf-Modified-Since. If the resource has not actually changed, the server responds304 Not Modifiedwith no body, and the client's existing cached copy is revalidated as fresh; if it has changed, the server responds normally with the new body and headers. - CDN and Service Worker interaction: a CDN typically respects
Cache-Controldirectly, serving from its edge cache without contacting the origin untilmax-ageexpires. A Service Worker sits in the browser and can implement its own caching logic (including bypassing normal HTTP semantics entirely) via the Cache API andfetchevent interception, which is useful when the app needs offline support or caching behavior more sophisticated than standard headers allow. - When a Service Worker should bypass CDN semantics: for content the app knows is safe to serve instantly from a local cache regardless of what a content delivery network (CDN)'s time-to-live (TTL) says (e.g., app shell assets for instant repeat-visit loads), a Service Worker can serve from its own cache first and revalidate in the background (a stale-while-revalidate pattern implemented at the application layer), rather than waiting on the CDN's standard freshness check.
Worked example
A JS bundle served with Cache-Control: max-age=31536000, immutable and a content-hashed filename (app.a1b2c3.js) never needs revalidation at all, since a new deploy produces a new filename/URL; "invalidation" is simply pointing to the new URL. A frequently-changing API response served with Cache-Control: max-age=0, must-revalidate plus an ETag lets the client always check freshness cheaply (a 304 response, no body) without re-downloading the full payload on every request when nothing has actually changed.
Trade-offs and pitfalls
Setting Cache-Control: public on a response containing per-user or sensitive data lets shared caches (a CDN, a corporate proxy) serve one user's private data to another; always use private or no-store for personalized responses. Relying on Last-Modified timestamp granularity (often only second-level precision) can miss legitimately distinct versions of a resource that changed within the same second; ETag avoids this by tying validation to actual content, not a coarse timestamp.
You observe that total request latency rose despite a high cache hit rate. Outline a step-by-step debugging plan to identify the root cause, including what metrics and traces you would collect.
Sample Answer
Direct answer
When latency rises despite a healthy hit ratio, the cache is doing its job (finding data), so the investigation shifts away from "is data cached" toward "what is slow about serving a cached value": serialization cost, network hops, object size, or an inconsistent-key problem that is quietly generating hidden extra misses within an otherwise-healthy aggregate hit ratio.
Structured elaboration
- Serialization/deserialization cost: a growing or changed payload shape can make encoding/decoding on every cache hit meaningfully slower even though the read itself succeeded; check whether payload size or format changed recently.
- Object size: a larger cached object takes longer to transfer over the network even on a hit; compare current average object size against historical baselines for a regression.
- Network hops / cache network topology: a routing change (a new proxy layer, a cross-availability-zone hop that used to be same-zone) adds latency to every hit without affecting whether it is a hit at all; check whether the cache client's network path to the cache changed recently.
- Cache misses due to inconsistent keys: a subtle bug (a key that includes a field with slightly different formatting on different code paths) can cause SOME requests to always miss while the AGGREGATE hit ratio still looks acceptable if that subset is a small fraction of total traffic; segment hit ratio and latency by endpoint or request shape, not just in aggregate.
- Backend cascading delays: if the "cache hit" path itself calls out to something else after the cache read (a second lookup, an enrichment call), a slowdown there shows up as rising latency without touching the cache's own hit ratio at all.
- Debugging plan: start with distributed tracing to see where time is actually spent within a request (cache read, deserialization, post-cache-hit processing), compare payload sizes and network path over time, and segment metrics by endpoint/request-shape rather than relying purely on aggregate numbers that can hide a localized problem.
Worked example
A service's overall hit ratio holds steady at 92 percent, but p99 latency has crept up over two weeks; tracing shows the cache READ itself is still fast (single-digit milliseconds), but deserialization time for the cached payload has grown from 2ms to 40ms, correlating with a recent change that added several new fields to the cached object; the fix is either trimming the payload to only what is actually needed, or switching to a faster serialization format, not anything related to the cache layer itself.
Trade-offs and pitfalls
Assuming "hit ratio is fine, so the cache isn't the problem" and stopping the investigation there is a common mistake; a hit ratio number says nothing about how expensive it is to USE a cached value once found. Aggregate metrics can hide a localized problem affecting a small but meaningful subset of traffic; segment by endpoint or request type before concluding a metric is uniformly healthy.
You must choose between Redis and Memcached to implement a session store for a web app. List trade-offs and recommend one choice. Consider persistence, data types, replication/HA, memory efficiency, eviction semantics, and operational features such as monitoring and backup.
Sample Answer
Direct answer
Choose Redis when you need richer data structures, persistence, or replication/high-availability (HA) built in; choose Memcached when you need the simplest possible pure key-value cache with the lowest per-operation overhead and multi-threaded read scaling out of the box.
Structured elaboration
- Data types: Redis supports strings, hashes, lists, sets, sorted sets, and more, useful when the cache itself needs to do more than store opaque blobs (e.g., a sorted set for a leaderboard). Memcached only stores simple key-value byte strings.
- Persistence: Redis can persist to disk (RDB snapshots, append-only file, AOF) so data can survive a restart; Memcached is purely in-memory with no persistence, so a restart is always a full cache flush.
- Replication / high availability: Redis has built-in replication and clustering (Sentinel for failover, Cluster for sharding); Memcached has no native replication, relying on the client or an external layer for HA.
- Memory efficiency: Memcached's simpler data model generally has lower per-key memory overhead for pure key-value use cases; Redis's richer data structures and features carry some additional overhead.
- Eviction semantics: both support least-recently-used (LRU) style eviction, but Redis offers more configurable policies (
allkeys-lru,volatile-ttl,allkeys-lfu, and others) versus Memcached's simpler slab-based LRU. - Operational features: Redis has a larger ecosystem for observability, Lua scripting for atomic multi-step operations, and pub/sub; Memcached's multi-threaded architecture can give it an edge on raw throughput for simple get/set at very high concurrency on a single node.
Worked example
For a session store: if sessions are pure key-value blobs, Memcached is a perfectly reasonable, simpler choice. If sessions need persistence across a restart (avoiding logging every user out simultaneously) or replication for HA, Redis with AOF persistence and Sentinel-managed failover is the safer choice, at the cost of a slightly more complex operational footprint.
Trade-offs and pitfalls
Choosing Redis "because it can do more" for a workload that is genuinely simple key-value adds operational surface area (persistence tuning, replication topology) without benefit; match the tool to the actual requirement. Memcached's lack of native replication means a node loss is a hard cache-miss event for everything that node held, with no automatic failover; that must be an explicit, accepted trade-off, not an oversight.
Describe a multi-level caching architecture for a web service: L1 in-process cache (per instance), L2 shared cache (Redis cluster), and a CDN in front of static assets. Explain read and write flows, benefits for latency and throughput, and the primary consistency and invalidation challenges for each layer.
Sample Answer
Direct answer
Layer the caches by how expensive a miss at that layer is and how often the content changes: content delivery network (CDN) edge for static/shared assets closest to the user, a regional shared cache (e.g., Redis) for personalized-but-cacheable data, and an application in-process cache for the hottest few keys where even a network hop to the regional cache is too slow, with each layer's time-to-live (TTL) and invalidation strategy sized to that layer's job.
Structured elaboration
- CDN/edge layer: caches fully static or long-TTL content (images, JS/CSS bundles, and cacheable HTML fragments for anonymous/public views) at points of presence near the user. This absorbs the largest fraction of read volume for almost no cost per request and should hold anything that does not vary per-user.
- Regional distributed cache (Redis/Memcached): serves personalized or frequently-changing data shared across all app instances in a region (product details, prices, computed recommendations). Requests per second (RPS) here are much lower than at the edge because the edge already absorbed the static traffic, but this layer must handle write-driven invalidation correctly since content changes.
- Application in-process (L1) cache: for the small set of extremely hot keys (a handful of top-selling products, a config flag read on every request), an in-process cache avoids even the network round-trip to the regional cache. It is the fastest layer and also the hardest to keep coherent, because every app instance has its own copy; use a short TTL or an event-driven invalidation signal (pub/sub) rather than relying on the regional cache alone.
- Database-side / materialized views: for expensive aggregate queries, a materialized view or a query-result cache sits closest to the database, reducing load on the primary store even when the higher layers miss.
- Invalidation strategy per layer: static assets at the edge use content-hashed URLs so "invalidation" is really just a new URL (no purge needed); the regional cache uses event-driven invalidation on write (an order/price update publishes an invalidation for that product's key); the in-process L1 layer uses a short TTL (seconds) plus a lightweight pub/sub signal, because coordinating a purge across every instance is expensive and slow.
- Sizing to a concrete target: pick numbers for the design (RPS, latency budget, SKU/product count) and work backward: at, say, 100,000 RPS globally with a 90 percent edge-cacheable static-asset ratio, only about 10,000 RPS reach the regional application tier, which then needs to comfortably serve that load with sub-50ms p95 latency from cache.
Worked example
For a product catalog with 1,000,000 stock-keeping units (SKUs) and 50,000 RPS globally: static images and category pages are edge-cached (roughly 35,000 RPS absorbed at essentially zero backend cost). The remaining ~15,000 RPS of personalized/price-sensitive reads hit the regional Redis cache; with a realistic 95 percent hit ratio there, the origin database sees roughly 750 RPS, which is a design a mid-sized read replica tier handles comfortably. Price changes (a write path) publish an invalidation event per SKU, propagated to the regional cache and any in-process L1 caches holding that SKU within roughly 100 to 500 ms, well inside a "price must update within seconds" product requirement.
Trade-offs and pitfalls
Adding more layers adds more places for staleness to hide; a change that only invalidates the regional cache and forgets the in-process L1 layer will show correct data to some app instances and stale data to others, which is a confusing bug class to debug. Do not put personalization-sensitive content at the CDN edge unless you are using edge compute (e.g., edge functions) that can vary the response per user; naively caching personalized HTML at a shared edge node leaks one user's data to another. Every additional layer is also an additional operational surface (its own metrics, its own failure mode, its own on-call runbook); do not add a layer unless the sizing math shows the layer above it cannot meet the latency or load target alone.
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.