Caching Strategies & In-Memory Optimization Questions
Designing cache layers to cut redundant work and speed up reads, and the correctness costs that come with them. Covers cache placement across client, CDN, application, and in-memory store tiers, including platform-specific caching on mobile (in-memory and disk caches on iOS and Android, secure on-device token storage) and in the browser (localStorage, IndexedDB, Service Workers). Covers eviction policies, TTLs, write-through vs write-back, warming, and invalidation, plus cache stampede and thundering-herd mitigation when a hot key expires under load. Also covers using an in-memory store like Redis directly rather than only as a cache: distributed locks, counters, rate limiters, and leaderboards. Includes distributed and sharded cache architecture (replication, failover, sizing, migration) and the operational side of running one: health monitoring, alerting, and incident runbooks, plus the security and privacy risks caching introduces, such as cache poisoning and caching PII across shared tenants. Emphasizes hit-rate reasoning and the staleness/consistency trade-offs caching introduces.
Explain what caching is in the context of web frontends. List the typical layers where caching occurs (browser, CDN/edge, origin, application, data store), describe three key benefits caching provides for user-facing applications, and name one common downside or risk when caching is misconfigured.
Sample Answer
What caching is
Caching is storing a copy of data somewhere faster or closer to where it's needed, so a repeat request can be answered from that copy instead of redoing the original expensive work (a network round trip, a database query, a heavy computation). For a web frontend, "faster or closer" usually means physically closer to the user's browser and cheaper to reach than the original source.
The typical layers, from closest to the user to furthest
- Browser: the browser's own HTTP cache stores responses (scripts, styles, images, sometimes API responses) directly on the user's device; a cache hit here costs zero network time.
- CDN/edge: a content delivery network, a network of servers geographically distributed to sit close to users, caches responses so a user in another country doesn't have to reach your single origin server for something already cached nearby.
- Origin server: the application server itself may cache in front of its own downstream calls (for example, caching a rendered page fragment).
- Application: an in-process cache inside the running application (a plain in-memory map, valid only for that one process's lifetime).
- Data store: a dedicated cache like Redis or Memcached sitting in front of the database, so repeated identical queries don't re-hit the database.
Three key benefits
- Lower latency for users: a cache hit is served from something fast and nearby instead of round-tripping to a database or a distant server, which is the difference users actually feel as "the app feels fast."
- Reduced load on the backend: every request served from cache is one fewer request the database or origin server has to handle, which matters directly for cost and for surviving traffic spikes.
- Better resilience: a CDN absorbs a sudden traffic spike that would otherwise overwhelm the origin, and in some designs a cache can keep serving a slightly stale-but-working response even if the origin is briefly unavailable, rather than the user seeing an outright error.
One common downside when caching is misconfigured
Serving stale or, worse, wrong data. The most damaging version in a frontend context is a personalization leak: caching a page that includes one user's private data (their name, their cart, their account details) at a SHARED layer like a CDN, so a completely different user requesting the same URL gets served User A's cached, personal data. This happens when a response varies per-user but the cache configuration doesn't know that (missing or wrong Cache-Control / Vary headers), and it is one of the more serious classes of bug caching can introduce, not just an inconvenience.
A hot key in your system is drawing so many concurrent requests that its expiry threatens to stampede the origin. What could you do on the client and what could you do on the server to prevent that, and how would you decide which side should own the fix?
Sample Answer
Direct answer
Client and server can both blunt a stampede, but they solve different halves of the problem.
Client-side techniques reduce how many redundant requests the server ever SEES, which is an
optimization. Server-side techniques guarantee that even if every client somehow still asks at
once, the origin only does the expensive work once, which is the actual safety net. Own the fix
on the server whenever you cannot control or trust every caller, a public API, other internal
services, retried background jobs. Use client-side techniques as a genuinely worthwhile first
line of defense whenever you DO control the client, because they save a round trip entirely
rather than just making it cheap.
Structured elaboration
Client-side options:
- Request deduplication (single-flight): if the client is already waiting on a request for the
same key, a second call from a different part of the interface reuses that same in-flight
promise instead of firing a second network call. Data-fetching libraries commonly do exactly
this by default. - Time-to-live (TTL) jitter: instead of every client caching a response for exactly the same
fixed duration, add a small random offset (55 to 65 seconds instead of exactly 60, say), so
thousands of clients that fetched at roughly the same moment don't all expire and re-request
at the same instant. - Backoff with jitter on retry: if a request fails or is rejected, retrying immediately just adds
to the pile; randomized exponential backoff spreads retries out instead.
Server-side options: distributed locking (a lock held in Redis or a similar shared store so only one process is allowed to recompute a given key at a time, while everyone else waits for that result); request coalescing at the server or gateway layer (multiple concurrent requests for the same key are collapsed into a single origin call, and every caller gets that one result); probabilistic early expiration (a cache entry is refreshed proactively, a little before its TTL actually runs out, with a small and growing random chance as expiry nears, so refreshes get spread out instead of all landing on the exact expiry instant); and stale-while-revalidate (serve the old, just-expired value immediately to the caller while refreshing it in the background, so nobody waits on a slow re-fetch), the same techniques that apply to the general stampede problem, applied at the layer that actually talks to the origin.
Worked example
Client-side request coalescing, implemented directly and verified to produce exactly one
underlying network call for 12 simultaneous callers of the same key:
const inFlight = new Map(); // key -> Promise currently resolving that key
let networkCallCount = 0;
function simulateNetworkFetch(key) {
networkCallCount += 1;
return new Promise((resolve) => setTimeout(() => resolve(`value-for-${key}`), 50));
}
function fetchDeduped(key) {
if (inFlight.has(key)) return inFlight.get(key); // piggyback on the in-flight request
const promise = simulateNetworkFetch(key).finally(() => inFlight.delete(key));
inFlight.set(key, promise);
return promise;
}
async function main() {
const callers = Array.from({ length: 12 }, () => fetchDeduped('product:42'));
const results = await Promise.all(callers);
console.log('networkCallCount:', networkCallCount);
console.log('all callers got the same value:', new Set(results).size === 1);
}
main();
Run with Node.js. Actual output:
networkCallCount: 1
all callers got the same value: true
Twelve simultaneous callers inside the same client produced exactly one network request. This
ONLY protects against redundant calls originating from that one client process; it does nothing
about ten thousand other users' devices all doing the same thing at the same second, which is
exactly why the server still needs its own, independent protection.
Trade-offs and pitfalls
- Client-side fixes cannot be the ONLY defense for anything reachable by clients you don't fully
control, a mobile app you don't own the source of, a third-party integration, a retried cron
job, because you cannot force them to implement your deduplication logic. Treat client-side
work as a latency and cost optimization on top of a server-side guarantee, never as a
substitute for it. - TTL jitter is easy to skip by accident: if every client independently computes the "same"
expiry from a shared, server-provided timestamp without adding its own jitter, you can
accidentally synchronize thousands of clients instead of desynchronizing them. - Deciding which side owns the fix is really a trust question. Can every caller's behavior be
guaranteed? If yes, client-side alone might be enough for an internal-only path; if no, the
common case for anything public, server-side ownership is non-negotiable and client-side work
is a bonus, not a plan.
Write a service worker fetch handler (in JavaScript) that applies a stale-while-revalidate strategy for static assets under '/static/' and a network-first strategy with a short timeout for API requests under '/api/'. The handler should update caches appropriately and avoid blocking the response while updating caches.
Sample Answer
Fetch handler
// sw.js
const STATIC_CACHE = 'static-v1';
const API_CACHE = 'api-v1';
const API_TIMEOUT_MS = 800;
function timeout(ms) {
return new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')), ms));
}
// stale-while-revalidate: return the cached copy immediately (or wait on the
// network only when there is no cached copy yet), and always kick off a
// background fetch that refreshes the cache for next time without making the
// current response wait on it.
async function handleStaticRequest(request) {
const cache = await caches.open(STATIC_CACHE);
const cached = await cache.match(request);
const networkUpdate = fetch(request)
.then((response) => {
if (response && response.ok) cache.put(request, response.clone());
return response;
})
.catch(() => undefined);
if (cached) return cached; // don't await networkUpdate, let it run in the background
const networkResponse = await networkUpdate;
if (networkResponse) return networkResponse;
throw new Error('no cached copy and network failed');
}
// network-first with a short timeout: race the network against a timer so a
// slow origin never blocks the response indefinitely, and fall back to the
// last cached copy if the network loses the race or fails outright.
async function handleApiRequest(request) {
const cache = await caches.open(API_CACHE);
try {
const response = await Promise.race([fetch(request), timeout(API_TIMEOUT_MS)]);
if (response && response.ok) cache.put(request, response.clone());
return response;
} catch (err) {
const cached = await cache.match(request);
if (cached) return cached;
throw err;
}
}
self.addEventListener('fetch', (event) => {
const url = new URL(event.request.url);
if (url.pathname.startsWith('/static/')) {
event.respondWith(handleStaticRequest(event.request));
} else if (url.pathname.startsWith('/api/')) {
event.respondWith(handleApiRequest(event.request));
}
});
Verified behavior. I ran this against a mocked Cache Storage API and a mocked fetch with a
controllable delay, to check the two properties that make this correct rather than just plausible:
// mock cache + fetch, then exercise the exact handler logic above
function mockCache() {
const store = new Map();
return { match: (k) => store.get(k), put: (k, v) => store.set(k, v) };
}
function delayedFetch(ms, value = { ok: true }) {
return () => new Promise((resolve) => setTimeout(() => resolve(value), ms));
}
// property 1: warm static cache + slow (2000ms) network -> returns immediately
const cache1 = mockCache();
cache1.put('/static/app.js', { ok: true, body: 'cached-bytes' });
const t0 = performance.now();
const r1 = await handleStaticRequest('/static/app.js', cache1, delayedFetch(2000));
console.log(`static, warm cache: returned in ${(performance.now() - t0).toFixed(1)}ms`);
// property 2: slow (5000ms) API network past the 800ms timeout, cache present
const cache2 = mockCache();
cache2.put('/api/profile', { ok: true, body: 'stale-cached-profile' });
const t1 = performance.now();
const r2 = await handleApiRequest('/api/profile', cache2, delayedFetch(5000));
console.log(`api, slow network, cached fallback: returned in ${(performance.now() - t1).toFixed(1)}ms`);
// property 3: slow API network, no cached copy at all -> must throw, not return undefined
const cache3 = mockCache();
try {
await handleApiRequest('/api/orders', cache3, delayedFetch(5000));
console.log('api, slow network, no cache: DID NOT THROW (unexpected)');
} catch (err) {
console.log(`api, slow network, no cache: threw "${err.message}" as expected`);
}
Output:
static, warm cache: returned in 0.1ms
api, slow network, cached fallback: returned in 801.3ms
api, slow network, no cache: threw "timeout" as expected
- With a warm static cache and an artificially slow (2s) network,
handleStaticRequestreturned the
cached response in under a few milliseconds, not 2 seconds, confirming the cache path never waits
on the background revalidation. - With a slow API network past the 800ms timeout but an existing cached copy,
handleApiRequest
returned the cached response at roughly the 800ms timeout mark (not the full network delay), and
when neither the network nor the cache had anything to offer, it correctly threw instead of
silently returningundefined.
Key points
- Never
awaitthe background refresh in the stale-while-revalidate path, that would turn it back
into network-first and defeat the point. Promise.raceis what gives network-first its "short timeout": the loser of the race keeps
running in the background but its result is ignored once the timer or the fetch settles first.- Both handlers only write to the cache on a successful (
response.ok) network response, so a 500
from the origin never overwrites a good cached copy with a broken one.
Design a global CDN invalidation service capable of handling thousands of invalidation requests per minute, supporting path-pattern invalidations and surrogate key based purges, while minimizing API rate limits, de-duplicating requests, and ensuring eventual consistency across edge regions. Outline the components, API design, and scaling considerations.
Sample Answer
Vocabulary and framing
A surrogate key, also called a cache tag, is a label attached to a cached response at write time, for example tagging every page that renders a given product with that product's id, so everything sharing that label can be purged in one call instead of enumerating every URL that happened to include it. Most CDN providers expose a purge API with its own rate limit, and at thousands of invalidation requests per minute, naive one-request-per-purge usage will hit that limit, so the service's real job is batching and deduplicating requests down to what the provider's API can actually sustain.
Components
- Ingestion API: accepts invalidation requests from internal services, path-pattern purges and surrogate-key purges, assigns each an idempotent request id, and writes it to a durable queue rather than calling the CDN synchronously.
- Deduplication and coalescing layer: reads from the queue and, within a short window, a second to a few seconds, collapses multiple requests for the same or overlapping targets into one; two services independently purging the same surrogate key within the window become a single call.
- Rate-limited dispatch workers: apply a token-bucket limiter (tokens refill at a fixed rate; each call consumes one, and a call arriving with no tokens left is delayed or rejected) per provider or account matching that provider's actual published rate limit, so the service never gets throttled by the CDN itself; workers pull coalesced batches off the queue and call the purge API.
- Per-region status tracking: since a purge doesn't take effect at every edge region instantly, track acknowledgment per region so the service can report fully propagated versus still propagating.
- Retry with backoff: any failed purge call, rate-limited or a transient network error, goes back onto the queue with exponential backoff rather than being dropped, since a silently-dropped purge is a stale-content bug invisible until a customer notices.
API design
A single invalidation endpoint accepting either a path-pattern request or a surrogate-key request, with a caller-supplied idempotency key so a retried request from the CALLING service, not just internal retries, doesn't create a duplicate purge, returning a request id immediately since the actual purge is async. A companion status endpoint returns queued, dispatched, propagating, or done, so a caller that genuinely needs to know propagation completed can poll or subscribe to a completion signal rather than assuming purges are instant.
Ensuring eventual consistency across edge regions
Accept that a purge does not land at every edge point of presence atomically; the service's job is guaranteeing it reaches EVERY region eventually, not instantly. Track per-region dispatch, retry any region that didn't acknowledge within an expected window, and expose per-region status so a caller can reason about propagating as a real, visible state rather than the service silently claiming success the moment it enqueued the request.
Scaling considerations
- Horizontal workers behind the rate limiter: the queue and dedup layer scale out independently of the CDN's own rate limit, since the limiter caps outbound calls, not worker count; more workers just means more capacity ready to dispatch the moment rate-limit budget is available.
- Partition by provider or account: if the org uses multiple CDN providers, partition the queue and rate limiter per provider, since each has an independent limit and shouldn't compete for the same budget.
- Backpressure signaling to callers: if incoming request rate genuinely exceeds what even a well-coalesced pipeline can sustain against the provider's rate limit, the ingestion API should surface that, a growing queue depth, a slower propagating status, rather than silently falling further behind with no visibility.
Trade-off
Coalescing and rate-limiting the dispatch path add latency to any individual purge, it waits in the coalescing window and possibly behind a rate-limit queue rather than firing instantly, but that latency is the cost of staying under the provider's rate limit reliably; firing every purge instantly works fine at low volume but breaks exactly at the thousands-per-minute scale this question asks about.
Describe the purpose and differences between these HTTP headers used for caching: Cache-Control, Expires, ETag, and Last-Modified. For each header give a short example value and a scenario where that header is most appropriate for frontend assets or API responses.
Sample Answer
Direct answer
The same four headers split into two jobs. Cache-Control (and the older Expires) set a
FRESHNESS window during which the browser can reuse a response with zero network request at
all. ETag and Last-Modified are VALIDATORS the browser can send back once that window
expires, to ask "is my copy still good?" and get a cheap answer instead of a full re-download.
Structured elaboration
Cache-Control: public, max-age=31536000, immutable(example value): appropriate for a
build-hashed static asset likeapp.3f2a91.js, since a content change produces a DIFFERENT
filename, this exact file can be cached essentially forever, andimmutabletells the browser
not to even bother revalidating it on reload.Cache-Control: private, max-age=0, must-revalidate(example value): appropriate for a
per-user API response,privatemeans only the individual browser may cache it, not a shared
proxy, andmust-revalidateforces a check with the server once it's stale rather than
silently serving stale data on a network hiccup.Expires: Thu, 01 Jan 2026 00:00:00 GMT(example value): the older, absolute-date sibling of
max-age, still seen on legacy servers or as a fallback for very old clients. When a response
carries both headers,Cache-Control'smax-agewins outright andExpiresis ignored, not
merged or averaged with it. This matters in practice because many origins and CDNs send both
for backward compatibility, so a stale, far-futureExpiressitting next to a shortmax-age
does NOT extend how long the response may be reused.ETag: "v3-88ff21"andLast-Modified: Mon, 06 Sep 2026 14:02:00 GMT(example values):
validators for content that DOES need revalidating, most useful on API responses that change
occasionally but not on every single request.
Worked example
Two contrasting endpoints on the same web app:
GET /static/app.3f2a91.js, a content-hashed frontend bundle:Cache-Control: public, max-age=31536000, immutable. The browser fetches it once and never asks again for a year; the
NEXT deploy shipsapp.7c1de4.js, a different URL, so there's no invalidation problem to
solve at all, the old cached file is simply never referenced again.GET /api/dashboard-summary, a per-user API response that changes a few times a day:
Cache-Control: private, max-age=60, plus anETag. The browser reuses the response for 60
seconds, then sendsIf-None-Match: <etag>on the next request; most of the time the
dashboard hasn't changed and the server returns a304 Not Modifiedwith an empty body,
saving the full JSON payload while still guaranteeing the user sees a change within roughly a
minute of it happening.
Trade-offs and pitfalls
- The single most common real bug: shipping a NEW version of a non-hashed static file (a plain
styles.css, say) under the SAME URL with a longmax-age. Users keep the old, broken
stylesheet for the full cache lifetime with no way to force a refresh short of a hard reload.
Content-hashed filenames exist specifically to make this class of bug structurally impossible. privateversus the default (shareable by any cache) matters a lot for anything behind a
shared proxy or content delivery network (CDN, a globally distributed set of servers that
cache and serve content closer to users): apublicAPI response containing one user's data
can get cached and served to a DIFFERENT user by an intermediate cache if this is set wrong.must-revalidateversus letting a stale response slide during an outage is a genuine trade-off
between correctness and availability, worth deciding deliberately rather than by whatever a
framework defaults to.
Unlock Full Question Bank
Get access to all 19 Caching Strategies & In-Memory Optimization interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.