Skip to content
Tech Interview Prep
Technical interview guide

Caching Strategies

Production caching for technical interviews: placement, read/write patterns, freshness, stampedes, HTTP caching, observability, failure recovery, and decision tradeoffs.

Minutes to read
3
Practice MCQs
25
Interview Q&A
25
Edition
v5
Editorial status
Reviewed

Scope: HTTP caching per RFC 9111 and RFC 5861; Redis behavior referenced from current official documentation accessed 2026-08-30..

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-1

Explain the cache-aside pattern and one downside of it.

Answer

Cache-aside (lazy loading) puts the application in charge of the cache. On a read, the app asks the cache first; on a miss it goes to the database, then writes the value back to the cache with a TTL. Writes go to the database directly, and the app either invalidates the cache key or lets the TTL absorb the change. The database remains the source of truth, and the cache is disposable: you can flush it and nothing is lost except latency.

Python
# Redis 7.x, redis-py 5.x — cache-aside read path
def get_user(user_id):
    key = f"user:{user_id}"
    cached = redis.get(key)
    if cached is not None:
        return json.loads(cached)          # hit: ~0.5 ms
    row = db.execute(
        "SELECT * FROM users WHERE id = %s", (user_id,)
    ).fetchone()                          # miss: ~15 ms
    redis.set(key, json.dumps(row), ex=300)  # 5-minute TTL
    return row

The downside worth explaining: the inconsistency window. Because the cache is populated lazily and expires on a timer, the cache can serve stale data even after a write has committed. Two distinct mechanisms produce this:

  1. TTL staleness. A write updates the database but the cached copy isn't touched. Until the TTL lapses or the key is explicitly invalidated, every read returns the old value. With a 5-minute TTL, a user can update their profile and see the old version for up to five minutes. If you invalidate on write, you shrink the window to milliseconds, but you don't eliminate it.
  2. Read-then-write race. Two concurrent misses both read the database; between the read and the SET, a writer commits a newer value; the stale reader then overwrites the cache with the old value. Now the cache is wrong for the entire TTL even though you invalidated on write. Mitigations: short TTLs as a backstop, or delete-on-write plus a versioned write to the cache (e.g., a Lua script that only sets if the version is newer).

The failure mode that actually pages people: the expiry stampede. A hot key expires and 500 concurrent requests all miss simultaneously, all hit the database, and all try to repopulate the cache. At 10,000 QPS with a 90% hit rate the database sees 1,000 QPS; if a top key expires and 20% of traffic lands on it, that's 2,000 extra queries in the ~15 ms it takes the first one to repopulate: enough to saturate a connection pool and turn a cache miss into a full outage. Fixes: request coalescing (a single-flight lock so one request fetches and the rest wait), probabilistic early expiration (repopulate slightly before the TTL at random offsets), or a mutex per key (SET key:lock 1 NX EX 1).

When cache-aside is the wrong choice.

PatternWrite pathStalenessBest for
Cache-asideDB only; cache filled on readUp to TTL after writeRead-heavy, tolerant of slight staleness
Write-throughDB and cache togetherNear-zero on writesRead-after-write consistency required
Write-behindCache first, DB asyncDB can lag; data loss riskVery high write throughput, loss-tolerant

If users must read their own writes (profile updates, config changes, balance after a payment) cache-aside with a long TTL will produce bug reports. Write-through costs you write latency (every write pays the cache round trip) but closes the window. Write-behind is faster still but the database lags, and a cache node dying before the flush loses committed-looking writes.

Cache-aside earns its place when reads dominate, stale-for-seconds is acceptable, and you want the cache to be a pure optimization: turn it off and the system still works, just slower. That degradation property is the real reason it's the default at most shops, but it's also why the stampede scenario needs to be designed for, not discovered in production.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-7

When would write-through caching be preferred over cache-aside?

Answer

Write-through is useful when the normal write path should update the authoritative store and cache together so subsequent reads are likely to observe the new value. The caller pays additional write latency and the implementation must define ordering, retries, and partial-failure recovery. It does not make two separate systems atomically consistent: a cache write can fail after the database commits, concurrent writers can complete out of order, and bypass writes can skip the cache. Cache-aside is simpler and avoids populating data that is never read, but its miss path and invalidation races need separate controls.

cache statesource rps at 10,000 QPS
90% hit1,000
cold cache~10,000

Production lens

Treat acknowledgements, retries, and recovery as a protocol. A diagram that omits partial failure is not a production design.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-2

Explain write-behind (write-back) caching and the risk-vs-performance tradeoff it makes compared to write-through.

Answer

Write-behind acknowledges a write once it lands in the cache or a pending-write buffer, then persists to the authoritative store asynchronously, usually batched. Write-through puts the durable write on the synchronous path: the caller waits for the store to commit before getting its ack. The tradeoff is latency and throughput on one side against a durability window on the other, and you should be able to put numbers on both.

Where you actually see it. Apache Ignite ships write-behind for its cache store: writeBehindFlushFrequency (default 10,000 ms) controls how often dirty entries flush, writeBehindFlushBatchSize (default 500) bounds batch size, and writeBehindFlushSize (default 10,240) caps the buffer before a forced flush. NCache has an equivalent write-behind with configurable batching and eviction retries. Redis has no server-side write-behind: you build it with keyspace notifications, a client-side buffer, or a queue like Kafka between the ack and the database. Below the database, the same pattern recurs: Linux's dirty page cache holds writes up to dirty_expire_centisecs (default 30 s) before writeback, and disk write caches buffer until the controller flushes. The concept is layered, not cache-specific.

The loss window, quantified. The ack is only as durable as the buffer. With Ignite's default 10,000 ms flush frequency and 5,000 writes/s, a crash that takes the buffer with it can lose up to ~50,000 acknowledged writes: that's the arithmetic to state in an interview, and it's why the default is far too loose for anything where the ack is a durability promise. Ignite's buffer lives in-process, so a JVM kill loses whatever hasn't flushed; a replicated queue (Kafka with acks=all and 3 replicas) shrinks the window to the queue's replication latency, a few ms, at the cost of an extra hop. If you need write-behind but a tighter bound, set writeBehindFlushFrequency to 100 ms and the same 5,000 writes/s crash loses at most ~500 acked writes: the knob is the contract.

| | write-through | write-behind (Ignite defaults) | | --- | --- | | Caller latency | store commit time, e.g. 5–20 ms | cache ack, sub-ms | | Ack durability | committed before ack | up to flush frequency × write rate at risk | | Store load | one write per call | batched, up to 500 per flush batch | | Failure mode | timeout, caller retries | silent loss of acked writes on crash |

Failure modes beyond the crash. Two more matter:

  1. Reordering. Async flushes can reorder updates to the same key: last-writer-wins at the cache but applied out of order at the store. Ignite coalesces updates to the same key within a flush window; if you roll your own, you must partition by key or version entries.
  2. Store outage. Flushes stall, the buffer fills toward writeBehindFlushSize (10,240), and you face the same fork as any queue: block new acks and lose the latency benefit, or spill and drop. Either way the throughput win is gone for the duration, which is the correct answer to "what happens when the database is down."

When write-through isn't automatically safer. Write-through removes the deferred-loss window but is not atomic across cache and store: the store commit can succeed while the cache update fails, leaving a stale cache that serves reads until invalidation. Concurrent writers racing through cache and store can also interleave, so you still need versioning or compare-and-set. Write-through is the right default when the ack is a durability promise: payments, inventory decrements. Write-behind earns its keep for high-write, low-value data: counters, analytics events, session state, denormalized view updates where a bounded loss window is acceptable and the store would otherwise be the throughput bottleneck.

The decision rule: name the acknowledgement contract first. If the caller treats the ack as "committed," write-behind is wrong regardless of the latency win. If the contract is "accepted, eventually persisted, at most N ms of loss," then size the flush frequency and buffer to that N and say so.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-12

How would you mitigate the risk of losing recent writes in a write-behind caching system, without fully reverting to write-through's synchronous latency cost?

Answer

Acknowledge only after the pending write has reached a storage mechanism whose durability matches the product contract (for example, a replicated durable log or queue) then flush to the database asynchronously. Give each operation an idempotency key and sequence or version, retry with bounded backoff, route poison operations to a dead-letter or repair path, apply backpressure when the backlog grows, and monitor the oldest pending age. Shorter flush intervals and replication can reduce exposure, but they do not by themselves prove durability; the system must be tested by killing writers and recovering or replaying the acknowledged backlog.

cache statesource rps at 10,000 QPS
90% hit1,000
cold cache~10,000

Production lens

Treat acknowledgements, retries, and recovery as a protocol. A diagram that omits partial failure is not a production design.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-4

How would you decide between LRU and LFU eviction policies for a specific caching workload?

Answer

Start by asking what predicts a future access in this workload: recency or stable popularity. That single question decides it, and you can answer it from an access log rather than opinion.

The mechanism. LRU keeps the n most recently touched keys, so it bets on temporal locality: if a key was just read, it will likely be read again soon. LFU keeps the n most frequently accessed keys over some window, so it bets on stable popularity: a key requested 500 times an hour stays even if nobody touched it in the last minute. The failure modes fall out of those bets directly.

LRU's failure mode: scan pollution. One batch job or crawler that sweeps a million cold keys once each evicts the entire hot set. Every swept key is "more recent" than every hot key. Detection is concrete: hit rate drops from, say, 92% to near zero for the duration of the scan, and origin traffic spikes to roughly full QPS (at 10,000 QPS and 92% hits, the origin sees ~800 rps normally; during a scan it can approach 10,000). If your workload has background scans, LRU alone is the wrong default: you need segmented LRU or a small admission filter (e.g., only promote a key to the main segment on its second access).

LFU's failure mode: dead-key retention. Frequency counters decay slowly, so a key that was popular yesterday but is dead today occupies memory until its count decays below the hot set's threshold. Worse, a one-hour viral key with 50,000 hits can pin memory for days. Detection: track the hit rate per key class; if a class's hit rate is high but its contribution to overall hits is flat while memory share grows, stale keys are squatting. Mitigations are decayed counters (halve counts periodically, as in Redis 4.0+ LFU, which uses a logarithmic counter with a configurable decay factor) or windowed LFU.

How to decide, concretely. Replay a real access trace (an hour of production logs is enough) through both policies at your target memory size and compare hit rate: that's the whole decision. Two signals to look for in the trace:

  • Skew stability. If the top-1% of keys by requests stays roughly the same hour over hour, LFU's bet is sound. If the hot set churns (trending content, time-of-day shifts), LFU's history works against it and LRU adapts faster.
  • Scan or burst traffic. Present in any meaningful fraction of requests? That disqualifies plain LRU unless you add admission.

When not to use either. If the working set barely fits in memory, both degrade toward scanning behavior and you should size the cache or shard differently, not tune the policy. If access patterns are near-uniform random, no policy beats another: hit rate is set by size alone.

What I'd actually ship. For most web/API workloads: LRU (or segmented LRU if scans exist), because it's O(1), self-tuning, and needs no decay parameters. I'd reach for LFU with decayed counters when the trace shows a stable hot set that LRU keeps evicting on transient bursts, and I'd verify the win by replaying the trace, not by argument.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-11

Explain why a distributed cache is generally required (rather than a local in-process cache) once an application scales to multiple server instances behind a load balancer.

Answer

A distributed cache gives the application fleet one shared cache service, so downstream miss load does not multiply once per process and a deployment does not empty the shared tier. It also reduces, but does not eliminate, coherence problems: local L1 tiers, cache replication, stale writers, failed invalidations, and network partitions can still expose different versions. Compared with an in-process cache it adds a network hop and another production dependency, so the decision should be driven by measured fleet-wide reuse, freshness needs, and source-load protection rather than a rule that every multi-instance service requires Redis.

cache statesource rps at 10,000 QPS
90% hit1,000
cold cache~10,000

Production lens

Validate the choice with realistic traffic, cache-disabled load tests, per-key-class telemetry, and an explicit degraded-mode runbook.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-13

Why might TTL-based expiration alone be insufficient for data that needs to reflect changes immediately, and how would you combine TTL with explicit invalidation?

Answer

A TTL guarantees data is refreshed eventually (once the TTL elapses) but doesn't help if a specific change needs to be visible sooner than the TTL window: e.g. a 10-minute TTL means a user could see stale data for up to 10 minutes after an important update. Combining approaches: using a TTL as a safety-net upper bound on staleness, while also explicitly invalidating (deleting or updating) the specific cache key immediately whenever the underlying data changes through a known code path: gives you both: immediate consistency for changes you can explicitly detect, and a bounded worst-case staleness for changes that might slip through an invalidation gap (e.g. a direct database update that bypasses the normal application code path).

cache statesource rps at 10,000 QPS
90% hit1,000
cold cache~10,000

Production lens

Keep a TTL or reconciliation path as a repair bound even when normal freshness is event-driven, and measure invalidation lag.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-18

Explain why a cache with a very short TTL might provide little real performance benefit despite technically "caching" data.

Answer

If the TTL is shorter than the typical interval between repeat requests for the same key, most requests will still miss the cache (the previous cached entry having already expired by the time the next request for that key arrives), providing little actual hit-rate benefit while still paying the overhead of checking and maintaining the cache. Choosing an appropriate TTL requires understanding the actual access pattern, how frequently the same keys are re-requested, rather than picking an arbitrarily short duration purely out of caution about staleness, which can accidentally defeat the caching's purpose entirely.

cache statesource rps at 10,000 QPS
90% hit1,000
cold cache~10,000

Production lens

Validate the choice with realistic traffic, cache-disabled load tests, per-key-class telemetry, and an explicit degraded-mode runbook.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-17

How would you design a cache key scheme to avoid accidentally serving one user's cached data to a different user?

Answer

Include every dimension that affects the response's content in the cache key itself: e.g. user:{userId}:cart rather than just cart, ensuring each user's data lives under a distinct key rather than colliding with another user's under a shared key. This seems obvious in isolation but is a common real bug source when caching is added to existing code without carefully auditing every place a response depends on request-specific context (user ID, locale, feature flags, A/B test variant) that must be reflected in the cache key to avoid cross-contamination between different contexts.

cache statesource rps at 10,000 QPS
90% hit1,000
cold cache~10,000

Production lens

Validate the choice with realistic traffic, cache-disabled load tests, per-key-class telemetry, and an explicit degraded-mode runbook.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-22

Explain the risk of caching data that includes sensitive or user-specific information at a shared layer like a CDN, and how Cache-Control headers help prevent this.

Answer

If a response containing one user's private data gets cached at a CDN edge node (a shared resource serving many users), a subsequent unrelated user requesting the same URL could receive the first user's cached private data: a serious security/privacy bug. Cache-Control: private (or no-store for the most sensitive cases) explicitly tells shared caches (CDNs, shared proxies) not to cache the response at all, or only allows caching in the specific browser that made the request (private, not shared): correctly setting this header on any response containing user-specific or sensitive data is essential to avoid this class of cross-user data leak.

cache statesource rps at 10,000 QPS
90% hit1,000
cold cache~10,000

Production lens

In production, verify actual browser/CDN behavior from response headers and cache-status telemetry; do not infer privacy or freshness from intent alone.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-15

How would you use HTTP caching headers (Cache-Control, ETag) to let browsers and CDNs cache API responses appropriately?

Answer

Cache-Control: max-age=3600 tells clients/CDNs a response is fresh for up to an hour without re-checking with the origin. An ETag (a hash/fingerprint of the response content) lets a client send a conditional request (If-None-Match) on subsequent fetches, if the content hasn't changed, the server responds with a cheap 304 Not Modified instead of re-sending the full payload, saving bandwidth while still verifying freshness. Combining both lets you cache aggressively for performance while still detecting and picking up real changes efficiently, rather than choosing between "never re-check" and "always re-fetch the full response."

cache statesource rps at 10,000 QPS
90% hit1,000
cold cache~10,000

Production lens

In production, verify actual browser/CDN behavior from response headers and cache-status telemetry; do not infer privacy or freshness from intent alone.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-14

How would you decide what granularity to cache at: e.g. caching an entire rendered page, versus caching individual data fragments that get assembled into a page?

Answer

Caching a whole rendered page is simplest and fastest to serve (a single cache lookup), but any single piece of dynamic content on that page (even a small personalized element) forces either skipping the cache for the whole page or accepting staleness on that one element. Caching individual fragments (e.g. "this product's description" separately from "this user's personalized recommendations") allows mostly-static parts to be cached aggressively and long while personalized parts refresh independently and more frequently: at the cost of more cache lookups and more complex assembly logic. The right granularity balances how much of the page is genuinely shared/cacheable versus how much varies per-request.

cache statesource rps at 10,000 QPS
90% hit1,000
cold cache~10,000

Production lens

Validate the choice with realistic traffic, cache-disabled load tests, per-key-class telemetry, and an explicit degraded-mode runbook.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-9

Why does caching a computed aggregate (like "total sales this month") require more careful invalidation logic than caching a single raw record?

Answer

A raw record's cache entry only needs invalidating when that specific record changes: a clean, direct relationship. An aggregate depends on many underlying records (every sale contributing to the monthly total), so any single one of those many records changing should, in principle, invalidate the cached aggregate: tracking this dependency (which cached aggregates does this specific record's change affect) is significantly more complex than the one-to-one invalidation a raw record needs, and is a common source of subtle staleness bugs if not carefully designed (e.g. via explicit dependency tracking, or simply accepting a TTL-based staleness window rather than perfect invalidation).

cache statesource rps at 10,000 QPS
90% hit1,000
cold cache~10,000

Production lens

Keep a TTL or reconciliation path as a repair bound even when normal freshness is event-driven, and measure invalidation lag.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-19

How would you handle caching for a value that's expensive to compute but changes on an unpredictable schedule (not a fixed TTL, but triggered by specific events)?

Answer

Publish or record an invalidation or refresh intent when the source-changing event commits, rather than guessing freshness with only a TTL. If losing an event would violate the contract, commit the intent with the source change using an outbox or change-data-capture stream, deliver it with retries, make consumers idempotent, and define ordering or version checks. Event-driven invalidation reduces normal lag but is not instantaneous: retain a TTL or reconciliation job as a repair bound and measure event-to-cache propagation latency and failures.

cache statesource rps at 10,000 QPS
90% hit1,000
cold cache~10,000

Production lens

Validate the choice with realistic traffic, cache-disabled load tests, per-key-class telemetry, and an explicit degraded-mode runbook.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-16

Explain why caching negative results (e.g. "this user ID doesn't exist") can be just as important as caching positive results for protecting a backend from load.

Answer

Without caching negative lookups, a client repeatedly querying for a non-existent (or not-yet-created) resource forces a full database round-trip on every single request, since there's no positive cached value to serve: this is a common oversight, since caching logic is often written with only the "found it" case in mind. Explicitly caching "not found" results (with an appropriate, often shorter, TTL to avoid masking a resource that gets created shortly after) protects against this specific gap, which matters especially for public-facing APIs where malicious or buggy clients might repeatedly probe for non-existent IDs.

cache statesource rps at 10,000 QPS
90% hit1,000
cold cache~10,000

Production lens

Validate the choice with realistic traffic, cache-disabled load tests, per-key-class telemetry, and an explicit degraded-mode runbook.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-20

Why might caching database query results at the application layer sometimes be redundant with a database's own internal query result caching?

Answer

Database buffer pools usually cache data and index pages, and plan caches reuse compiled execution plans; those mechanisms do not generally mean the database returns an old application query-result object without executing the query. An application cache can still avoid query execution, a database network round trip, serialization, and application post-processing. It is worthwhile only when those avoided costs and cross-request reuse exceed the invalidation and operational cost introduced by the application cache.

cache statesource rps at 10,000 QPS
90% hit1,000
cold cache~10,000

Production lens

Validate the choice with realistic traffic, cache-disabled load tests, per-key-class telemetry, and an explicit degraded-mode runbook.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-10

How would you measure and improve a poor cache hit ratio for a specific application?

Answer

First instrument the application to log/measure hits versus misses per cache key or key pattern, identifying whether misses are concentrated on specific data (suggesting a poor caching strategy for that particular access pattern) or spread broadly (suggesting insufficient cache capacity or too-short TTLs). Common fixes include increasing cache size/capacity (if eviction is happening before items would naturally be re-requested), tuning TTLs to better match how often the underlying data actually changes, or restructuring what's cached (e.g. caching at a different granularity that better matches actual request patterns): the right fix depends on which specific cause the measurement reveals.

cache statesource rps at 10,000 QPS
90% hit1,000
cold cache~10,000

Production lens

Validate the choice with realistic traffic, cache-disabled load tests, per-key-class telemetry, and an explicit degraded-mode runbook.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5

How does a cache stampede happen, and what's one way to mitigate it?

Answer

The 90-second answer

A cache stampede is what happens when a key that many concurrent requests depend on stops being served from cache at the same instant, so all of them fall through to the origin together. The trigger is usually expiry or eviction of a hot key, but the actual cause is synchronization: the requests were already concurrent, and the cache was the only thing collapsing them into a single origin call. Remove the cache and they all arrive at once.

The arithmetic is unforgiving. At 10,000 QPS against a key with a 90% hit rate, the origin sees 1,000 rps. The moment that key expires, it sees ~10,000 rps for as long as the rebuild takes. If the origin is a database with a 20-connection pool and 5 ms per query, its ceiling is 20 / 0.005 = 4,000 queries/s. It saturates in well under a second, and the queue does not drain, because every request that times out and retries adds more load.

The mitigation I'd reach for first is request coalescing, often called single-flight: the first request to miss takes a lock and rebuilds the value; every other request for that key waits on the same in-flight result instead of issuing its own query. One origin call instead of ten thousand.

Why expiry alone isn't the whole story

Two things have to be true for a stampede: the key has to be hot, and the misses have to be correlated in time. Correlated misses come from more than TTL expiry: an LRU eviction under memory pressure, a deploy that flushes the cache, a bulk warm-up that writes 50,000 keys with the same TTL, or a lookup for a key that doesn't exist (cache penetration). Jittering TTLs (base + rand(0, 10%)) fixes the bulk-write case and does nothing for a single hot key, which is why it complements coalescing rather than replacing it.

Single-flight, concretely

Go
var group singleflight.Group

func GetUser(ctx context.Context, id string) (*User, error) {
	if u, ok := cache.Get(id); ok {
		return u, nil
	}
	ch := group.DoChan(id, func() (any, error) {
		if u, ok := cache.Get(id); ok { // a queued caller may have filled it
			return u, nil
		}
		u, err := db.LoadUser(ctx, id)
		if err != nil {
			return nil, err
		}
		cache.Set(id, u, 5*time.Minute)
		return u, nil
	})
	select {
	case r := <-ch:
		if r.Err != nil {
			return nil, r.Err
		}
		return r.Val.(*User), nil
	case <-ctx.Done():
		return nil, ctx.Err()
	}
}

Three details matter. The re-check inside the closure closes the window between the miss and the lock. DoChan plus the ctx.Done() case means a caller that gives up doesn't hold a goroutine. And the shared load runs on the first caller's context, if that caller disconnects, the load is cancelled for everyone waiting. Detach it: context.WithTimeout(context.WithoutCancel(ctx), 2*time.Second).

Probabilistic early expiration

The alternative is to refresh before expiry, with a probability that rises as the deadline approaches. XFetch (Vattani et al., VLDB 2015) recomputes when

now - delta * beta * ln(rand()) >= expiry

where delta is the measured rebuild time and beta defaults to 1. The trigger probability is exp(-(expiry - now) / (beta * delta)). With delta = 100 ms:

time before expiryP(recompute)
10 ms0.90
100 ms0.37
300 ms0.05

So the refresh starts a few hundred milliseconds early instead of at the deadline. Note what this does not do: it spreads the decision but doesn't cap concurrency, so 10,000 QPS still produces hundreds of recomputes per second near expiry. Pair it with single-flight, or use it where the rebuild is cheap.

Failure modes

  • Per-process scope. singleflight coalesces within one process. With 40 pods you get up to 40 concurrent rebuilds, not one. Cross-instance coalescing needs a distributed lock (SET key NX PX 500 in Redis), which adds a round trip and a new failure mode: if the lock TTL expires before the rebuild finishes, a second rebuild starts and you're back to a stampede. Detect it with a metric on concurrent origin queries per key.
  • Waiter pile-up. 10,000 QPS blocked on one lock with a 200 ms rebuild parks ~2,000 goroutines. Fine in Go; in a thread-per-request stack it exhausts the pool. Watch queue depth and p99, not just error rate.
  • Stale-while-revalidate avoids the wait entirely (serve the stale value, refresh in the background) at the cost of a bounded staleness window. Right call for a product page, wrong one for an account balance.
  • Cache penetration. A key that doesn't exist is never cached, so every request for it hits the origin. Cache the negative result with a short TTL.

The signal to alert on is origin QPS correlated with a drop in hit ratio for a single key class, not overall hit ratio: a stampede on one hot key barely moves a global average.

cache statesource rps at 10,000 QPS
99% hit100
90% hit1,000
hot key expires~10,000

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-6

Explain the cold-cache problem after a cache server restart, and how cache warming addresses it.

Answer

What I'd say first

Two clarifications before answering: is one node restarting or the whole tier, and is the cache look-aside (the app reads the cache, and on a miss reads the origin and populates) or read-through? The blast radius changes; the mechanism doesn't.

A restarted cache node comes up with an empty keyspace, so its hit rate is 0% until it refills. Every read it receives falls through to the origin. If the cluster was serving 10,000 QPS at a 90% hit rate, the origin was absorbing 1,000 QPS. Restart one of three nodes and roughly 3,300 QPS now lands on the origin; restart the tier and all 10,000 does.

cache stateorigin rps at 10,000 QPS
90% hit1,000
cold cache~10,000

That is the cold-cache problem: the cache exists to absorb read load, and a restart removes that absorption exactly when the origin is least able to take it. Whether the origin survives is arithmetic. A 20-connection pool with 5 ms queries tops out at 20 / 0.005 = 4,000 QPS; 10,000 QPS of demand means the queue grows without bound and p99 climbs until timeouts start shedding load.

There's a second effect on top of the volume: a stampede. When a hot key is missing, every concurrent request for it misses and every one of them queries the origin. A single key at 500 QPS becomes 500 origin queries in the window before the first one populates the cache. That's why warming alone isn't sufficient: you also want request coalescing (single-flight: the first miss for a key fetches, the rest wait on the same future) or probabilistic early expiration (XFetch: refresh a key before its TTL expires, with probability rising as expiry nears).

Cache warming

Warming means populating the node with the keys it will be asked for before it takes production traffic. Three approaches, in rough order of fidelity:

  • Copy from a warm peer. If another replica holds the same keyspace, replicate or snapshot it (Redis replication, or DUMP/RESTORE for a subset). Highest fidelity, but only works when a warm peer exists: a full-tier restart has none.
  • Replay the hot set from access logs. Take the top-N keys by request count over the last hour and issue MGETs against the origin into the cache. Works from cold, but only covers what you logged, and the tail stays cold.
  • Shadow traffic. Add the node to the load balancer for a small percentage of reads while still serving from the warm nodes, so it warms organically. No extra origin load beyond what the traffic already causes, but it takes as long as the traffic takes to cover the keyspace.

Warming is not free: you're deliberately issuing the misses, just at a controlled rate instead of at arrival rate. A worked example: 1M keys, 50 concurrent workers, 5 ms per origin read gives 50 / 0.005 = 10,000 keys/s, so about 100 seconds to warm. That's 1M origin reads the origin must serve on top of live traffic, so throttle it and run it against a replica if you have one.

When warming doesn't help

If the working set is large and long-tailed, top-N warming covers a small fraction of requests. If the access pattern shifted since you captured the hot set, you warm the wrong keys. And warming does nothing for a single hot key under a stampede: that needs coalescing.

Failure modes to watch

  • The warming job itself saturates the origin: unbounded concurrency, no throttle. Detect via origin QPS spiking before the node takes traffic.
  • Warmed keys written without a TTL never expire, memory fills, and the eviction policy starts evicting the hot keys you just warmed. Detect via key count and eviction rate.
  • Crashloop: the node warms, dies, warms again, and each cycle re-hits the origin. Detect via restart count and repeated origin load spikes.
  • Warming from a peer that is itself stale or partially evicted: you inherit its gaps.

Detection is per-node hit rate, origin QPS and connection-pool saturation, and eviction rate, all on the same dashboard. If hit rate on the new node climbs but origin QPS doesn't fall, the warmed set doesn't match the live access pattern.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3

One cache key for a viral item absorbs 40% of your read traffic and saturates the single shard it hashes to: how would you fix it without giving up caching?

Answer

Two different failures share a cause here, and I'd fix them separately. Skew is a capacity problem: consistent hashing puts item:42 on one shard, so that node takes 40% of the reads while its neighbours idle. The same key's expiry is a stampede problem: at the TTL boundary every request misses at once and converges on one database row. Fixing the load imbalance without fixing the miss path gives you a balanced cluster that falls over every 60 seconds.

Assumptions I'd state up front: 50,000 rps read traffic, one key at 40%, 16 cache shards at roughly 25,000 ops/s each, 2 KB values, 60 s TTL, and the item tolerates a second or two of staleness. It's a product detail, not a permission check.

scenariobusiest shard, ops/s
no hot key, traffic uniform~3,125
hot key on one shard~21,875
hot key replicated 8 ways~4,375

1. Replicate the key. Store item:42:r0 … item:42:r7 and let each client pick a copy: hash of the request id, or round-robin. The spread comes from client choice, not from the hash function. Eight copies turn 20,000 rps against one key into 2,500 rps per copy. The price lands on the write path: updating the item now means rewriting or invalidating N copies, so N is a freshness-versus-ops knob, not a free win.

2. Coalesce the misses. One request per node fetches from origin; the rest wait for that result.

Go
// Go 1.22, golang.org/x/sync/singleflight
func GetItem(ctx context.Context, id string) (*Item, error) {
	if v, ok := memo.Get(id); ok { // local memo, 1.5s TTL
		return v.(*Item), nil
	}
	v, err, _ := group.Do(id, func() (any, error) {
		if b, gerr := cache.Get(ctx, replicaKey(id)); gerr == nil {
			return decode(b), nil
		}
		it, derr := db.GetItem(ctx, id) // one origin fetch per node per key
		if derr == nil {
			cache.Set(ctx, replicaKey(id), encode(it), 60*time.Second)
		}
		return it, derr
	})
	if err != nil {
		return nil, err
	}
	return v.(*Item), nil
}

Across 20 app nodes, one expiry produces 20 origin fetches instead of 20,000. To collapse that to one fetch per cluster you add a Redis SET key val NX PX 3000 lock, but treat it as a coalescing device, not a correctness primitive. It can expire under a slow holder and admit a second fetch, which is harmless here and would need fencing tokens if correctness depended on it (the argument in the Redis distributed-locks docs).

3. Bound local memoization. A 1–2 s in-process memo on every node cuts cross-node cache reads by roughly an order of magnitude and absorbs retry storms, at the cost of up to that TTL of divergence between nodes. Fine for a viral catalogue record; wrong for a balance.

4. Fall back when the key stays hot. Shortening the TTL cuts staleness but raises the miss rate, so pair it with coalescing. Frequency-based admission, admit a key only on its second request, keeps one-shot scan keys from evicting the working set (the same pollution concern the Redis eviction docs describe for LFU). If the value is a cheap single-row read, stop caching it and hit a read replica directly. At the HTTP layer, stale-while-revalidate / stale-if-error (RFC 5861) turn origin trouble into slightly old data instead of errors.

Detection. Top-K keys by ops from per-key counters, per-shard CPU and p99 against the cluster median, miss rate per key class. Alert when one shard's CPU runs 2x the median or a single key exceeds ~5% of traffic.

Failure modes. Replication skews itself if every client picks the same copy: measure hit distribution across r0..r7. A coalescing lock held against a slow origin turns one miss into a queue of waiting requests, so cap waiters and time out to a direct fetch. Short TTL without coalescing draws a sawtooth in origin QPS at every expiry boundary.

When not to bother: if measurement shows no skew, N-way replication is write amplification for nothing. If the value changes on every read, a live counter, don't cache it; INCR in Redis and serve from process memory.

Production lens

Validate with a load test that reproduces the skew shape (one key at 40%) instead of uniform traffic, watch top-K key distribution and per-shard CPU, and run an expiry drill that deletes the hot key to see the miss path under real concurrency.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

How would you design a multi-level caching architecture for a high-traffic web application, and what role does each level play?

Answer

A typical setup: a CDN caches static assets (images, JS/CSS) at the network edge, closest to users, absorbing the highest-volume, most cacheable traffic before it reaches your infrastructure at all. Behind that, a distributed cache (like Redis) shared across all application instances caches frequently-accessed dynamic data (user sessions, computed query results), reducing database load. Optionally, a small local in-process cache within each application instance caches extremely hot, small data with the absolute lowest possible latency (no network round trip), accepting some inconsistency risk across instances for that top tier's speed benefit. Each layer trades off scope/consistency for speed, with faster/smaller layers checked before falling back to slower/larger ones.

cache statesource rps at 10,000 QPS
90% hit1,000
cold cache~10,000

Production lens

Validate the choice with realistic traffic, cache-disabled load tests, per-key-class telemetry, and an explicit degraded-mode runbook.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-21

How would you decide whether to cache at the API gateway/edge layer versus deep within a specific microservice?

Answer

Caching at the API gateway/edge is effective for responses that are identical (or nearly so) regardless of which internal microservice ultimately produced them, and avoids even routing the request into the internal service mesh at all for a cache hit: maximum efficiency for broadly cacheable, non-personalized data. Caching within a specific microservice makes more sense when the cacheable unit is something internal to that service's own logic (e.g. a cached lookup table it uses internally) that doesn't map cleanly onto a full external API response: the right layer depends on whether the cacheable thing is naturally expressed at the API-response level or at some internal computation level within a single service.

cache statesource rps at 10,000 QPS
90% hit1,000
cold cache~10,000

Production lens

Validate the choice with realistic traffic, cache-disabled load tests, per-key-class telemetry, and an explicit degraded-mode runbook.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-24

Why might a caching strategy that works well for a monolithic application need to be redesigned when that application is split into microservices?

Answer

The relevant boundary is not 'monolith versus microservices' by itself but the number of independently deployed processes and data owners. A single-process monolith can use one coherent in-memory copy, while a horizontally scaled monolith already has many local caches. Splitting ownership across services adds more write paths, independently versioned schemas, and failure domains, so the design must define which service owns each cached representation, how invalidations cross boundaries, and how missed events are repaired. A shared cache may help fleet-wide reuse, but local caches with bounded TTLs or versioned event-driven invalidation can also be valid when their staleness contract is explicit.

cache statesource rps at 10,000 QPS
90% hit1,000
cold cache~10,000

Production lens

Validate the choice with realistic traffic, cache-disabled load tests, per-key-class telemetry, and an explicit degraded-mode runbook.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-25

How would you implement event-driven cache invalidation for a product catalog, where a product update should immediately invalidate its cached entry across all application instances?

Answer

Commit the product update and an invalidation intent atomically, for example in a transactional outbox, then publish the product ID and source version through a durable broker. Each cache owner consumes the event idempotently and deletes or conditionally updates its key; version checks prevent an older event from overwriting newer state. A Redis Pub/Sub notification can be a low-latency hint, but disconnected subscribers can miss it, so it is insufficient as the only path when immediate freshness matters. Keep a bounded TTL or reconciliation process, retry failed deliveries, and monitor invalidation lag.

cache statesource rps at 10,000 QPS
90% hit1,000
cold cache~10,000

Production lens

Keep a TTL or reconciliation path as a repair bound even when normal freshness is event-driven, and measure invalidation lag.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

How would you approach debugging a production issue where users report seeing stale data intermittently, given multiple caching layers might be involved (browser cache, CDN, application cache, database)?

Answer

Start by pinning down which layer is serving the stale value, because "stale data" has four different culprits and each has a different fix. I'd work from the outside in, comparing what each layer holds against the source of truth at the same moment.

First, reproduce and capture the evidence. Get an affected user's URL, timestamp, and if possible their user ID and region. Then:

  1. Browser. Open dev tools, check the Network tab: is the response coming from disk/memory cache, and what are the Cache-Control, ETag, and Last-Modified headers? A Cache-Control: max-age=3600 on an endpoint that should be fresh per-request is a bug you can fix right there.
  2. CDN. Most CDNs expose a hit/miss indicator: CloudFront's X-Cache: Hit from cloudfront, Fastly's X-Served-By and X-Cache: HIT/MISS, Cloudflare's cf-cache-status: HIT. Curl the URL with cache-busting off and on: curl -sD - https://example.com/api/x vs. the same with a random query param. If the un-busted request returns stale data and the busted one is fresh, the CDN edge is holding a stale object.
  3. Application cache. Query it directly: GET key in Redis, check the TTL (TTL key), and compare the value against the database. A stale value with a long TTL means your invalidation path is broken or the write path updates the DB without invalidating the key.
  4. Database. Confirm what the current value actually is, so you're not chasing a ghost: sometimes the "stale" data is correct and the user's expectation is wrong.

The layer whose value disagrees with the database is your culprit. If all layers agree and the user still sees stale data, suspect per-user or per-region variance: a CDN edge in one region holding an old object, or a cache key that embeds a user or version dimension you didn't check.

Common root causes, in rough order of frequency:

CauseSignatureFix
TTL longer than data freshness requirementStale value expires on its own eventuallyShorten TTL or move to explicit invalidation
Write path doesn't invalidate cacheStale until TTL expiry; reproducible after every writeInvalidate on write, or write-through
Race: read misses, write commits, miss fills with old valueStale for a full TTL after a write; intermittentDelete-after-write, or short TTL as backstop
CDN caching an endpoint it shouldn'tOnly CDN-cached users affected; cf-cache-status: HIT on a personalized responseCache-Control: private, no-store or bypass cache for authed routes

Trade-offs worth stating out loud. Long TTLs with no invalidation are simple but staleness is bounded only by the TTL. Explicit invalidation (delete the key on write) gives freshness but adds a failure mode: if the delete fails or races, you serve stale data for a full TTL, so most teams pair invalidation with a short TTL as a backstop. Write-through caching eliminates staleness but couples your write path to the cache and adds latency there. Cache-aside with versioned keys (key includes a version number bumped on schema/semantic change) makes invalidation trivial, you just stop reading the old key, at the cost of orphaned keys you need TTLs or a sweep to clean up.

Detection in production, not just debugging: log cache hit/miss ratios per endpoint, alert on invalidation failures, and for user-visible staleness, add a "data version" field to responses so support can compare what a user saw against the current version. If staleness is intermittent and you can't reproduce it, the race condition row in the table above is the usual suspect, and it's worth reproducing under load with a write-heavy test rather than guessing.

Curated: · Written: · Reviewed:

Difficulty: Hard