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.
Plan an A/B experiment to quantify the impact of enabling edge caching (stale-while-revalidate) on checkout conversion. Define metrics, hypothesis, sample size considerations, experiment duration, instrumentation, significance tests, and safeguards (e.g., kill switch). Discuss how to isolate caching effects from confounders like traffic source or client geography.
Sample Answer
What stale-while-revalidate means, and why it's being tested
Stale-while-revalidate is an HTTP caching directive that lets a cache serve an EXPIRED response immediately while it fetches a fresh one in the background for the next request, instead of making the current request wait for a fresh fetch. On a checkout page this can reduce perceived latency, but checkout is also revenue- and correctness-sensitive (prices, inventory, promo eligibility), so leadership wants proof it helps before shipping it everywhere.
Hypothesis
Enabling this on the checkout page's cacheable responses reduces page load time and increases checkout conversion rate by some minimum meaningful amount, for example a relative lift of 1%, a number chosen for being worth the engineering and risk cost, not treating any positive number as success.
Metrics
- Primary: checkout conversion rate, completed purchases divided by checkout page visits.
- Guardrails: checkout error rate (did anyone see stale pricing or an inventory mismatch), page load time median and p95 (confirm the mechanism actually fired), and revenue per visit, in case conversion moves one way and average order value moves the other.
- Frontend guardrails: Core Web Vitals for the checkout page, particularly layout shift if stale data visually updates after the page has already rendered, since the whole mechanism is a frontend perceived-performance trade and deserves its own direct instrumentation rather than being inferred from conversion alone.
Sample size, worked with real numbers
Say baseline checkout conversion is 20% and you want to reliably detect a 1% relative lift, 20.0% to 20.2%, an absolute delta of 0.002, at 80% power and 95% confidence:
n ≈ 16 × p × (1 - p) / delta^2
Plugging in p = 0.20, delta = 0.002:
n ≈ 16 × 0.20 × 0.80 / (0.002)^2 ≈ 2.56 / 0.000004 ≈ 640,000
Roughly 640,000 checkout-page visits PER ARM. That's a real number worth stating to the team requesting the experiment: if weekly checkout traffic is far below that, either the test runs longer, or the team accepts detecting only a larger effect than 1%, and that trade-off should be a stated decision, not a silent one.
Duration
Run at least one to two full weekly cycles, since weekday and weekend behavior differ, and don't stop early just because the metric looks significant after a few days; a result that looks significant on day three has a meaningfully higher chance of being noise than the same result sustained through the planned duration.
Instrumentation
Tag every checkout request with its experiment arm at the edge, where the caching decision is actually made, and log the ACTUAL observed cache behavior per request, hit, stale-served, or miss, not just the assigned arm, so a bug that makes the treatment behave identically to control isn't invisible in the results.
Significance test
A two-proportion test on conversion rate between arms, reporting the 95% confidence interval on the difference, not just a p-value. An interval entirely above zero is a real, positive effect; one straddling zero means the test was inconclusive at this sample size, not proof of no effect.
Isolating caching effects from confounders
Randomize at the user or session level, not by time window or geography, and verify after assignment that the arms are balanced on traffic source, device type, and client geography, since edge latency, and therefore the caching benefit, varies by region. If a check reveals a skew, re-run the randomization or explicitly stratify the analysis by the confounding variable rather than reporting a single pooled number a skewed split could bias.
Kill switch and other safeguards
Wire the toggle to the same feature-flag mechanism used for arm assignment, so it can be disabled instantly, no deploy, if guardrail metrics breach a threshold mid-experiment, and automate that check, an automatic rollback if the treatment arm's checkout error rate exceeds a set threshold, rather than relying on someone watching a dashboard continuously.
Alternate treatment: a TTL change instead of enabling stale-while-revalidate
The same design, hypothesis, metrics, sample size math, randomization, kill switch, applies unchanged if the actual treatment being tested is a TTL change, for example raising a cacheable response's TTL from 30 seconds to 5 minutes, rather than toggling stale-while-revalidate on or off. The treatment variable in the analysis just becomes old TTL versus new TTL, and the same guardrails matter for the same reason: a longer TTL raises the same staleness-versus-latency trade-off.
Trade-off
Running this as a properly powered experiment costs real calendar time, weeks, given the sample size math above, and holds back a potentially real user-experience win during that window, but checkout is exactly the surface where an untested caching change causing even a small correctness issue, stale pricing shown at checkout, has outsized cost, which is why the rigor is worth it here specifically.
You have 100 million keys in Redis, each holding roughly 1KB of JSON, and memory pressure is causing frequent evictions. How would you go about shrinking the footprint without just buying more memory, and what would you weigh in choosing between the options you come up with?
Sample Answer
Start from the honest arithmetic
100 million keys times roughly 1KB of JSON each is about 100,000,000 x 1,024 bytes = 102.4 GB of raw
payload (roughly 95 GiB using the 1024-based unit), before Redis's own per-key bookkeeping is counted
at all. That per-key overhead (the dictionary entry, the object header, pointers) is commonly cited as
tens of bytes per key for Redis; even a conservative ballpark of 50 to 70 bytes of overhead per key
adds another 5 to 7 GB on top at 100 million keys. I'm flagging that overhead figure as an estimate,
not a measured number for your exact Redis version and configuration, but it is large enough at this
key count that it belongs in the sizing conversation, not just the raw payload size.
Levers, roughly in order of effort
- Shrink the payload itself. If the JSON is verbose (repeated field names, human-readable
numbers), switch to a compact binary serialization like MessagePack or Protocol Buffers, which
typically cuts size meaningfully versus JSON text for the same data, and/or apply compression
(gzip/zstd) on the value before storing it. Trade-off: every read now pays a small CPU cost to
decompress/decode, so this helps most when you're memory-bound, not CPU-bound. - Reduce structural (per-key) overhead by consolidating. If many of the 100 million keys are
small pieces of a related entity (say, several fields of the same logical object stored as separate
string keys), storing them as fields of a single Redis hash instead of separate top-level keys
amortizes the per-key overhead across fewer actual keys, and Redis encodes small hashes very
compactly (thelistpack/ziplist-style encoding) as long as they stay under the configured field
count and value size thresholds. Trade-off: you lose the ability to set a TTL on an individual
field, only on the whole hash, so this only works cleanly if those fields genuinely expire
together. - Tighten TTLs where staleness is cheap. Shrinking TTLs reduces the steady-state working set, at
the cost of more cache misses and more backend load; this only helps net-positive if the backend
can absorb the extra miss traffic. - Tune Redis's own memory behavior rather than just the data model:
maxmemory-policy(for exampleallkeys-lruorallkeys-lfu) (allkeys-lruevicts the least-recently-accessed key first;allkeys-lfuevicts the least-frequently-accessed key first) decides what gets evicted once
you're at the memory ceiling; picking the wrong one (or leaving it at thenoevictiondefault)
turns memory pressure into write errors instead of graceful eviction.mem_fragmentation_ratiofromINFO memorytells you whether the problem is actually the data
itself or fragmented allocator overhead; a high ratio (well above 1) with active defragmentation
turned on can reclaim real memory without touching the data model at all.lazyfree-lazy-eviction(and the relatedlazyfree-lazy-expire) moves the actual freeing of a
big evicted key's memory to a background thread instead of blocking the main event loop, which
matters more for latency than for total memory, but is cheap to turn on and worth checking.
- Scale horizontally (Redis Cluster) as the fallback, once the per-key and per-payload levers are
exhausted, rather than as the first move, since resharding and rebalancing carry their own
operational cost.
How I'd weigh the options
Serialization/compression is usually the highest-leverage first move because it attacks the largest
share of the footprint (the payload, not the per-key overhead) and needs no data-model change, at the
cost of CPU on every read and write. Hash consolidation is the next move if many keys really are
fragments of the same entity, since it removes structural overhead essentially for free, but it is a
real data-model change and only fits data that genuinely shares a TTL. The maxmemory-policy and
fragmentation knobs are close to free to check and should happen regardless of which of the above you
choose, since a misconfigured eviction policy can make even a well-sized cache behave badly. Buying
more memory or sharding out is the right call only after these are exhausted, since it doesn't reduce
the underlying footprint, just defers dealing with it.
You need to choose a session store for a globally distributed web app: local in-memory per-process cache, Memcached, or Redis. Compare them across latency, shared access across instances, failover and replication, secure handling of session data, and operational complexity. Recommend the best approach for scalable sessions and justify your choice.
Sample Answer
Direct answer
For a globally distributed web app, recommend Redis, deployed with replication such as Redis
Cluster or a managed multi-region setup, as the shared session store. A local in-memory
per-process cache fails the core requirement outright: a user's second request can land on a
different app instance or region with no memory of their session. Memcached is a viable
alternative but gives up built-in replication and richer data handling, which makes Redis the
safer default for something as availability-sensitive as sessions.
Structured elaboration
| Axis | Local in-memory (per-process) | Memcached | Redis |
|---|---|---|---|
| Latency | Lowest possible, no network hop, but it only helps the ONE process that has it. | Low, a single network hop to a flat key-value store. | Low, comparable to Memcached for plain get/set; slightly more overhead for richer commands. |
| Shared access across instances | None; each process has its own copy, a different server has no idea the session exists. | Yes, any app instance can read and write the same cluster. | Yes, plus optional read replicas near each region to cut cross-region latency. |
| Failover and replication | Not applicable, and the routine "failure" mode is restarting the process, which loses every session on it. | No native replication; typically client-side consistent hashing across independent nodes, so a node failure loses everything on that node. | Built-in primary-replica replication with automatic failover (Sentinel or Cluster), so a node failure promotes a replica instead of losing data. |
| Secure handling of session data | Data never leaves the process, smallest exposure surface, but secrets still must never sit in a client-visible cookie. | TLS in transit and access control are the operator's responsibility to configure; historically weaker built-in authentication than Redis. | TLS in transit, ACL-based authentication (Redis 6+, restricting which commands or keys a client may touch), and at-rest encryption via the platform; still your job to keep the cookie to a random session identifier, never the payload. |
| Operational complexity | Lowest, there's nothing to run. | Low to moderate; simple to operate, but you own consistent-hashing and rebalancing behavior client-side. | Moderate to higher; replication and clustering are powerful, but they are real infrastructure you must size, monitor, and upgrade. |
Worked example
A retailer runs app servers in six regions behind a global load balancer with no sticky
sessions, any request can land on any region for capacity reasons. A shopper logs in in region
A, adds items to a cart, then their next request is routed to region B during a traffic
reshuffle. With Redis as the shared session store, a primary in each region replicating to the
others, region B's app server reads the same session by identifier and the cart survives. The
session cookie holds only a random session identifier, never the session contents; the session
hash itself (holding fields like user id and cart contents) carries a time-to-live (TTL) of, say,
30 minutes of inactivity, refreshed on every request, so an abandoned session cleans itself up
instead of accumulating forever.
Trade-offs and pitfalls
- Cross-region replication has real lag; if a write lands on region A's primary and the user's
next request hits region B before that write replicates, region B can serve a slightly stale
session. For session data this is usually tolerable, worst case the cart looks one step
behind for a moment, but it must be an explicit, communicated trade-off, not a surprise. - Running Redis Cluster or Sentinel across regions is genuinely more operational surface than
"just run Memcached," and that cost is worth naming rather than hiding behind "Redis is
better." - A local in-memory cache isn't useless here, it's a reasonable first tier IN FRONT of Redis
(a short-lived, invalidation-tolerant read-through cache of the same session) to shave off a
network hop on hot, same-instance repeat requests, as long as you accept it can go briefly
stale relative to Redis. - Never trust the cookie itself as the source of truth for anything beyond "which session id to
look up"; storing session payload client-side in a cookie reintroduces the exact secure-handling
problem this question calls out.
In JavaScript, write a concise Service Worker fetch handler that implements a 'stale-while-revalidate' strategy for images: return cached image if present, kick off a background fetch to update the cache, and on cache miss fetch from network and store in cache. Use async/await, Cache API, and include a cache name constant and a TTL comment.
Sample Answer
Approach
Stale-while-revalidate means: return whatever is currently cached immediately (even if it might be out of date), and kick off a background fetch to refresh it for next time, never blocking the response on the network. The demo below uses the same minimal Cache API polyfill (caches.open, cache.match, cache.put) as any other Service Worker demo, so the real fetch-handler logic can be executed and its behavior verified directly rather than just described.
// Same minimal Cache API polyfill as the other Service Worker demo, so the
// real fetch-handler logic below can run and print its actual behavior here.
class MockCache {
constructor() { this.store = new Map(); }
async match(request) { return this.store.get(request) ?? null; }
async put(request, response) { this.store.set(request, response); }
}
class MockCacheStorage {
constructor() { this.caches = new Map(); }
async open(name) {
if (!this.caches.has(name)) this.caches.set(name, new MockCache());
return this.caches.get(name);
}
}
const caches = new MockCacheStorage();
const IMAGE_CACHE = 'images-v1'; // TTL is enforced by refetching on every
// read via revalidate(), not by a stored
// expiry: the cache never serves anything
// OLDER than "whatever the last background
// fetch returned", which is the point of
// stale-while-revalidate.
const networkLog = [];
async function fakeNetworkFetch(url) {
networkLog.push(url);
return { url, bytes: `image-bytes(${url})@${networkLog.length}` };
}
/**
* Real Service Worker fetch handler for images:
* - cache hit -> return the cached response immediately, refresh in the background
* - cache miss -> fetch from network, cache it, then return it
*/
async function handleImageFetch(request) {
const cache = await caches.open(IMAGE_CACHE);
const cached = await cache.match(request);
if (cached) {
// don't block the response on the network: fire-and-forget the refresh
fakeNetworkFetch(request).then((fresh) => cache.put(request, fresh));
return cached;
}
const fresh = await fakeNetworkFetch(request);
await cache.put(request, fresh);
return fresh;
}
async function main() {
console.log('Request 1 (miss, network fetch):', await handleImageFetch('/img/hero.png'));
console.log('network calls:', networkLog);
console.log('\nRequest 2 (hit, returns stale immediately, refresh queued):');
console.log(await handleImageFetch('/img/hero.png'));
// give the fire-and-forget refresh a tick to land
await new Promise((r) => setTimeout(r, 10));
console.log('network calls after refresh landed:', networkLog);
console.log('\nRequest 3 (hit again, now serves what the background refresh stored):');
console.log(await handleImageFetch('/img/hero.png'));
console.log('network calls:', networkLog);
}
main();
Output
Request 1 (miss, network fetch): { url: '/img/hero.png', bytes: 'image-bytes(/img/hero.png)@1' }
network calls: [ '/img/hero.png' ]
Request 2 (hit, returns stale immediately, refresh queued):
{ url: '/img/hero.png', bytes: 'image-bytes(/img/hero.png)@1' }
network calls after refresh landed: [ '/img/hero.png', '/img/hero.png' ]
Request 3 (hit again, now serves what the background refresh stored):
{ url: '/img/hero.png', bytes: 'image-bytes(/img/hero.png)@2' }
network calls: [ '/img/hero.png', '/img/hero.png', '/img/hero.png' ]
Key points
- Cache hit: return the cached response immediately (request 2 above returns the same bytes it had before), then fire off a background fetch without awaiting it in the response path,
.then(...)without a precedingawaiton the response. - Cache miss: no cached value to return yet, so this one request has to wait on the network, then gets cached for next time.
- TTL comment: there's no stored expiry timestamp here; freshness is enforced by refetching on every read via the background revalidation, so the cache never serves anything staler than "whatever the last background fetch returned."
IMAGE_CACHE = 'images-v1', the trailing version number is how you'd force a hard reset if the caching strategy itself ever changes.
Edge cases
- If the background revalidation fetch fails (network error, 500 from origin), the cached (now technically stale) image keeps being served indefinitely until a fetch eventually succeeds; that's usually the right default for images specifically, since a broken image is worse UX than a stale one.
- Two overlapping requests for the same image while a background revalidation is already in flight both read the currently cached value and both trigger their own revalidation fetch; harmless for images (idempotent, cache.put on the same key twice is fine) but worth flagging as duplicate network work under high concurrency.
Compare localStorage, sessionStorage, cookies, and IndexedDB for client-side caching. For each API list ideal use-cases, approximate size limits, persistence characteristics, and key security considerations for storing cached data.
Sample Answer
Comparison
| API | Ideal use case | Approximate size limit | Persistence | Key security considerations |
|---|---|---|---|---|
localStorage | Small key-value settings/preferences that should survive closing the browser, such as a theme choice | About 5 to 10MB per origin, browser-dependent | Persists indefinitely until explicitly cleared | Synchronous and JavaScript-readable; never store tokens or personal data, since any XSS (cross-site scripting, a malicious script injected into your page) on the page can read it |
sessionStorage | Data scoped to one tab's lifetime, such as a multi-step form's in-progress state | Same ballpark as localStorage | Cleared when the tab/window closes; not shared across tabs | Same XSS exposure as localStorage, but the shorter lifetime somewhat limits the blast radius |
| Cookies | Data the SERVER needs on every request, such as a session ID, since cookies are automatically attached to HTTP requests | About 4KB per cookie, plus a per-domain cookie-count limit | Persists per the Expires/Max-Age attribute the server sets, or session-only | Set HttpOnly (blocks JavaScript access, the main defense for session cookies), Secure (HTTPS only), and SameSite (CSRF, cross-site request forgery, defense); the only one of the four automatically sent on every request, which is also its main risk if scoped too broadly |
| IndexedDB | Larger structured data: an offline product catalog, cached API responses needing complex querying | Hundreds of MB to low GB, quota-based and negotiated with the browser | Persists until explicitly cleared, same as localStorage | Also JavaScript-readable and XSS-exposed; being asynchronous and transactional is a performance/ergonomics property, not a security one |
Choosing between them
The deciding questions are: does the SERVER need to read this automatically, only cookies do that; does it need to survive the tab closing, localStorage and IndexedDB yes, sessionStorage no; and how much data, a few KB fits anywhere, hundreds of KB to MB pushes you toward IndexedDB. Avoid putting an auth token in localStorage/sessionStorage when possible: an HttpOnly cookie is the only one of the four immune to a JavaScript-based XSS read.
Unlock Full Question Bank
Get access to all Caching Strategies & In-Memory Optimization interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.