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 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.
You are asked to reduce p99 latency for a critical service by 50% within 3 months. Provide a prioritized plan that uses caching and asynchronous processing where appropriate. Include measurable milestones, stakeholders to involve, quick wins, risk mitigation, and how you'll validate improvements against SLOs.
Sample Answer
Direct answer
A credible plan to cut p99 (99th percentile) latency by 50 percent in 3 months starts by measuring where the current p99 time is actually going, so caching effort is spent on the specific paths where it will move the number, not applied uniformly across the whole service.
Structured elaboration
- Milestone 1 (weeks 1 to 2): measure and prioritize: instrument end-to-end latency with breakdowns per stage (cache lookup, database query, downstream calls); identify the top few endpoints or code paths contributing most to the current p99, since a small number of slow paths usually dominate the tail.
- Milestone 2 (weeks 3 to 6): quick wins: add caching (or fix an already-present but under-tuned cache: wrong time-to-live (TTL), low hit ratio, missing warm-up) for the highest-impact, easiest-to-cache paths identified in milestone 1; these are the fastest way to show measurable progress and build stakeholder confidence.
- Milestone 3 (weeks 6 to 10): asynchronous processing where appropriate: for paths where the slow part is not cacheable (a write, a side effect) but can be deferred without hurting the user experience, move it off the synchronous request path.
- Milestone 4 (weeks 10 to 12): validate and harden: confirm the p99 improvement holds under real production load (not just a synthetic benchmark), add monitoring so a regression is caught automatically, and document the new baseline.
- Stakeholders to involve: the on-call/SRE team (for monitoring and rollout safety), product owners of the affected endpoints (to confirm caching-introduced staleness is acceptable), and whoever owns the origin systems being protected (database, downstream services), since reducing their load is often a secondary benefit worth communicating.
- Risk mitigation: roll out caching changes gradually (canary a percentage of traffic) rather than all at once, and keep a fast rollback path for any change that introduces a correctness regression.
- Validating against service-level objectives (SLOs): track p99 latency on a dashboard against the SLO target continuously through the project, not just at the end, so a milestone that is not moving the number is caught and re-prioritized early rather than discovered in month 3.
Worked example
If measurement shows a product-details endpoint contributes disproportionately to overall p99 because of an uncached, expensive database join, adding a cache-aside layer with a suitable time-to-live (TTL) for that specific endpoint might cut ITS p99 from 400ms to 60ms; if that endpoint represents a large enough share of overall traffic, the service-wide p99 improvement could plausibly approach or exceed the 50 percent target from this one change alone, which is exactly why prioritizing by measured impact (milestone 1) matters more than spreading effort evenly.
Trade-offs and pitfalls
Committing to a 50 percent number before measuring where the current latency actually goes risks promising a target the available levers cannot hit; the honest first step is measurement, even if it means the initial plan is provisional. Chasing quick wins without validating they hold under full production load (not just a staging benchmark) risks a milestone that looks done but regresses the moment real traffic returns.
Design a cache key naming and versioning strategy for a microservice whose response schema changes frequently. Explain how you would support rolling upgrades, avoid stale data breaking clients, and manage key explosion over time with examples of key formats and migration steps.
Sample Answer
Direct answer
Embed a namespace version in the cache key itself (product_v42:123) so a bulk invalidation is a single atomic version bump rather than deleting millions of individual keys, and old versions simply age out via normal eviction instead of needing an active cleanup pass.
Structured elaboration
- How it works: reads and writes always go through a lookup of "what is the current namespace version" (cached itself, refreshed rarely) and construct the key as
entity_v{version}:{id}; when a schema or bulk change happens, bump the version atomically in one place, and every subsequent read/write automatically targets the new namespace, with old-version keys becoming unreachable (not actively deleted, just no longer referenced). - Atomic bulk invalidation via version bump: this is the core benefit; rather than issuing a delete for every affected key (expensive, slow, and racy if new writes happen during the delete), one atomic increment of a version counter instantly redirects all future reads/writes to the new namespace.
- Garbage-collecting old namespaces: because old-version keys are simply unreferenced, not deleted, they occupy memory until evicted normally by the cache's eviction policy (least-recently-used or time-to-live based); if faster reclamation is needed, a background sweep can explicitly delete keys matching the old version prefix, but this is an optimization, not a correctness requirement.
- Single-point-of-failure concerns for the version pointer: the "current version" lookup itself must be fast, highly available, and consistent, since every cache operation depends on it; storing it in the same cache cluster (as a well-known key) is common, but that makes the version pointer's own availability a dependency for the whole cache, worth explicitly designing for (e.g., a short local cache of the version value with a brief TTL, so a momentary version-lookup failure does not stall every request).
- Compare-and-swap (CAS) on versioned keys: for concurrent updates to the same entity, a versioned key naturally supports CAS semantics (only apply if the version you are updating still matches what you read), avoiding a stale-overwrite race without needing an explicit lock.
Worked example
A microservice's response schema changes in a way that would make previously-cached responses invalid; rather than deleting potentially millions of cached response keys (slow, and racy against concurrent writes happening during the delete), bumping the namespace version from v41 to v42 in one atomic operation instantly means every read constructs a v42 key, gets a miss, and repopulates with the new schema, while old v41 entries simply age out of the cache over the following minutes to hours via normal eviction.
Trade-offs and pitfalls
If the version pointer lookup becomes slow or unavailable, every cache operation that depends on it is affected, so treat its own latency and availability as a first-class design concern, not an afterthought. Not garbage-collecting old-version keys at all (relying purely on eviction) can leave a meaningful amount of dead memory around if the cache is large and eviction pressure is low; monitor and, if needed, add an explicit sweep for versions old enough to be safely deleted.
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.
Describe common cache eviction policies (LRU, LFU, FIFO, and TTL-based expiry). For each policy explain: how it decides what to evict, what access patterns it suits best, and give a short concrete example scenario (e.g., session caching, hot-working set, analytics counters).
Sample Answer
Direct answer
Least Recently Used (LRU) evicts by recency, Least Frequently Used (LFU) evicts by access count, First-In-First-Out (FIFO) evicts by insertion order regardless of access pattern, and time-to-live (TTL) based expiry evicts by a fixed age regardless of how popular the item is; each fits a different assumption about what predicts future value.
Structured elaboration
- LRU: evicts the item that has gone longest without being accessed. Fits workloads with strong temporal locality (a session that is hot right after login, then cold); weak spot is a one-time scan flushing genuinely popular items.
- LFU: evicts the item with the fewest accesses (often with decay). Fits a stable popularity distribution (a small set of perennially popular catalog items); weak spot is that brand-new items start at zero and can be evicted before they get a chance to prove their popularity.
- FIFO: evicts the oldest-inserted item regardless of how often it has been accessed since. It is the simplest and cheapest to implement (no access-order bookkeeping needed on every read), and fits workloads where recency of insertion genuinely correlates with relevance (e.g., a queue of recent events), but performs poorly for general-purpose caching where popular older items get evicted just because they were inserted first.
- TTL-based expiry: evicts (expires) an item after a fixed duration regardless of access pattern; it is really answering a different question ("how stale is too stale") rather than "what should we keep when we're full," and is often combined with one of the other policies as a ceiling on staleness rather than used as the sole eviction mechanism.
- Choosing for a workload: session caching (LRU: recency-driven), hot-working-set analytics (LFU or a hybrid: stable popularity), analytics counters with a natural expiry (TTL: staleness is the real constraint, not memory pressure).
Worked example
A cache of user session objects with occasional heavy churn (many users logging in and out in bursts) fits LRU well: sessions are hot right after login and cold afterward, and LRU naturally keeps the currently-active sessions warm through the churn. LFU would be a poor fit here because it would take time to "learn" a new burst of sessions are popular, during which it might evict genuinely active sessions in favor of older sessions that accumulated more historical hits.
Trade-offs and pitfalls
FIFO is cheap but usually the wrong default for a general-purpose cache; it is easy to reach for because it is simple to implement, but it ignores the one signal (access pattern) that actually predicts value. Do not conflate TTL (a staleness ceiling) with an eviction policy chosen for memory pressure; a cache can need both simultaneously for different reasons.
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.