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.
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 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.
Your product team must decide between a global CDN with many PoPs and a regional CDN with fewer PoPs. Explain the high-level trade-offs for each choice regarding latency, cache hit ratio, purge/invalidation latency, cost, data locality/regulatory constraints, and origin load. Provide guidance for making the decision for a global consumer app.
Sample Answer
Direct answer
More points of presence (PoPs) generally means lower latency and higher cache hit ratio for a global audience, but at higher cost and slower/more complex purge propagation across every location; a regional content delivery network (CDN) with fewer PoPs can be the right choice when your audience is concentrated and purge speed or cost matters more than shaving the last few milliseconds off distant users.
Structured elaboration
- Latency: more PoPs closer to users directly reduces round-trip time for a cache hit; the benefit is largest for a geographically spread audience and smallest for a concentrated one (a service with 95 percent of users in one country gets little latency benefit from PoPs on other continents).
- Cache hit ratio: more PoPs can actually LOWER hit ratio for a given piece of content if traffic gets spread thin across many locations (each PoP sees fewer requests for the same object, so each one independently experiences more cold-start misses) unless the CDN supports origin-shielding (a mid-tier cache that absorbs the first miss from any edge location so the true origin only sees one).
- Purge/invalidation latency: purging content from many PoPs takes longer to propagate globally than purging from a handful; if your content changes frequently and must invalidate quickly everywhere, fewer PoPs (or a CDN provider with fast global purge) matters more than raw PoP count.
- Cost: more PoPs and more total edge capacity generally costs more, both in direct CDN fees and in the operational complexity of monitoring and troubleshooting more locations.
- Data locality/regulatory constraints: some jurisdictions require caching (not just origin storage) to respect data-residency rules, which can rule out certain PoP locations for specific content regardless of latency benefit.
- Guidance for a global consumer app: a truly global consumer audience generally justifies a global CDN with many PoPs and origin shielding to protect hit ratio; a service concentrated in one or two regions gets most of the benefit from a regional CDN at lower cost and simpler operations.
Worked example
A media-serving platform with genuinely global traffic and frequently-updated, signed uniform resource locators (URLs) benefits from a global CDN with origin shielding (protecting hit ratio despite many PoPs) and a provider known for fast global purge propagation, since both broad reach and update speed matter for this content type; a B2B (business-to-business) internal tool used almost entirely by employees in one country would get little benefit from paying for a global PoP footprint and is better served by a regional CDN or even skipping a CDN in favor of a reverse proxy closer to the origin.
Trade-offs and pitfalls
Assuming "more PoPs is always better" ignores the hit-ratio dilution effect on low-traffic content; validate with actual per-PoP hit-ratio data, and use origin shielding if you choose a many-PoP provider. Purge latency is easy to overlook when evaluating CDN options by latency benchmarks alone; if your content changes often, test purge propagation time explicitly, not just cache-hit latency.
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.
You are designing cache invalidation for a globally distributed service where reads are frequent and writes happen in a primary region: describe strategies to keep caches coherent across regions. Discuss trade-offs between consistency, staleness, cost, and complexity (push invalidation, TTL, versioned keys, fanout updates).
Sample Answer
Direct answer
Keeping caches coherent across regions means picking, per data class, between a pull model (short time-to-live, TTL, that self-heals without any messaging) and a push model (explicit invalidation events fanned out to every region), and being explicit about the bounded-staleness window you are willing to accept in exchange for lower cost and complexity.
Structured elaboration
- TTL (pull-based): the simplest option. Every region's cache entry expires on its own after a fixed window; no cross-region messaging is required. Staleness is bounded by the TTL itself, cost is near zero, and it self-heals from any missed update (a lost invalidation event just means the entry expires normally at worst-case TTL). The downside is that staleness is guaranteed, not just possible, for the full TTL window.
- Push invalidation via messaging: on write, the writing region publishes an invalidation event (key, and optionally a version or tombstone) to a durable message bus; consumers in every other region apply it to their local cache. This gets close-to-immediate propagation (bounded by replication lag of the message bus, typically under a second) but adds a moving part that can itself fail, reorder, or duplicate, so you still need a TTL as a backstop.
- Versioned keys: instead of invalidating, bump a version token that is part of the cache key (
profile:123:v42); old versions simply age out via normal eviction rather than needing an active delete. This avoids race conditions where an invalidation arrives before the write it corresponds to, at the cost of needing a place to look up "what's the current version" (which itself needs to be fast and consistent). - Fanout updates: instead of invalidating (forcing every region to re-fetch), push the new VALUE itself to every region's cache. This trades more network bandwidth (sending full payloads, not small invalidation markers) for lower read-side latency (no cache-miss round-trip to origin after the update lands), and is worth it for small, very hot objects.
- Bounded staleness as the actual requirement: whichever mechanism you choose, state the staleness bound explicitly (e.g., "under 5 seconds in 99% of cases") and design the propagation pipeline's monitoring around that number, rather than treating "eventually consistent" as sufficient specification.
Worked example
A profile-update event published in the primary write region reaches a message bus with typical cross-region replication lag of 200 to 500 ms, plus consumer processing time of tens of milliseconds per region; a realistic end-to-end propagation time is under 1 second for the median case, with a long tail driven by consumer backlog during traffic spikes. If the product requirement is "profile changes visible within 5 seconds globally," a push-based invalidation pipeline with a 5-second TTL backstop comfortably meets it even if a specific invalidation event is dropped, because the TTL guarantees the bound independently.
Trade-offs and pitfalls
Relying purely on push invalidation without a TTL backstop means any lost, delayed, or duplicated event becomes an unbounded staleness bug with no self-healing mechanism; always pair push invalidation with a TTL ceiling. Fanout-updates for large or rarely-read objects wastes bandwidth pushing data nobody will read in some regions; reserve it for small, universally-hot keys. Versioned keys solve the ordering race but shift complexity to "how fast and how consistent is the version lookup itself," which can become its own single point of failure if not designed carefully.
Unlock Full Question Bank
Get access to all 13 Caching Strategies and Distributed Caching interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.