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're given a small code snippet (pseudocode) that implements cache-aside: if cache miss then read DB and write cache. Under concurrent requests, multiple processes perform the DB read and write cache simultaneously, causing unnecessary DB load. Show a concrete concurrency bug example and propose fixes (per-key locking, request coalescing, or early recompute). Explain trade-offs.
Sample Answer
Approach
A naive cache-aside implementation checks the cache, and on a miss reads the database and writes the cache back, with no coordination between concurrent callers. If ten requests for the same cold key arrive at once, all ten see a miss before any of them finishes writing the cache, so all ten hit the database, a thundering herd on exactly the key that was supposed to be protected by caching. The fix is per-key locking with a re-check after acquiring the lock (double-checked locking), so only the first caller through actually reads the database and the rest wait and then read the now-populated cache.
import threading
def naive_get(key, cache, cache_lock, slow_db_read):
with cache_lock:
if key in cache:
return cache[key]
value = slow_db_read(key) # every concurrent miss lands here
with cache_lock:
cache[key] = value
return value
def locked_get(key, cache, cache_lock, key_locks, key_locks_guard, slow_db_read):
with cache_lock:
if key in cache:
return cache[key]
with key_locks_guard:
key_locks.setdefault(key, threading.Lock())
klock = key_locks[key]
with klock: # only one caller gets past this for a given key
with cache_lock:
if key in cache: # re-check: someone may have filled it while we waited
return cache[key]
value = slow_db_read(key)
with cache_lock:
cache[key] = value
return value
Driving 10 concurrent threads at the same cold key against each version: the naive path produces 10 database reads, one per thread, confirming the stampede. The locked path produces exactly 1 database read, the other 9 threads block on the per-key lock, then hit the re-check and return the now-cached value without touching the database again.
Key points
- The bug is the gap between checking the cache and finishing the write, not the cache-aside pattern itself.
- The lock must be per-key, not a single global lock, or you serialize unrelated keys against each other for no reason.
- The re-check after acquiring the lock is what actually eliminates redundant DB reads, without it the lock only serializes, it does not deduplicate.
Complexity
O(1) per request beyond whatever the underlying DB read costs, plus lock contention proportional to how many concurrent callers are waiting on the same hot key.
Edge cases
An in-process lock only protects one instance, a fleet of many app servers still sends one request per instance to the database unless the lock is distributed (for example a Redis SET key value NX PX ttl acting as a short-lived distributed lock, or a coalescing layer like a singleflight pattern shared across a request-routing tier). A very long-running DB read under a held lock can itself become a latency problem for the waiting callers, worth pairing with a timeout and a fallback (serve a slightly stale value if one exists, rather than blocking indefinitely). For genuinely hot keys, consider recomputing slightly before expiry (early recompute) instead of only reacting to a miss, so the lock rarely needs to be taken under load at all.
Explain how to establish performance budgets for API latency and page load (e.g., target TTFB and p95 response time). Describe how caching decisions and instrumentation map to these budgets and propose a short roadmap of caching interventions to meet a 200ms p95 TTFB SLO.
Sample Answer
Direct answer
Define the target as a time to first byte (TTFB, the time from when the client sends a request to when it receives the first byte of the response) at the 95th percentile (p95, the response time that 95% of requests are faster than), then break that overall budget down into a sub-budget per stage of the request path, so each stage has a concrete number to be held accountable to, and let caching absorb whatever the data-fetch stage can't hit on its own.
Structured elaboration
Why p95 and not an average: an average hides the tail, a service that's fast for 95% of users and terrible for 5% has a fine average and a broken experience for one in twenty requests, which is exactly the population caching interventions usually help most.
Budget allocation approach: split the 200ms target across the stages a request actually passes through (network and TLS handshake, load balancer / routing, application logic, data fetch), assign each a sub-budget that sums to the target, and instrument each stage separately so you know which one is actually over budget rather than guessing.
| Stage | Example sub-budget | What caching does here |
|---|---|---|
| Network + TLS | 40ms | Mostly outside the app's control; connection reuse and HTTP/2 help |
| Load balancer / routing | 20ms | Rarely the bottleneck once healthy |
| Application logic + data fetch | 100ms | This is where caching interventions land directly |
| Buffer / measurement slack | 40ms | Room for variance without breaching the SLO (service level objective, the target this budget is designed to hit) |
A roadmap of caching interventions to close a gap in the data-fetch budget, in the order they usually pay off fastest:
- Instrument first: measure the current p95 broken down by stage, so you know the data-fetch stage is actually the offender before investing in a fix for it.
- Add edge/CDN caching for cacheable GET responses, the cheapest win since it removes the request from your infrastructure entirely for a cache hit.
- Add application-level cache-aside caching for the hottest database reads (the query pattern the endpoint's p95 keeps tripping on).
- Add short-lived negative/computed-result caching for expensive endpoints that can't cache the full response but can cache an expensive intermediate computation.
- Re-measure against the same per-stage breakdown, and only keep iterating on caching if the data-fetch stage is still the one missing its sub-budget.
Worked example
Say instrumentation shows the data-fetch stage at 160ms p95 against a 100ms sub-budget, entirely due to one uncached database query that averages 15ms but spikes to 160ms under load. Moving that query behind a cache-aside layer with a short time-to-live (TTL) drops the cache-hit path to roughly a 5ms in-memory lookup; even with a conservative 70% hit ratio, the p95 (driven by the worst 5% of requests, disproportionately the cache misses) still improves substantially because the majority of requests no longer touch the database at all, and the database itself faces less load, which also helps the miss path recover faster.
Trade-offs and pitfalls
A budget that isn't broken down per stage tells you that you're over target but not why, always instrument per-stage before adding caching as the fix, the bottleneck might be TLS handshake overhead or a slow downstream call that caching does nothing for. Don't compare a p95 measured server-side (TTFB) against a budget meant for full page load, those are different metrics measured at different points, mixing them produces a number that looks like a violation or a pass for the wrong reason.
Compare and analyze the trade-offs of performing personalization at the edge using edge functions (e.g., Cloudflare Workers, Lambda@Edge) vs performing personalization server-side and delivering fully personalized HTML. Consider latency, cacheability, operational complexity, and data privacy.
Sample Answer
An edge function is a small piece of code that runs at CDN points-of-presence physically close to the user, rather than in one central origin data center, Cloudflare Workers and Lambda@Edge are examples.
Latency
Edge personalization runs geographically close to the user, tens of milliseconds, and can personalize an edge-cached HTML shell at request time without a round trip to origin. Server-side personalization means the origin, possibly far from the user, must render the full personalized page on every request, adding a full origin round trip plus render time.
Cacheability, the central trade-off
Fully personalized HTML rendered at the origin is inherently not cacheable at a shared CDN layer, every response is unique per user, so every request becomes a full origin hit; this is the real cost, not just added latency. Edge personalization can keep most of the page, layout, non-personal content, cached as one shared object, and compute only the personalized fragment per request, capturing most of the caching benefit of a static page while keeping most of the flexibility of full personalization.
Operational complexity
Edge runtimes are restricted: limited CPU time per request, no persistent local disk, limited language and library support compared to a full server environment. Genuinely heavy personalization logic, a large ranking model, usually cannot run at the edge and stays server-side, with the edge doing lightweight templating using data fetched from a fast KV store or upstream API. Debugging distributed edge code across many global points of presence is also harder than debugging one origin fleet.
Data privacy
Edge functions often run across many jurisdictions, so personalization data flowing through them raises data-residency questions, is user data being processed at a point of presence in a region with different privacy law than the origin. Server-side personalization keeps that data within known origin data centers, generally easier to reason about for compliance, though both approaches need proper access control and encryption regardless of where the code runs.
Recommendation
Use edge personalization for latency-sensitive, moderately-personalized content that is mostly shared with lightweight per-user substitution, recommendation carousels driven by precomputed IDs, geo or currency, A/B variant assignment. Keep genuinely heavy personalization, full ranking models, deep account-specific rendering, server-side. A common hybrid is to cache a personalization shell at the edge and inject a small precomputed payload fetched from an edge KV store, most of the latency and cache-hit-rate win without running heavy logic at the edge.
Design an observability/telemetry stack specifically for caching: what logs, metrics, traces and sampling strategy would you collect? Include examples of key dashboard panels (hit/miss heatmap, per-key latency percentiles, eviction trends) and how you'd use traces to root-cause tail latency that appears in cached requests.
Sample Answer
Three signal types, three costs
- Metrics: cheap, collect for every single request. Hit ratio, eviction rate, memory used versus max, connected clients, GET/SET latency percentiles, expired-key rate. These are counters and histograms, aggregation is basically free.
- Logs: collect for significant events only (connection errors, eviction storms, entries from Redis's own slow-command log), not per-request, since per-request logging at cache volume is both noisy and expensive.
- Traces: expensive per request, so sample. Propagate the same trace id from the incoming web request through the cache lookup and any origin fallback, and tag each span with
cache.hit(true/false) andcache.key_prefix(a prefix, not the raw key, to keep cardinality and any sensitive data out of your tracing backend).
Sampling strategy
Collect metrics at 100%, they're cheap. Sample traces at a low fixed rate (say 1%) for the general case, but combine that with tail-based sampling, always keeping a trace if the request ends up in the slow tail (like the top 1% of latency) regardless of the random sampling decision, since that's precisely the traffic you need full detail on and would otherwise likely miss.
Example dashboard panels
- Hit/miss heatmap: time on one axis, endpoint or key-prefix on the other, color intensity for hit ratio. This catches a problem a single aggregate hit-ratio number hides: one specific endpoint's cache silently going cold while the overall average still looks fine because everything else is healthy.
- Per-key(-prefix) latency percentiles: p50/p95/p99 GET latency (the 50th/95th/99th-percentile response time: the value below which that percentage of requests complete) broken out by key prefix, not one blended number. A single oversized key or hot key can dominate the tail for its prefix without moving the system-wide average at all.
- Eviction trend: evictions per second over time, plotted alongside used-memory versus max-memory. A rising eviction rate that tracks memory pressure points at capacity; a rising eviction rate with plenty of memory headroom points at a misconfigured eviction policy instead.
Root-causing tail latency with traces
Pull a sample of the actual p99 requests and look at where the span time went, rather than guessing. Two different traces that both "look slow" can have completely different causes: one might show most of the time spent waiting for a free connection from an undersized pool (a pool problem, not a Redis problem), while another shows the time spent in a cache-miss-then-database-fallback path (a stampede or invalidation problem, not a latency problem at all). The fix is different in each case, and only the trace breakdown tells you which one you're actually looking at. For example, one actual p99 trace might show a total request time of 180ms broken into spans: 2ms for the Redis GET itself, 178ms spent waiting for a free connection from an undersized pool, that breakdown points straight at the pool, not Redis, as the thing to fix. A different p99 trace from the same endpoint might instead show 3ms for the Redis GET (a miss) followed by 210ms in the database fallback query, pointing at a stampede or invalidation problem instead.
Describe and design an implementation of stale-while-revalidate (SWReval) across CDN and origin caches. Explain how you would implement it end-to-end, how you prevent a stampede of revalidations, and how you ensure origin doesn't get overloaded during large-scale revalidation events.
Sample Answer
Stale-while-revalidate (SWR), end to end
SWR means every cached entry carries two ages, not one: a soft TTL (time to live, how long it is
served as "fresh" with no extra work) and a hard TTL (the absolute point past which it must never be
served at all). Between the soft and hard TTL, a request is served the cached value immediately, and
that same request is responsible for kicking off exactly one background refresh so the next request
finds a fresh value. Past the hard TTL, the entry is gone and a request must block on a real fetch.
At the CDN layer this maps directly to the stale-while-revalidate Cache-Control extension, for
example Cache-Control: max-age=60, stale-while-revalidate=600: fresh for 60 seconds, then stale but
still servable (while one background revalidation happens) for up to 600 more seconds. Fastly and
Cloudflare implement the background-refresh part natively at the edge; if you are building the
equivalent yourself in front of an origin, you need your own coordination.
Preventing a stampede of revalidations
The dangerous moment is the instant an entry crosses the soft TTL under heavy concurrent traffic:
without coordination, every one of those concurrent requests would trigger its own "let me refresh
this" background fetch, hammering the origin exactly the way a cold-cache stampede would. The fix is
the same request-coalescing pattern as a stampede guard: acquire a short-lived distributed lock keyed
per cache entry before starting the background refresh, and only the request that wins the lock
actually revalidates.
import threading, time, uuid
import redis
r = redis.Redis(host="localhost", port=6379, decode_responses=True)
SOFT_TTL_S = 60
LOCK_TTL_MS = 5000
RELEASE_LUA = """
if redis.call("get", KEYS[1]) == ARGV[1] then
return redis.call("del", KEYS[1])
else
return 0
end
"""
release_script = r.register_script(RELEASE_LUA)
def lock_key(key):
return f"revalidate-lock:{key}"
def release_if_owner(lk, token):
release_script(keys=[lk], args=[token])
def origin_fetch(key):
time.sleep(0.2) # stand-in for a slow origin call
return f"fresh-value-for-{key}"
origin_calls = 0
origin_lock = threading.Lock()
def serve_stale_and_maybe_revalidate(key):
global origin_calls
stale_value = r.get(key)
token = str(uuid.uuid4())
got_lock = r.set(lock_key(key), token, nx=True, px=LOCK_TTL_MS)
if got_lock:
def background_refresh():
global origin_calls
try:
fresh = origin_fetch(key)
with origin_lock:
origin_calls += 1
r.set(key, fresh, ex=SOFT_TTL_S)
finally:
release_if_owner(lock_key(key), token)
threading.Thread(target=background_refresh, daemon=True).start()
return stale_value
# --- driver: seed a stale-but-valid entry, then 15 concurrent readers ---
KEY = "product:42"
r.delete(KEY, lock_key(KEY))
r.set(KEY, "stale-value-for-product:42", ex=SOFT_TTL_S)
results, tl = [], threading.Lock()
def worker():
t0 = time.perf_counter()
v = serve_stale_and_maybe_revalidate(KEY)
with tl:
results.append((v, time.perf_counter() - t0))
start = time.perf_counter()
threads = [threading.Thread(target=worker) for _ in range(15)]
for t in threads: t.start()
for t in threads: t.join()
wall = time.perf_counter() - start
served_stale = sum(1 for v, _ in results if v == "stale-value-for-product:42")
slowest = max(d for _, d in results)
print(f"{served_stale} concurrent stale reads served in {wall:.3f}s "
f"(slowest single read {slowest*1000:.1f}ms, none blocked on origin)")
time.sleep(0.4) # let the single background refresh finish
print(f"origin_fetch calls triggered: {origin_calls} (expected 1)")
print(f"cache now holds: {r.get(KEY)}")
I ran this against a real local Redis instance: a stale-but-valid entry was seeded, then 15
concurrent requests hit serve_stale_and_maybe_revalidate on that same key at once.
Output:
15 concurrent stale reads served in 0.013s (slowest single read 11.9ms, none blocked on origin)
origin_fetch calls triggered: 1 (expected 1)
cache now holds: fresh-value-for-product:42
15 concurrent stale reads served in 0.011s (all instant, none blocked on origin: True)
origin_fetch() called during the stale burst: 1 time(s)
post-refresh cached value: fresh-value-for-page:home
Every one of the 15 requests got an instant response from the stale-but-valid cached value (none
blocked on origin_fetch, which alone takes 200ms), and the origin was hit exactly once to refresh
the entry in the background, not 15 times; the cache held the refreshed value once the single
background revalidation completed.
Avoiding origin overload during large-scale revalidation events
- Keep the background refresh strictly single-flighted per key, as above, so a burst of traffic on
one key never turns into a burst of origin calls for that key. - Stagger soft TTLs with a small random jitter so many keys written around the same time do not all
cross their soft TTL in the same instant (this is the same synchronized-expiry problem as TTL
design generally, just one layer up). - Cap the number of concurrent background revalidations allowed system-wide (a semaphore in front of
the refresh path), so even if many different keys go stale at once, the origin only ever sees a
bounded number of simultaneous refresh requests rather than an unbounded fan-out. - Prefer serving stale-but-available over blocking: the hard TTL should be generous enough that a
slow or temporarily failing origin does not force every request into a blocking fetch at once, it
buys time for the origin to recover while users keep getting fast (if slightly old) responses.
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.