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.
In Node.js (TypeScript), implement a simple cache-aside wrapper function fetchWithCache(key, fetchFn, ttlSeconds) that: (1) checks Redis for key, (2) on miss calls fetchFn() to get fresh value, (3) stores result in Redis with TTL, (4) handles Redis errors by falling back to fetchFn, and (5) ensures JSON serialization. Provide the function and then describe concurrency considerations for simultaneous cache misses.
Sample Answer
Approach
Implement fetchWithCache as a thin wrapper: check the cache first, and on a miss (or an error reading the cache) call the underlying fetch function directly so a cache outage degrades to "no caching" rather than an outright failure. Store successful results with the given time-to-live (TTL) after JSON-serializing them, and treat a cache write failure as non-fatal (log it, still return the fresh value).
import { createClient, RedisClientType } from "redis";
type FetchFn<T> = () => Promise<T>;
export async function fetchWithCache<T>(
redis: RedisClientType,
key: string,
fetchFn: FetchFn<T>,
ttlSeconds: number
): Promise<T> {
try {
const cached = await redis.get(key);
if (cached !== null) {
return JSON.parse(cached) as T;
}
} catch (err) {
// Redis unavailable or a bad payload: fall through to origin, do not fail the request.
console.error("cache read failed, falling back to origin", { key, err });
}
const fresh = await fetchFn();
try {
await redis.set(key, JSON.stringify(fresh), { EX: ttlSeconds });
} catch (err) {
console.error("cache write failed, returning fresh value anyway", { key, err });
}
return fresh;
}
Key points
Cache read and cache write failures are both caught separately and treated as non-fatal, so a Redis outage degrades to hitting the origin on every request rather than breaking the caller. fetchFn is only ever called once per request (on a cache miss), which keeps the origin call count predictable per request even though it is not yet protected against concurrent misses on the same key.
Complexity
Time is O(1) plus the cost of fetchFn on a miss (dominated by whatever fetchFn does, typically a database or network call); space is O(1) per cached key, bounded by the serialized payload size.
Concurrency considerations for simultaneous cache misses
As written, N concurrent requests that all miss the same key will all call fetchFn independently, which is correct but not efficient: it does not prevent a stampede. To fix that, add request coalescing: acquire a short-lived per-key lock (e.g., SET key:lock value NX PX 5000) before calling fetchFn; if the lock is already held, either wait briefly and retry the cache read, or call fetchFn directly as a fallback if waiting exceeds a bounded timeout, so a crashed lock-holder cannot permanently stall other requests.
Edge cases
A fetchFn that throws should propagate the error rather than being silently swallowed, since callers need to know the underlying fetch failed; only cache read/write errors should be treated as non-fatal, never a fetch failure. Values that fail to JSON.parse (a corrupted or incompatible cached payload) should be treated the same as a cache miss, not as a fatal error.
Explain the trade-offs between client-side caching (in-process or browser) and a server-side shared cache (Redis). From an operations standpoint, what concerns differ between the two approaches?
Sample Answer
Direct answer
Client-side (in-process or browser) caching is faster and needs no network hop but is invisible and hard to invalidate from the server; a server-side shared cache (Redis) is slower per read (a network hop) but is centrally observable, controllable, and consistent across every consumer.
Structured elaboration
- In-process caching: fastest possible access (no network at all), but exists as N independent copies across N instances, invisible to any centralized monitoring or invalidation mechanism unless you specifically build one (e.g., pub/sub to every instance).
- Browser caching: similarly fast for the end user, but the server has essentially no direct control once data leaves it; "invalidation" really means waiting out a time-to-live (TTL) or changing a versioned resource identifier.
- Server-side shared cache (Redis): a single, centrally-managed copy; invalidation is a single operation that immediately affects every consumer, and its state is directly observable via standard monitoring, at the cost of a network round-trip on every access.
- Operational concerns for a shared server-side cache: capacity planning, replication/failover for availability, and security (access control, encryption) are all first-class operational concerns that a purely in-process or browser cache does not have in the same way, since those are either per-instance (in-process, trivially "available" as long as the instance is up) or entirely outside your infrastructure (browser).
- Service-mesh sidecar caching: a variant worth naming, a sidecar proxy running alongside each service instance can cache responses transparently at the network layer; this gets some of in-process caching's speed benefit without embedding caching logic in application code, but invalidation and consistency questions are similar to any other local-cache design (each sidecar has its own copy).
- A hybrid, fast-tier-plus-persistent-tier design: combining a fast in-memory tier for hot items with a persistent, larger tier for warm items (promotion/demotion between them based on access) gets some of both worlds' benefits, at the cost of managing two tiers' worth of operational complexity.
Worked example
An application caching a rarely-changing configuration value both in-process (near-zero latency access on every request) and in Redis (as the source the in-process cache warms from, and as what gets explicitly invalidated on a config change) gets the speed benefit of in-process access for the common case while still having a centrally controllable invalidation point; the in-process copies use a short TTL as a backstop in case a pub/sub-based invalidation signal is missed by a given instance.
Trade-offs and pitfalls
Relying purely on in-process caching for data that changes and needs prompt, reliable invalidation across many instances is a common design mistake; without a centralized signal (or at least a short backstop TTL), some instances can serve stale data indefinitely after a change. From an operations standpoint, a shared server-side cache is a dependency you must monitor, secure, and plan capacity/failover for, in a way an in-process cache simply is not; that operational surface is a real cost, not just a technical detail.
A payments ledger requires strong correctness when updating balances. Compare write-through caching (synchronous write to cache and datastore) vs write-behind (asynchronous background writes). For each, discuss durability, read visibility immediately after write, failure modes, and techniques (idempotency, ordering) to preserve correctness. Which approach would you choose and why?
Sample Answer
Direct answer
For a durability-sensitive service like payments, prefer write-through (synchronous write to both cache and datastore) or cache-aside with synchronous invalidation over write-behind, because write-behind's asynchronous flush introduces a data-loss window that is unacceptable when the data is money or an authentication state.
Structured elaboration
- Write-through for payments: every write goes to the cache and the datastore together, synchronously, before acknowledging the caller; reads are always fresh, and there is no window where an acknowledged write could be lost, at the cost of higher write latency (paying for both writes on the request path).
- Cache-aside with synchronous invalidation for sessions: a session service that must reflect login/logout changes quickly can use cache-aside (only cache what is actually read) with an invalidation triggered synchronously on logout, rather than waiting for a time-to-live (TTL) to expire; this balances the simplicity of cache-aside with the responsiveness a security-sensitive change needs.
- Why write-behind is the wrong default here: write-behind acknowledges the write before it is durably applied to the datastore; a crash in that window loses the write entirely, which is an acceptable trade for a metrics counter and not acceptable for a payment or a security-relevant state change.
- Trade-off in consistency versus write amplification: write-through pays extra write latency and writes data that might never be read (caching every write regardless of read demand); cache-aside with synchronous invalidation only caches what is actually requested, trading a small amount of extra invalidation-path complexity for less wasted cache capacity.
- Failure modes to consider: with write-through, a failure writing to EITHER the cache or the datastore must be handled explicitly (does the whole operation fail, or does it proceed with just the datastore write and treat the cache write as best-effort); an inconsistent partial failure here is exactly the kind of subtle bug that durability-sensitive systems cannot tolerate silently.
Worked example
A session service where sessions must invalidate within seconds of logout: cache-aside with an explicit, synchronous invalidation call on logout (rather than relying on a TTL to eventually expire the session) meets that requirement directly; a subsequent read after logout misses the cache, goes to the datastore, finds the session revoked, and correctly denies access, all within the same request cycle rather than waiting out a TTL window during which a logged-out session token would still work.
Trade-offs and pitfalls
Choosing write-behind for its throughput benefit on a durability-sensitive path is a common and dangerous shortcut; always name the data-loss window explicitly and get an explicit sign-off that it is acceptable before using it, rather than defaulting to it for performance reasons alone. A write-through implementation that treats the cache write as best-effort (silently swallowing cache write failures) can mask a growing coherence problem between cache and datastore; log and monitor cache write failures even when they are non-fatal to the request.
Design a graceful degradation mechanism for when the caching layer becomes unavailable or overloaded. Propose fallback patterns, thresholds and protection mechanisms to prevent origin overload, and how to surface degraded behavior to users and operators.
Sample Answer
Direct answer
Graceful degradation means the application keeps functioning, at reduced quality or freshness, when the cache is unavailable, rather than the cache's failure becoming the application's failure; that requires a fast, automatic fallback path plus protection so the fallback itself does not overwhelm the origin.
Structured elaboration
- Direct origin fetch with a circuit breaker: when cache calls start failing or timing out, a circuit breaker trips after a threshold of failures and stops attempting cache calls for a cooldown period, falling back straight to the origin; this avoids adding cache-timeout latency on top of every request during an outage.
- Serve stale content: if a recently-expired or slightly-stale cached value is still available (even if technically past its time-to-live, TTL), serving it is often better than a full origin round-trip or an error, for data where a few extra minutes of staleness is an acceptable trade for availability.
- Limited origin admission (protection against overload): because the cache's job is normally absorbing load, a cache outage means the origin suddenly sees a much larger fraction of traffic; apply rate limiting or admission control at the origin's edge so it degrades gracefully (serving a fraction of requests well) rather than falling over entirely trying to serve all of them.
- Thresholds and protection mechanisms: define explicit thresholds for when to trip the circuit breaker (e.g., error rate or timeout rate exceeding X percent over a rolling window) and when to attempt recovery (a periodic "half-open" probe to check if the cache has recovered, per the standard circuit-breaker pattern).
- Surfacing degraded behavior: expose a clear operational signal (a metric, a status indicator) that the system is currently in degraded mode, both for on-call visibility and, where appropriate, for user-facing messaging (e.g., "results may be slightly delayed") rather than degrading silently.
Worked example
A product-listing page normally reads from cache with a 20ms budget; when the cache becomes unavailable, a circuit breaker trips after 5 consecutive timeouts within 10 seconds, and subsequent requests skip the cache call entirely, going straight to the origin with a rate limiter capping concurrent origin requests at a level the database can sustain (say, 500 concurrent queries), while excess requests receive a fast, clearly-labeled degraded response (a cached-but-stale value, or a simplified fallback) rather than queueing behind an overwhelmed origin.
Trade-offs and pitfalls
A circuit breaker with too low a failure threshold trips on ordinary transient blips, causing unnecessary degradation; too high a threshold delays the fallback until real damage has already occurred. Serving stale content is a correctness trade-off that must be explicitly acceptable for that specific data; do not apply it uniformly to data where staleness during an outage is actually harmful (e.g., real-time inventory during checkout).
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 Caching Strategies and Distributed Caching interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.