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.
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.
Compare in-process caches (like Caffeine/Guava) vs remote/shared caches (Redis) for microservices. Discuss latency, consistency, memory duplication across instances, eviction complexity, failure modes, and operational trade-offs. Provide guidance for when to use local caches, remote caches, or a two-level strategy.
Sample Answer
The two options
In-process (local, "L1") caches like Caffeine or Guava (popular Java in-memory caching libraries) live inside the application's own process. Remote/shared ("L2") caches like Redis live outside it, reached over the network and shared by every instance.
Comparison
| Dimension | In-process (local) | Remote/shared (Redis) |
|---|---|---|
| Latency | Microseconds, no network hop | Sub-millisecond to a few ms, over the network |
| Memory | Duplicated per instance (N instances each hold their own copy) | Shared, one copy total |
| Consistency across instances | Weak: each instance's cache is independent, one instance can serve stale data while another is fresh | Stronger: one shared view, one invalidation clears it everywhere |
| Eviction | Simple, tuned per JVM heap (for example Caffeine's window-TinyLFU policy, an eviction algorithm that weighs both how recently and how frequently an entry was used rather than recency alone) | Centrally tuned (maxmemory-policy), consistent everywhere |
| Failure mode | Contained: a bug in one instance's cache doesn't affect others, and there's no extra network dependency | Correlated: if Redis is slow or down, every instance feels it at once |
| Operational burden | None, it's just a data structure in the process | Running, monitoring, and scaling a stateful service |
Guidance
Use a local cache for small, very-hot, mostly-read data where a little staleness across instances is tolerable, feature flags, small config or lookup tables, things where all instances converging on the same value within a few seconds is fine. Use a remote cache when the data set is too large to duplicate across every instance, needs a consistent view across instances, or changes often enough that per-instance staleness would actually matter.
Two-level strategy
Put a small local L1 in front of a shared L2 (Redis). L1 absorbs the very highest-QPS keys at sub-microsecond latency and takes load off L2; L2 remains the shared source of truth across instances and survives individual instance restarts and deploys, which also softens a cold rolling-deployment start, since a freshly started instance only has an empty local L1 and still serves from the already-warm shared L2 instead of hitting the origin directly. The risk is that L1 can go stale relative to L2 after a write, until L1's own entry expires. Mitigate that by keeping L1 TTLs deliberately short (seconds, not minutes) or by broadcasting an invalidation (pub/sub) to every instance's L1 the moment L2 is invalidated, so writes propagate quickly instead of waiting out L1's TTL.
Describe how a Service Worker can implement an offline-first caching strategy for a single-page application. Outline the lifecycle events (install, activate, fetch) and provide a high-level fetch handler strategy that: returns cached shell assets immediately, serves cached API responses when offline, and attempts network refresh in background. Mention considerations for cache versioning and update UX.
Sample Answer
Approach
A Service Worker is a script the browser runs in the background, separate from the page, that can intercept network requests. Three lifecycle events matter here: install (fires once, when the worker is first registered, the moment to pre-cache the app shell), activate (fires after install, once no old version of the worker is still controlling a page, the moment to clean up old caches), and fetch (fires on every network request the page makes, the moment to decide cache versus network).
To make the exact logic checkable outside a browser, the demo below implements a minimal Cache API polyfill (caches.open, cache.match, cache.put, cache.keys, cache.delete) with the same method names and behavior a real browser provides; only the browser plumbing (self, addEventListener, the real network) is mocked, the caching strategy itself is real and runs unmodified.
// --- Minimal Cache API + fetch polyfill, so the SAME fetch-handler logic a
// browser would run can be executed and verified here in Node. The
// install/activate/fetch event names, the Cache API surface (caches.open,
// cache.match, cache.put, cache.keys, cache.delete) and the strategy below
// are the real Service Worker API; only the browser plumbing (self,
// addEventListener, the network) is mocked.
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); }
async keys() { return [...this.store.keys()]; }
async delete(request) { return this.store.delete(request); }
}
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);
}
async keys() { return [...this.caches.keys()]; }
async delete(name) { return this.caches.delete(name); }
}
const CACHE_VERSION = 'v2';
const SHELL_CACHE = `app-shell-${CACHE_VERSION}`;
const API_CACHE = `api-data-${CACHE_VERSION}`;
const SHELL_ASSETS = ['/index.html', '/app.js', '/app.css'];
const caches = new MockCacheStorage();
const networkLog = [];
// stands in for the real network; logs each hit so the demo can show when
// the network was (and was not) used.
async function fakeNetworkFetch(url) {
networkLog.push(url);
return `network-response(${url})`;
}
// --- install: pre-cache the app shell -------------------------------------
async function onInstall() {
const shell = await caches.open(SHELL_CACHE);
for (const asset of SHELL_ASSETS) {
shell.put(asset, `shell-asset(${asset})`);
}
}
// --- activate: drop caches from older versions -----------------------------
async function onActivate() {
const names = await caches.keys();
const stale = names.filter((n) => n !== SHELL_CACHE && n !== API_CACHE);
await Promise.all(stale.map((n) => caches.delete(n)));
return stale;
}
// --- fetch: shell from cache, API cache-first with background refresh ------
async function onFetch(url) {
const isShellAsset = SHELL_ASSETS.includes(url);
if (isShellAsset) {
const shell = await caches.open(SHELL_CACHE);
const cached = await shell.match(url);
if (cached) return { source: 'cache', body: cached };
// shell miss (e.g. first load before install finished): go to network
const body = await fakeNetworkFetch(url);
return { source: 'network', body };
}
// API/data requests: return cache immediately if present, but always kick
// off a network refresh in the background so the next read is fresh.
const api = await caches.open(API_CACHE);
const cached = await api.match(url);
const refresh = fakeNetworkFetch(url).then((body) => api.put(url, body));
if (cached) {
await refresh; // awaited only so the demo output below is deterministic
return { source: 'cache-then-refreshed', body: cached };
}
const body = await refresh.then(() => api.match(url));
return { source: 'network-then-cached', body };
}
async function main() {
await onInstall();
console.log('After install, shell cache has:', await (await caches.open(SHELL_CACHE)).keys());
const dropped = await onActivate();
console.log('Activate dropped stale caches:', dropped);
console.log('\nFetch /index.html (shell, should be a cache hit, no network):');
console.log(' ', await onFetch('/index.html'));
console.log(' network calls so far:', networkLog);
console.log('\nFetch /api/profile (first time, cache miss, must hit network):');
console.log(' ', await onFetch('/api/profile'));
console.log(' network calls so far:', networkLog);
console.log('\nFetch /api/profile again (cache hit, background refresh also fires):');
console.log(' ', await onFetch('/api/profile'));
console.log(' network calls so far:', networkLog);
}
main();
Output
After install, shell cache has: [ '/index.html', '/app.js', '/app.css' ]
Activate dropped stale caches: []
Fetch /index.html (shell, should be a cache hit, no network):
{ source: 'cache', body: 'shell-asset(/index.html)' }
network calls so far: []
Fetch /api/profile (first time, cache miss, must hit network):
{ source: 'network-then-cached', body: 'network-response(/api/profile)' }
network calls so far: [ '/api/profile' ]
Fetch /api/profile again (cache hit, background refresh also fires):
{ source: 'cache-then-refreshed', body: 'network-response(/api/profile)' }
network calls so far: [ '/api/profile', '/api/profile' ]
Key points
- Install: pre-caches the app shell (
index.html,app.js,app.css) so the shell is available offline from the first load onward. - Activate: deletes any cache whose name doesn't match the current version constants, so a deploy doesn't leave old, unreachable caches consuming storage forever.
- Fetch, shell assets: cache-first, since the shell is versioned by the cache name itself, a stale shell is impossible once activate has run.
- Fetch, API/data: cache-first for speed, but always kicks off a background network refresh so the NEXT read gets fresher data, this is the offline-first trade: instant response now, freshness catching up in the background.
- Cache versioning: bumping
CACHE_VERSIONcreates new cache names, so the nextactivatecleans out everything from the previous version automatically, no manual cache-busting needed.
Edge cases
- A shell asset requested before
installfinishes (a fast reload right after registering) falls through to the network branch rather than returning nothing. - Update UX: since the fetch handler favors the cache, a user with a tab open during a deploy keeps seeing the OLD shell until they reload; pair this with a "new version available, refresh" prompt driven by the worker's
updatefoundevent so this isn't invisible to the user.
Propose an ML-driven adaptive caching system that tunes per-key TTLs based on features (recency, frequency, object size, compute cost). Describe feature extraction, training pipeline (offline or online), evaluation metrics (hit rate, origin load), safe rollout strategies, and fallback safeguards if the model misbehaves.
Sample Answer
Framing
Instead of a hand-tuned TTL (time to live) per key or per key-class, a model predicts a good TTL (or a caching decision more generally) from features about the key's observed behavior. This is worth the added complexity specifically when the keyspace is large and heterogeneous enough that no small number of hand-picked TTL tiers captures the real variation well, and it needs strong operational guardrails because a misbehaving model choosing bad TTLs at scale can cause real user-facing staleness or real origin-load spikes.
Feature extraction
Per key (or per key-class, for very large keyspaces where per-key tracking is too expensive), track:
- Recency and frequency of access: time since last read, rolling read rate, read-interval distribution.
- Object size: larger objects cost more to keep cached (memory) and often more to recompute, both relevant to the TTL trade-off.
- Compute cost to regenerate: latency and resource cost of a cache miss (a cheap key lookup versus an expensive join or an external API call), directly relevant because a higher miss cost should push toward a longer TTL, all else equal.
- Update frequency / volatility: how often the underlying data actually changes, which bounds how long a TTL can safely be before staleness risk becomes unacceptable.
- Business-defined staleness sensitivity: a label or tag (not purely learned) for how much this data class tolerates staleness, since some staleness costs (e.g. showing a stale price) are qualitatively different from others (e.g. a stale "last seen" timestamp) in a way raw access statistics alone can't capture.
Training pipeline
- Offline, to start: log the features above alongside the OUTCOME of different TTL choices (via a small held-out slice of keys running varied TTLs, essentially a controlled experiment, or via historical logs if TTL has varied naturally over time), and train a model (even something as simple as a regression or a small gradient-boosted tree predicting a good TTL from the features performs well here, this doesn't need to be a large or complex model since the feature set is small and structured) to predict a TTL that would have minimized a defined cost (origin load plus a staleness penalty, similar in spirit to the cost-function approach used for simpler TTL auto-tuning, just with a learned function instead of a hand-derived one).
- Online, once validated offline: periodically retrain (e.g. daily) as access patterns drift, and consider a lightweight online update (adjusting predictions based on very recent observed outcomes) for keys whose behavior changes faster than a daily retrain would catch.
Evaluation metrics
- Hit rate: does the model's TTL choice actually reduce cache misses versus the prior fixed-TTL baseline, for a comparable staleness profile.
- Origin load: total request volume and cost hitting the backend, the thing a good TTL choice is directly trying to reduce.
- Staleness distribution: not just "did hit rate go up" but "how old was the data, on average and at the tail, when clients actually read a cache hit," since a naive optimizer could trivially maximize hit rate by choosing enormous TTLs and silently accept unacceptable staleness; staleness has to be tracked and bounded as its own metric, not inferred from hit rate.
Safe rollout
- Shadow mode first: run the model's predictions alongside the current TTL policy without actually applying them, logging what it WOULD have chosen, and compare its predicted cost against the actual baseline cost before it ever controls a live TTL.
- Canary on a small, low-risk slice of keys (or key-classes) once shadow evaluation looks good, watching the real hit-rate/origin-load/staleness metrics on that slice specifically before expanding.
- Ramp gradually (percentage of keys, or percentage of traffic) rather than a single cutover, so a bad model version affects a bounded blast radius while it's being caught.
Fallback safeguards
- Hard bounds: clamp every model-predicted TTL to a
[min, max]range appropriate to that key's data-sensitivity class, so the model can never push a compliance-sensitive key's TTL past a legally or contractually required ceiling, regardless of what it predicts. - A circuit breaker: if the model's predictions start diverging wildly from recent history (a sudden shift suggesting a bad deploy, a feature-pipeline bug, or model drift), fall back automatically to the last-known-good static TTL policy for the affected keys rather than trusting an anomalous prediction.
- Treat the model as an optimizer layered on top of a safe default, never as the sole source of the TTL; a key that's never been scored by the model, or whose score looks implausible, should fall back to its class's default TTL, not to an unclamped model output.
Worked example
A content-delivery cache with 10 million distinct keys currently uses 3 hand-picked TTL tiers (1 minute, 10 minutes, 1 hour), and the "10 minute" tier holds 2 million of those keys. Shadow-mode evaluation on a held-out sample shows the hand-picked tier running at a 76.2% hit rate (23.8% miss rate) for a large sub-population of stable keys within it, while the trained model's predicted TTLs project an 83.7% hit rate (16.3% miss rate) at the same staleness profile, a (23.8 - 16.3) / 23.8 = 31.5% relative reduction in origin-hitting requests for that slice. Canaried on 2% of the tier's keys (40,000 keys), the observed hit rate over one week comes in at 83.4%, within 0.3 points of the shadow-mode projection, and the p99 (99th-percentile) staleness-at-hit metric, capturing the slow/stale tail rather than the average, holds at 9.6 minutes versus the hand-picked baseline's 9.9 minutes, both comfortably inside the tier's 10-minute ceiling, confirmed before wider rollout.
Trade-offs
The added complexity (feature pipeline, training/retraining, shadow and canary infrastructure, fallback logic) is real operational cost; it's justified specifically when a keyspace is heterogeneous enough that hand-picked tiers are provably leaving meaningful hit-rate or cost improvement on the table, which is worth demonstrating with the simpler cost-function auto-tuning approach first before reaching for a learned model at all.
JVM-based services using large in-process caches (like Caffeine) sometimes experience GC pauses affecting latency SLOs. Explain how cache size and object churn influence GC, what JVM and GC settings you would tune, and alternative strategies like off-heap caches or serialization to reduce GC pressure. Give concrete tuning suggestions.
Sample Answer
Garbage collection (GC) is the JVM automatically reclaiming memory for objects no longer referenced, and a stop-the-world pause is a phase where some GC work briefly halts all application threads, adding directly to request latency during that pause. An SLO (service level objective) like "p99 under 200ms" is exactly the kind of target a long GC pause can blow through in one shot.
How cache size and churn drive GC pressure
A large in-process cache, millions of entries in Caffeine, gives the GC a much bigger live set, objects it must repeatedly scan and NOT collect on every cycle, since the cache still references them, and this alone lengthens cycles even with nothing being evicted. Churn, a high eviction and insertion rate, makes it worse: every evicted entry becomes garbage the GC then has to reclaim, so a cache with high turnover (short TTL, small max size relative to traffic) generates a steady stream of short-lived garbage on top of an already-large long-lived heap, close to a GC's worst case, a mix of a big long-lived footprint and heavy short-lived churn.
JVM and GC tuning
Use a low-pause-focused collector, G1GC is the modern default and a reasonable starting point; ZGC or Shenandoah trade some throughput for much shorter target pause times and are worth evaluating specifically once GC pause is confirmed to be the latency bottleneck. Set an explicit pause-time goal with G1 (-XX:MaxGCPauseMillis=50) rather than only sizing the heap and hoping. Size the heap deliberately, an oversized heap means longer, though less frequent, cycles when they do happen, an undersized heap means more frequent cycles, this is a real sizing exercise, not just "give it more RAM." Monitor GC logs for pause duration and frequency trends over time, correlated against your cache size metrics, to actually confirm the cache is the driver rather than assuming it.
Off-heap and serialization alternatives
Move the cache's bulk data off the regular GC-managed heap, an off-heap store paired with Caffeine, or something like Chronicle Map, or a Redis sidecar instead of a very large in-process cache. Off-heap memory is not scanned by the GC at all, which removes the big-live-set problem directly, at the cost of needing serialization on every access, objects have to be marshaled into and out of the off-heap buffer, a real CPU trade-off worth making only once GC pause is demonstrably the dominant cost, confirmed from the GC logs, not assumed.
The mirror-image effect: a GC pause causing a miss storm
A long stop-the-world pause freezes request processing, so requests queue up during the pause and then all get processed in a burst right after it ends. If a meaningful share of those queued requests are for keys that were about to expire or were not yet cached, the pause effectively synchronizes a burst of cache misses immediately after it ends, which looks like an unrelated miss storm but is actually caused by the GC pause, not a coincidence. To catch this, correlate GC pause timestamps directly against the cache miss-rate time series, not just latency, a miss-rate spike that reliably follows GC pause events by roughly the pause duration is the fingerprint. Mitigate with the same pause-time tuning above, and by adding TTL jitter so expirations are not already clustered and ready to compound with a GC-caused processing backlog.
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.