All modules

Caching: interview questions

14 questions. Try answering out loud before you open the model answer.

1. This read-heavy service sits on a single database and is getting slow. Where would you add caching, and what exactly would you cache?

Mid-levelcachingcache-asidehit-ratio

What the interviewer is really testing

Whether you decide from the workload (read to write ratio, skew, tolerance for staleness) instead of adding Redis by reflex, and whether you know the different layers a cache can sit at and what each is good for.

Show the model answer, follow-ups and checklist

Model answer

Before placing a cache I want three facts: what is slow or expensive, how skewed the reads are, and how stale each piece of data may be. A cache pays off when the same answer is requested many times between changes.

Then I work from the user inwards, because the best cache is the one closest to the user that can still serve a correct answer.

  • Browser and CDN. Static assets and public pages that are the same for everyone can be served at the edge. Those requests never reach us at all.
  • Shared application cache. For data that is per-entity but reused across requests, such as a product or a user profile, I would use cache-aside in Redis. The key is the entity id, the value is the assembled object the page needs, and the TTL is minutes with some jitter. On a write, the service updates the database and deletes the key.
  • In-process cache. A small set of very hot, rarely changing values can sit in the application’s memory with a TTL of seconds.
  • The database itself. It has its own buffer pool, so I would first check that the slow query is not simply missing an index.

Next I would estimate the benefit. If 90% of reads are for 10% of entities and each entity changes a few times a day, a hit ratio of about 90% is realistic from caching the popular tenth alone, and the database is left with about a tenth of the read load. If reads were spread evenly over a huge key space, I would expect a poor hit ratio and would not add the cache.

Finally I would say what I am not caching: anything used to make a decision that must be correct, such as stock at checkout. And I would note that the database must survive a cold or failed cache, so it needs either headroom or protection.

Likely follow-ups

How would you know the cache is doing its job?
Track the hit ratio, the eviction rate, cache latency and the database's read load before and after. A healthy cache shows a high and stable hit ratio and a database load that follows the miss ratio. A hit ratio that looks fine while the database is still busy usually means the expensive queries are not the ones being cached.
When would you add an in-process cache as well as Redis?
For a small amount of very hot, slowly changing data such as configuration, feature flags or a few hundred popular items. It removes the network hop and the deserialisation. The costs are memory on every instance and copies that disagree between instances, so I would give it a TTL of seconds or broadcast invalidations.
Would you cache query results or objects?
Objects keyed by id where I can, because it is obvious which key a write affects. Cached query results, such as a filtered list, are hard to invalidate because many different writes can change them. For those I rely on a short TTL or a version in the key.
What would you refuse to cache?
Anything where the decision needs the current value, such as a balance or stock check at the moment of purchase. Also data written more often than it is read, and requests so varied that entries would be evicted before they are reused.

Common mistakes

  • Saying "add Redis" without naming the key, the value, the TTL or the expected hit ratio.
  • Ignoring the layers in front of the application, when a CDN or browser cache would remove the request entirely.
  • Caching data that changes more often than it is read.
  • Not saying what happens to the database when the cache is empty or unavailable.
  • Treating the cache as a fix for a missing index or an N+1 query pattern.

A strong answer includes

  • Asks about read to write ratio, access skew and how stale each kind of data may be
  • Walks the layers from browser and CDN through the application cache to the database
  • Names the cache key, the cached value and a TTL for at least one concrete item
  • Estimates or reasons about the hit ratio and what load remains on the database
  • States the read and write pattern (for example cache-aside with delete on write)
  • Says what is deliberately not cached and why

Revise: Caching patterns

2. Writes to this data are frequent and reads must be fast. Would you use cache-aside, write-through or write-behind, and why?

Seniorcachingwrite-throughwrite-behind

What the interviewer is really testing

Whether you choose a write strategy from the durability and freshness requirements of the data, and whether you can say precisely what each option loses when something fails.

Show the model answer, follow-ups and checklist

Model answer

Two questions decide this. Can we afford to lose an acknowledged write? And must a read that follows a write see the new value?

If a write must never be lost, the database has to confirm it before we acknowledge. That rules out write-behind and leaves two options.

  • Cache-aside with delete on write. Write the database, delete the key, and let the next read reload it. It is simple, and the cache can fail without failing writes. The cost is a miss after every write. If writes to a key are as frequent as reads, that key is hardly ever cached, and I would question caching it at all.
  • Write-through. The cache layer updates its entry and the database synchronously. Reads after a write are hits and current, which matters when users reload straight after saving. Each write is slower, and the layer has to cope with one of the two writes failing.

If losing a few seconds is acceptable, write-behind fits. The write is acknowledged from the cache and flushed to the database in batches, with repeated updates to one key merged. It suits view counts, likes and last-seen timestamps. I would say plainly that a cache node failure loses whatever has not been flushed, and that the database lags, so reports and other services read old numbers.

In most systems I would mix them. For a social post, the body and settings use cache-aside with delete on write, because they change rarely and must not be lost. The like counter uses write-behind, because it changes constantly and an approximate value is fine. Orders and payments are written to the database directly and are read from it when a decision depends on them.

So my default is cache-aside, write-through when read-after-write freshness is worth slower writes, and write-behind only for data I am prepared to lose a little of.

Likely follow-ups

With write-behind, the cache node dies with ten seconds of writes queued. What are your options?
Those writes are gone unless the queue was durable. I can shrink the window with replication and frequent flushes, but if the loss is unacceptable the buffer should be a durable log such as Kafka, with a consumer applying changes to the database. At that point the design is a log-based pipeline with a cache as a read model, which is a more honest description.
Why not write the database and then SET the cache from the application?
Two writers can commit in one order and reach the cache in the other, leaving the older value cached. And the two writes are not atomic, so a crash between them leaves them different. Deleting the key gives the same result in any order and can be retried.
How do write-through and write-behind behave when the database is down?
Write-through fails the write, which is correct and visible. Write-behind keeps acknowledging and builds a backlog, which hides the outage from users and from you. It needs a bound on the queue and an alert on its depth, and a decision about what to do when the bound is reached.
A counter is incremented 10,000 times a second. How would you store it?
Increment in Redis with INCR, which is atomic and fast, and flush the accumulated delta to the database every few seconds as one update. I would accept losing a few seconds of counts on a failure and say so. If the count drives money, I would use a durable log and not write-behind.

Common mistakes

  • Choosing write-behind for speed without saying which acknowledged writes can be lost.
  • Describing "write the database, then set the cache" from application code as write-through and missing the ordering race.
  • Forgetting that with write-behind, anything that reads the database directly sees old data.
  • Treating all data in the system the same, when counters, profiles and orders need different answers.

A strong answer includes

  • Asks whether a lost write is acceptable and whether readers must see a write immediately
  • Gives cache-aside with delete on write as the default and says what it costs
  • Explains what write-through buys (fresh reads after writes) and its write latency cost
  • States the durability risk of write-behind and limits it to data that can tolerate loss
  • Mentions the non-atomic dual write and how the chosen pattern handles failure of either side
  • Picks different strategies for different kinds of data in the same system

Revise: Caching patterns

3. Your cache is at its memory limit and the hit ratio is falling. How do you choose an eviction policy, and what else would you check?

Seniorcachingevictionlru

What the interviewer is really testing

Whether you diagnose before tuning, know what the common policies assume about the workload, and know how the store you named really implements them.

Show the model answer, follow-ups and checklist

Model answer

I would diagnose first, because the policy is often not the cause.

What I would look at. The eviction rate and hit ratio over time, memory used against the limit, the number of keys and average value size, and how many keys have a TTL. In Redis I would also check the maxmemory-policy setting. If it is noeviction, writes are failing, not evicting. If it is a volatile-* policy and few keys have TTLs, very little is eligible.

Is the working set too big? If the set of keys read in, say, an hour is larger than memory, every policy will churn. The fixes are then capacity and shape: more memory or more shards, smaller values (cache only the fields used, compress large blobs), and not admitting keys that are read once, for example by caching only on the second request.

Then the policy. It should match how the data is accessed.

  • Skewed, with recently used items likely to be used again: allkeys-lru. This is the usual default.
  • Stable popularity plus scans or many one-off keys: allkeys-lfu, because a single access does not make a key look valuable. Redis LFU decays its counters, which matters when popularity shifts.
  • Near-uniform access: random eviction does as well as anything.
  • A mix of cache entries and data that must not be evicted in one instance: a volatile-* policy with TTLs only on cache entries, though I would prefer two instances.

What changed? A falling hit ratio usually has a cause in time. A new feature with high-cardinality keys, a batch job scanning the key space, larger values after a release, or growth in the number of users. Finding that is more useful than tuning.

I would change one thing, then watch the hit ratio and the database’s load, since that load is what the cache exists to reduce.

Likely follow-ups

How does Redis implement LRU?
Approximately. Each object stores a coarse last-access time, and when Redis needs memory it samples a handful of keys (five by default) and evicts the one idle longest, keeping a small pool of candidates between rounds. There is no global list, so reads stay cheap. Raising maxmemory-samples makes it closer to exact LRU at some CPU cost.
Every night the hit ratio collapses for an hour and then recovers. What is your first guess?
A batch job that reads through the whole key space. Under LRU each key it touches looks recently used, so the hot set is pushed out. I would have the job read the database directly or skip populating the cache, and consider an LFU policy, which a single pass does not fool.
Could you just set short TTLs and avoid eviction?
Short TTLs free memory, but they remove popular and unpopular entries alike, so the hit ratio falls for everything. Expiry is for freshness and eviction is for memory. I would set TTLs from how stale data may be and let the eviction policy decide what to drop under pressure.
How would you build an exact LRU with O(1) operations?
A hash map from key to node plus a doubly linked list in recency order. A get moves the node to the head, and a put inserts at the head and removes the tail when over capacity. Every read mutates the list and needs a lock, which is why large caches use approximations.

Common mistakes

  • Changing the policy before checking whether the working set simply does not fit in memory.
  • Believing Redis keeps an exact LRU list.
  • Using a volatile policy when few keys have a TTL, so that Redis has nothing to evict and rejects writes.
  • Confusing expiry with eviction.
  • Recommending LFU without mentioning that counters must decay or old popular keys never leave.

A strong answer includes

  • Checks eviction rate, hit ratio, memory per key and TTL distribution before changing anything
  • Explains what LRU and LFU each assume and the workload that breaks each
  • Knows the Redis policy families (allkeys and volatile) and the noeviction default
  • Describes Redis LRU or LFU as sampled approximations
  • Offers non-policy fixes such as more memory or shards, smaller values, and not caching one-off reads
  • Separates expiry (freshness) from eviction (memory)

Revise: Eviction policies

4. A popular cache key expires and a few seconds later the database is overloaded. What happened, and how do you prevent it?

Seniorcachingstampedesingle-flight

What the interviewer is really testing

Whether you can explain a stampede with arithmetic and layer the standard fixes, knowing the limits of each one instead of listing names.

Show the model answer, follow-ups and checklist

Model answer

This is a cache stampede. With cache-aside, every request that finds the key missing goes to the database. The key does not come back until the first recompute finishes, so every request in that window misses too.

The size is simple arithmetic. If the key is read 3,000 times a second and the query takes 300 ms, about 900 requests start the same query. The database then slows down under 900 copies of an expensive query, the window stretches, more requests join, and clients begin retrying. One expiry becomes an outage.

The principle behind every fix is the same: a missing key should be recomputed once, not once per request. I would layer the fixes.

  1. Request coalescing in each process. The first request to miss starts the load and the rest wait for its result. This is cheap and I would always have it. It bounds the damage to one query per app server.
  2. Stale-while-revalidate for hot keys. Store a soft expiry inside the value and a longer hard TTL on the entry. After the soft expiry, serve the old value immediately and let one request refresh it in the background. Nobody waits, and the database sees one query. Probabilistic early refresh achieves much the same without a lock.
  3. A lock or lease in the cache when the recompute is expensive enough that one per server is still too many.
  4. TTL jitter, so that keys loaded together do not expire together.
  5. A concurrency limit on that query, so that if everything else fails the database sheds load and does not collapse.

I would not apply all of this to every key. A stampede needs a key that is both hot and expensive to rebuild, so I would identify those few keys and protect them, with coalescing as the default for everything else.

Likely follow-ups

You have 50 app servers with in-process coalescing. That is still 50 queries. What if that is too many?
Add a lock or lease in the cache so one server in the fleet recomputes, for example a Redis SET with NX and a short expiry. The others serve the stale value if there is one, or wait briefly and re-read. The lock must expire by itself in case the holder crashes.
What should a request do when it loses the lock and there is no stale value?
Wait a short, bounded time and re-read the cache, with a small randomised delay between attempts and an overall deadline. When the deadline passes it should fail or return a degraded response. It should not fall through to the database, because that brings back the stampede.
How does probabilistic early expiry work?
Each read may choose to refresh before the real expiry, with a probability that rises as expiry approaches and scales with how long the recompute takes. On a hot key some request almost always refreshes early, so the key never expires under load. It needs no lock and no coordination.
What if the recompute fails?
Keep serving the stale value for a limited time, back off before trying again, and alert. Do not cache the error as if it were the value. Without a backoff, every request would retry the failing query, which is another kind of stampede.

Common mistakes

  • Proposing only a longer TTL, which makes the event rarer but no smaller.
  • Saying "add a lock" without an expiry on the lock or a plan for the requests that do not get it.
  • Assuming in-process coalescing gives one load for the whole fleet.
  • Forgetting that the database slows down under the load, which widens the window and makes it worse.
  • Applying heavy machinery to every key when only hot and expensive keys can stampede.

A strong answer includes

  • Explains that all requests arriving during the recompute also miss, and quantifies it as request rate times recompute time
  • Proposes in-process request coalescing as the baseline
  • Adds a distributed lock or lease when one load per server is too many, with a lock expiry
  • Offers stale-while-revalidate or early refresh so that requests do not wait
  • Mentions TTL jitter for keys loaded together
  • Protects the database with a concurrency limit as a last line of defence

Revise: Cache stampede and thundering herd

5. A large share of requests ask for ids that do not exist, and every one of them reaches the database. How do you handle it?

Seniorcachingpenetrationbloom-filter

What the interviewer is really testing

Whether you recognise that a normal cache gives no protection for keys that are absent, and whether you can weigh negative caching against a Bloom filter with their real costs.

Show the model answer, follow-ups and checklist

Model answer

This is cache penetration. A lookup for an id that does not exist misses the cache, finds nothing in the database, and by default stores nothing. The next request for the same id repeats the whole trip, so the cache offers no protection however large it is.

First I would find out who is asking. Missing ids can come from a client bug, from a crawler following stale links, or from an attacker sending random ids. The first is fixed at the source. The others need defences.

Validate early. If ids have a known format or range, reject impossible ones at the edge before any lookup.

Negative caching. When the database says “not found”, store a marker under that key with a short TTL, around 30 to 60 seconds. Repeated requests for the same missing id are then answered from the cache. This works well for the bug and the crawler, where the same ids recur. It works badly against random ids, since each one is new and each adds a marker.

A Bloom filter of existing ids. In front of the cache, keep a Bloom filter that contains every id that exists. If it says an id is definitely absent, return “not found” without touching the cache or the database. It can give false positives, which just proceed down the normal path, and it never gives false negatives as long as every new id is added when the item is created. This handles random ids with a fixed amount of memory.

Rate limiting. A client that produces a high rate of misses is throttled or blocked.

I would normally combine them: validation and negative caching as the cheap baseline, and a Bloom filter when the miss traffic is large or hostile. The costs I would mention are the filter’s memory, the work of keeping it current, and the short delay before a newly created item is visible if a marker is not cleared.

Likely follow-ups

What are the downsides of negative caching?
Each distinct missing key takes a cache entry, so an attacker sending random ids can fill memory with markers. And an item created just after a miss looks absent until the marker expires. I would keep the TTL short, delete the marker when the item is created, and give the markers their own small budget if the cache supports it.
How large is a Bloom filter for a billion ids at a 1% false positive rate?
About 10 bits per key, so roughly 1.2 GB, with seven hash functions. That fits in memory on one machine, though it is large to hold in every app server. Accepting a higher false positive rate, or sharing one copy behind a service, reduces the cost.
Items get deleted. How does the Bloom filter cope?
A standard Bloom filter cannot remove a key, so deleted ids keep answering "possibly present". They fall through to the normal path, where negative caching absorbs them. To keep the false positive rate from creeping up I would rebuild the filter periodically from the source of truth, or use a variant that supports deletion, such as a counting Bloom filter or a cuckoo filter.
Where does the filter live, and how is it kept current?
Either in each app server's memory, built from a snapshot and updated from a stream of newly created ids, or in a shared store at the cost of a network hop. A newly created id must be added before the item can be read, or it will be wrongly rejected, so the add belongs in the create path.

Common mistakes

  • Proposing a longer TTL or a bigger cache, neither of which helps for keys that are never stored.
  • Suggesting a Bloom filter without mentioning false positives, inserts or deletes.
  • Caching "not found" with a long TTL, so that new items stay invisible.
  • Not asking whether the traffic is a bug, a crawler or an attack, which changes the best fix.

A strong answer includes

  • Names the problem as cache penetration and explains why misses for absent keys are never cached by default
  • Proposes negative caching with a short TTL and deletion of the marker on create
  • Proposes a Bloom filter and states that false positives fall through while negatives are certain
  • Addresses how the filter is updated on insert and what happens on delete
  • Adds input validation and rate limiting for abusive clients
  • Considers the source of the traffic before choosing

Revise: Cache stampede and thundering herd

6. Your cache cluster goes down at peak traffic. What happens to the system, and what should have been in place?

Seniorcachingfailureavalanche

What the interviewer is really testing

Whether you treat the cache as a dependency with a failure mode, can trace the cascade to the database and back to the user, and can design both the protection and the recovery.

Show the model answer, follow-ups and checklist

Model answer

What happens. Every read becomes a miss. If the cache normally absorbs 95% of reads, the database is asked for twenty times its usual read load. It saturates, queries time out, application threads block waiting, and clients retry, which adds more load. If cache calls have long timeouts, the application stalls even before the database does. This is a cache avalanche, and unless it is designed for, it takes the whole service down.

What should be in place.

Do not lose everything at once. Shard the cache with consistent hashing so that one node failing loses about 1/N of the keys. Give each shard a replica in another availability zone and automatic failover.

Fail fast. Cache calls get timeouts in the tens of milliseconds and a circuit breaker, so that a dead or slow cache is skipped quickly.

Protect the database. Put a hard limit on concurrent queries from the fallback path. Beyond that limit, shed load. For many pages a degraded answer is acceptable: a slightly old copy from an in-process cache, a default list, or a clear error for less important features while critical paths are kept alive. Retries need backoff and a budget.

Know the numbers. I want to know what share of peak read traffic the database can serve alone. If the answer is 10%, the cache is a hard dependency and deserves the same redundancy and rehearsal as the database.

Recovery. An empty cache at peak is its own risk. I would warm it before giving it full traffic, by pre-loading hot keys or ramping gradually, with request coalescing so each key is loaded once, and with jittered TTLs so the refilled keys do not all expire together an hour later. If the cache is Redis with persistence, a restarted node comes back with old data, which is stale but far better than cold.

Likely follow-ups

The cache is back but empty. How do you bring it into service?
Gradually. Pre-load the hottest keys if I can, then ramp the share of traffic that uses it while watching database load. Coalescing and jittered TTLs need to be in place, or the refill itself causes a stampede and a second wave of expiries later.
Should the application treat a cache timeout as a miss?
For a read cache, yes, but behind a circuit breaker and a limit on database concurrency, otherwise a slow cache turns into a database overload. Where the cache holds state and not copies, such as sessions or rate limit counters, a timeout is not a miss, and I have to decide per use whether to fail open or closed.
Why are cache timeouts so important here?
A slow cache is worse than a dead one. If each call waits a second before giving up, request threads pile up and the service stalls even though the database is healthy. Cache calls should have timeouts of tens of milliseconds, and a breaker should stop calling a cache that keeps timing out.
When one cache node fails, should its keys be rehashed onto the survivors?
That is the simple option and usually fine with consistent hashing, since only that node's share moves. The risk is that a very hot key overloads its new owner and the failure cascades. Facebook's memcache paper describes an alternative, a small pool of spare servers that takes over a failed node's traffic with short TTLs.

Common mistakes

  • Saying "requests fall back to the database" and stopping there, without asking whether the database can take that load.
  • Leaving default or long timeouts on cache calls.
  • Planning for failure but not for the cold restart afterwards.
  • Assuming replication makes cache loss impossible, when a full flush or a bad deploy can still empty it.
  • Letting client retries multiply the load during the incident.

A strong answer includes

  • Traces the cascade from misses to database overload to timeouts and retries
  • States how much read traffic the database can serve without the cache
  • Limits the blast radius with shards, replicas and placement across zones
  • Sets short cache timeouts and a circuit breaker
  • Protects the database with concurrency limits and load shedding, and offers degraded responses
  • Describes a warm-up and ramp for recovery

Revise: Cache stampede and thundering herd

7. One key receives a large share of all traffic and the cache node that owns it is saturated. Adding nodes does not help. What do you do?

Staffcachinghot-keyssharding

What the interviewer is really testing

Whether you understand that sharding balances keys and not load, and whether you can offer several ways to spread or absorb a single key's traffic along with the consistency cost of each.

Show the model answer, follow-ups and checklist

Model answer

Adding nodes does not help because sharding spreads keys, not requests. A key hashes to exactly one node, and if that one key takes 30% of the traffic, its node takes 30% however many nodes exist. So the fix has to act on the key itself.

Absorb reads before they reach the cache. Put a small in-process cache on each app server for the handful of hottest keys, with a TTL of about a second. With 100 app servers, the shared cache then sees at most about 100 reads a second for that key, whatever the user traffic is. The cost is up to a second of extra staleness and a little memory per server. This is usually the most effective single change.

Spread reads over more machines. Two ways:

  • Read the key from the shard’s replicas as well as its primary. This is simple, and replicas may lag slightly.
  • Split the key. Store N copies under names with a suffix from 1 to N, which hash to different nodes, and have each reader pick a suffix at random. Reads spread over up to N nodes. Every write must now update or delete N copies, so this suits keys that are read far more than written.

Shrink the cost per read. If the value is large, the node may be limited by network and not CPU. Compress it, or split out the part that most readers need.

Detect and automate. These measures apply to a few keys, so I need to know which ones. I would sample keys at the client or proxy to maintain a list of the current heaviest keys, and apply the local cache or the split to the keys on that list automatically, since hot keys change with events.

The trade in every option is the same: I buy capacity for one key with a slightly staler value or with more work on write. For a celebrity profile or a viral item, a second of staleness is an easy price to pay.

Likely follow-ups

How do you find hot keys before they cause an incident?
Sample requests in the client library or proxy and keep a running top-k, which costs little. Per-node CPU and network metrics show that a node is hot but not why. Redis can also report hot keys from its LFU counters when an LFU policy is in use. I would alert on any key taking more than a set share of a node's traffic.
With N copies of a key and a local cache on every server, how do you invalidate?
Delete all N suffixed copies on a write, which is N small operations. Local copies rely on a TTL of a second or so, or on an invalidation message broadcast to the app servers. Either way there is a bounded staleness window, and I would state its length.
The hot key is hot for writes, such as a like counter on a viral post. Now what?
Split the counter into several sub-counters on different nodes and sum them on read, or buffer increments in each app server and send one combined delta every second. Both make the count slightly delayed or approximate, which is usually acceptable for a counter shown to users.
What happens when the hot key expires?
It is the worst key for a stampede, since it has the highest read rate. I would never let it expire under load. Refresh it in the background before expiry, or serve it stale while one request reloads it.

Common mistakes

  • Proposing more shards or more virtual nodes, which does not divide a single key.
  • Offering a local cache without stating its staleness or how it is invalidated.
  • Forgetting that splitting a key multiplies the work on every write.
  • Ignoring the write-hot case or the expiry of the hot key.
  • Having no way to detect which key is hot.

A strong answer includes

  • Explains that one key maps to one node, so consistent hashing or more nodes cannot spread it
  • Proposes a short-TTL in-process cache for the hottest keys
  • Proposes spreading reads across replicas or across N suffixed copies of the key
  • States the consistency cost of each option and how invalidation works
  • Covers detection of hot keys
  • Addresses hot writes and the stampede risk on the hot key

Revise: Cache stampede and thundering herd

8. How do you decide what TTL to put on a cache entry?

Mid-levelcachingttlstaleness

What the interviewer is really testing

Whether you see a TTL as a bound on staleness chosen per kind of data, can reason about its effect on hit ratio and load, and know it works alongside invalidation instead of replacing it.

Show the model answer, follow-ups and checklist

Model answer

A TTL answers one question: if nothing else corrects this entry, how long may it be wrong? So I choose it per kind of data, from four inputs.

How stale may it be? This is a product question. A product description can be an hour old. A price that is displayed but checked again at checkout can be a minute old. A permission that has been revoked may need to take effect within seconds.

How often does it change, and is there invalidation? If writes delete the key, the TTL is only a safety net and can be generous. If there is no invalidation, the TTL is the whole consistency story and must match the tolerance above.

What does a miss cost, and how hot is the key? For one key, the hit ratio is roughly 1 minus 1 over (requests per second times TTL in seconds). A key read 100 times a second with a 10 second TTL misses once per 1,000 reads, which is 99.9%. Raising the TTL to 60 seconds moves that to about 99.98%, a small gain for six times the staleness. For hot keys a short TTL already captures nearly all of the benefit. Long TTLs matter mostly for the long tail of rarely read keys, where the question is whether to cache them at all.

Memory. Entries that outlive their usefulness take space, although the eviction policy handles that if the TTL does not.

Then two refinements. I add random jitter of 10 to 20% so that keys written together do not expire together. And I use different TTLs for special cases: short, such as 30 seconds, for “not found” markers, and long for immutable data.

So the answer is never a single number. For a shop I might say: catalogue pages one hour with delete on write, prices one minute, session data matched to the session length, and negative results 30 seconds.

Likely follow-ups

If invalidation on write is reliable, why have a TTL at all?
Because invalidation is never fully reliable. Deletes fail, races re-insert old values, and a script or another service writes without invalidating. The TTL caps how long any such mistake can last. With good invalidation the TTL can be long, but I would not remove it.
After a deploy the cache was flushed and refilled within a minute, with a one hour TTL on everything. What happens next?
An hour later most keys expire within the same minute and the database takes a wave of reloads. Adding random jitter of 10 to 20% to each TTL spreads the expiries out, so the wave becomes a gentle slope.
Is a short TTL a substitute for invalidation?
Only if the product accepts that staleness for everyone, including the person who just made the change. A user who edits their profile and sees the old one for 30 seconds will think the save failed. For user-edited data I would invalidate on write and keep the TTL as the backstop.
What TTL would you give data that never changes?
A long one, such as a day or more, since it cannot be stale. Memory is then managed by the eviction policy and not by expiry. Immutable data is also a good fit for versioned keys, where a new version gets a new key.

Common mistakes

  • Giving one TTL for the whole system instead of one per kind of data.
  • Choosing by instinct without relating the TTL to request rate and the cost of a miss.
  • Treating a short TTL as a consistency guarantee.
  • Forgetting jitter, so that keys loaded together expire together.
  • Setting no TTL because "we invalidate on write".

A strong answer includes

  • Frames the TTL as the maximum staleness when nothing else corrects the entry
  • Sets it per data type from business tolerance for stale data and how often the data changes
  • Relates TTL and request rate to hit ratio and shows diminishing returns
  • Says that active invalidation allows a longer TTL but does not remove the need for one
  • Adds jitter
  • Uses short TTLs for negative entries and long ones for immutable data

Revise: Cache invalidation

9. When a row changes, do you update the cache entry or delete it? Walk me through the race conditions.

Seniorcachinginvalidationrace-conditions

What the interviewer is really testing

Whether you can reason step by step about interleavings between concurrent readers and writers across two systems, and whether you know which races are common, which are rare and how each is contained.

Show the model answer, follow-ups and checklist

Model answer

I delete, after the database commit. Here is why, race by race.

Race 1: update on write. Writers A and B both change the row. A commits first, then B, so the database holds B’s value. Each then sets the cache, but nothing forces those calls to arrive in commit order. If B’s set lands first and A’s second, the cache holds A’s value and the database holds B’s. It stays wrong until the TTL. A delete avoids this because two deletes give the same result in either order.

Race 2: delete, then write. If I delete first, a reader can arrive before my commit. It misses, reads the old row and caches it. My commit lands, and the cache now holds the old value with nothing left to remove it. This is not an unusual interleaving. It happens whenever a read falls between the two steps, so on a hot key it happens constantly.

So: write, then delete. Now the worst ordinary case is a brief window between commit and delete in which readers see the old value, and the delete then closes it.

Race 3: the one that remains. A reader misses and reads the old row. Before it stores the value, a writer commits and deletes the key. The reader then stores the old value. This needs a miss, a concurrent write and a reader slower than the writer, so it is rare with a single database. It is much more likely when misses are filled from a read replica, because the reader can pick up the old row for as long as the replica lags.

Containing it. Every entry has a TTL, so nothing is wrong for ever. For more, I would use a delayed second delete, or have the cache reject stale sets with a lease or version check, or fill from the primary shortly after a write. And because a delete can simply fail, I would back it with retries or CDC-based invalidation.

Likely follow-ups

Why delete after the transaction commits and not inside it?
Before the commit, other connections still see the old row. A reader that misses after an early delete reloads the old value and caches it, and nothing removes it later. If the transaction rolls back, the delete was also a wasted miss. So the delete goes after a successful commit.
The database write succeeds and the delete fails. What now?
Retry with backoff, and if that fails hand the key to a retry queue so the request can finish. The backstop is the TTL. For stronger assurance, invalidate from the database's change log with CDC, which will see the commit even if the application crashed straight after it.
How would you choose the delay for a delayed double delete?
It has to exceed the time a stale reader could still be holding old data, which is the replication lag plus a slow read. About a second is typical. It is a heuristic, since a longer pause or lag defeats it, so I would still keep a TTL.
How do leases close the stale-set race?
On a miss the cache gives the reader a token for that key. A delete invalidates outstanding tokens. When the slow reader later tries to set the old value with its token, the cache rejects it. A version number stored with the value, checked on set, has a similar effect.

Common mistakes

  • Updating the cache from application code and not seeing the lost ordering between two writers.
  • Deleting the cache entry before writing the database.
  • Claiming that write-then-delete is free of races.
  • Forgetting that the delete can fail or that some writers bypass the application.
  • Ignoring read replicas, which make the stale-set race much more likely.

A strong answer includes

  • Chooses delete over update and explains the two-writer ordering race
  • Orders the steps as database commit first, then delete, and explains why the reverse is worse
  • Describes the remaining stale-set race between a slow reader and a writer
  • Mentions the replica lag variant
  • Handles a failed delete with retries, CDC or both
  • Keeps a TTL as the final bound and names leases or version checks as the stricter fix

Revise: Cache invalidation

10. Can you guarantee that the cache never returns data that differs from the database? If not, what can you promise?

Staffcachingconsistencyinvalidation

What the interviewer is really testing

Whether you can state consistency guarantees precisely, resist over-promising, and design the system so that the staleness a cache introduces cannot cause incorrect outcomes.

Show the model answer, follow-ups and checklist

Model answer

No. The cache and the database are separate systems with no shared transaction, so there is always some moment when one has changed and the other has not. I could shrink that moment by making every write coordinate with the cache, for example by holding a lock across both. But then every write depends on the cache being available, latency rises, and a crash in the middle still leaves a gap. I would have built a slower database and lost the reason for having a cache.

What I can promise is bounded staleness, and I would put numbers on it.

  • In normal operation, a read reflects any write that committed more than a few tens of milliseconds ago. That is the gap between the commit and the delete.
  • When something goes wrong, such as a failed delete, a race or a writer that bypassed the application, the entry is wrong for at most the TTL, say five minutes.
  • With invalidation from the database’s change log as a backstop, missed deletes are caught within the pipeline’s lag, typically a second or two, and the TTL covers only a stalled pipeline.

On top of that I can add specific guarantees where they matter. Read-your-writes for the author is cheap to provide and covers most complaints, because people notice staleness mainly in their own changes.

Then I design so that staleness is harmless.

  • Decisions that must be right do not read the cache. Checkout reads stock and price from the database. A permission check for a sensitive action reads the source of truth or uses a very short TTL.
  • Writes are conditional. An update carries the version it was based on, and the database rejects it if the row has moved on. A stale read then causes a retry, not a corrupt record.

So the honest statement is: the cache is eventually consistent, typically within milliseconds and always within the TTL, and nothing whose correctness matters depends on it.

Likely follow-ups

How would you give a user read-your-writes through a cache?
After a user writes, route that user's reads for the affected data past the cache to the primary for a few seconds, tracked with a timestamp in their session. Or return the new value from the write and let the client show it. Other users still see bounded staleness, which is usually fine.
A service reads a cached value, changes it and writes it back. What can go wrong?
A lost update. The cached value may be stale, so the write overwrites a newer change. Read-modify-write should read from the database inside a transaction, or use a conditional write that checks a version column, so that a stale read makes the write fail and not corrupt data.
How does this change with caches in several regions?
A write in one region must invalidate caches in all of them, and the remote region's database replica lags. If the remote delete arrives before the replicated row, the next read re-caches the old value. Driving each region's invalidation from that region's own replication stream orders the delete after the data.
How would you know how inconsistent the cache really is?
Measure it. Run a checker that samples keys, compares the cached value with the database, allows for in-flight writes by re-checking after a short delay, and reports the mismatch rate. Without that number, "eventually consistent" is a hope and not a guarantee.

Common mistakes

  • Claiming the cache is always consistent because writes invalidate it.
  • Proposing a distributed transaction between cache and database without acknowledging the cost and remaining failure windows.
  • Giving no numbers for the staleness bound.
  • Allowing correctness-critical decisions or read-modify-write cycles to use cached values.
  • Forgetting replica lag and multi-region propagation.

A strong answer includes

  • Says no, and explains that the two systems do not share a transaction
  • States the achievable guarantee as eventual consistency with a bounded staleness, with numbers
  • Lists the mechanisms that produce that bound (write then delete, CDC, TTL)
  • Offers read-your-writes for the author as a targeted addition
  • Keeps decisions that must be correct on the source of truth, with conditional writes
  • Proposes measuring the inconsistency rate

Revise: Cache invalidation

11. Users report that they sometimes see old data for several minutes after saving a change. How do you debug it?

Seniorcachinginvalidationdebugging

What the interviewer is really testing

Whether you can debug methodically across every layer that holds a copy of the data, use the symptoms to narrow the cause, and avoid jumping to a fix before finding which cache is stale and why.

Show the model answer, follow-ups and checklist

Model answer

I would start by characterising the symptom, because its shape points at the cause.

Questions first. How long does the old data last, and does that match a TTL somewhere? Does it affect the user who saved, other users, or both? Is it every save or occasional? On refresh, is it steadily old or does it flip between old and new?

List every copy. The data may be held in the browser cache, the CDN, an in-process cache on each app server, the shared cache, and read replicas. I would write down each layer’s TTL and compare it with the reported duration. “Several minutes” that matches the shared cache’s five-minute TTL is a strong hint. A response header that says which layer served the value makes this much faster.

Then test hypotheses in order of likelihood.

  1. The delete does not happen on some path. Is there an admin tool, batch job or second service that writes the table without invalidating? Are there errors or timeouts on delete calls in the logs?
  2. The wrong key is deleted. The write path deletes one key, but the read path uses a different one, or several derived keys such as a list or a per-locale variant that nobody invalidates.
  3. Wrong order. The code deletes before the commit, so readers re-cache the old row.
  4. Refill from a lagging replica. The delete works, but the next read fetches the old row from a replica and caches it for a full TTL. “Sometimes” and “lasts exactly the TTL” both fit this.
  5. Local caches. If the value flips on refresh, different app servers hold different copies.

Fix the cause. For a missing path, add invalidation there or move to CDC so that every commit invalidates. For replica refill, fill from the primary shortly after a write or add a delayed second delete. For key mismatches, derive keys in one shared function.

I would finish by adding a checker that samples cached values against the database, so that the next regression shows up as a metric before a user reports it.

Likely follow-ups

On refresh, the page flips between the old and the new value. What does that tell you?
More than one copy is being served and they disagree. The usual suspects are in-process caches on individual app servers, read replicas with different lag, or different CDN edge locations. A single shared cache with a wrong value would be consistently wrong, not alternating.
The staleness always lasts almost exactly five minutes, which is the TTL. What does that suggest?
The entry was never deleted, or an old value was written back after the delete, and only expiry corrected it. I would look for a failed or missing delete, a writer that bypasses invalidation, a key mismatch, or a reader refilling from a lagging replica.
How would you confirm that replica lag is the cause?
Log each cache fill with the source it read from and the row's version or update time, then look for fills that stored a version older than one already committed. Comparing the fill time with the replica's measured lag confirms it. Temporarily filling from the primary for one key class should make the problem disappear.
How do you stop this from coming back?
Fix the specific cause, then add monitoring that would have caught it. A background checker that samples keys and compares cache with database gives a mismatch rate to alert on. CDC-based invalidation covers writers that the application code does not know about.

Common mistakes

  • Shortening the TTL as the first move, which hides the symptom and lowers the hit ratio without finding the cause.
  • Looking only at the application cache and forgetting the browser, the CDN, in-process caches and read replicas.
  • Not using the pattern of the symptom (duration, who is affected, flipping or steady) to narrow the search.
  • Assuming the invalidation code runs for every write path.
  • Declaring it fixed without a way to measure staleness afterwards.

A strong answer includes

  • Characterises the symptom first, including how long it lasts, how often, and whether it alternates
  • Lists every layer that can hold a copy, from the browser to read replicas
  • Compares the staleness duration with the TTL of each layer
  • Checks the write path order, delete failures and writers that bypass invalidation
  • Checks that the key deleted is the key read, including derived and variant keys
  • Considers the replica-fill race and proposes a way to confirm it
  • Ends with monitoring or CDC so the class of bug is caught in future

Revise: Cache invalidation

12. You put a CDN in front of product pages. How do you choose the cache key, and how does a price change reach users quickly?

Seniorcachingcdncache-control

What the interviewer is really testing

Whether you understand HTTP caching as a contract set by the origin, can design a cache key that is neither too broad nor too narrow, and can combine TTLs, validation and purging so that changes propagate without sacrificing the hit ratio.

Show the model answer, follow-ups and checklist

Model answer

The cache key. The rule is that everything that changes the response is in the key and nothing else is. For a product page I would use the host, the path and a normalised query string. Normalising means dropping tracking parameters and sorting the rest. If the page differs by country or currency, I add that as a small segment value computed at the edge. I would not add cookies, the full User-Agent or anything per user, because each of those gives every visitor their own copy and the hit ratio falls to nothing.

Per-user content. The page shell is the same for everyone, so that is what the CDN caches. The basket count and the user’s name come from a separate request that the origin marks private or no-store. The CDN never has a personalised object to serve by mistake.

Freshness. The origin sends something like Cache-Control: max-age=60, s-maxage=86400, stale-while-revalidate=30 with an ETag. The CDN may keep the page for a day. Browsers keep it for a minute, because a browser cache cannot be purged.

Making a price change visible. A day is far too long to wait, so the CDN lifetime is only a ceiling. Each response carries tags for the entities it was built from, for example the product and its category. When the price service commits a change, it publishes an event, and a small consumer calls the CDN’s purge API for that product’s tag. Every page and API response that included the product is dropped within seconds, and the next request refetches. Browser copies are at most a minute old.

The limit of this. The cached price is for display. Checkout reads the price from the source of truth and shows the user any difference, so a stale page can never cause a wrong charge.

So the design is a long, purgeable CDN lifetime, a short browser lifetime, tag-based purging driven by writes, and a server-side check where the value matters.

Likely follow-ups

The CDN hit ratio is 30%. How do you investigate?
Look at what makes keys unique. Tracking parameters, unsorted query strings, a Vary header on a high-cardinality request header and cookies in the key are the usual causes. Then check whether the TTL is too short and whether traffic is long-tail, in which case each edge location rarely sees a repeat and a tiered cache or origin shield helps.
Someone wants to purge the whole cache at peak after a bad deploy. What do you say?
A full purge sends all traffic to the origin at once, which is a self-inflicted stampede. Prefer purging by tag for the affected content, or a soft purge that marks objects stale so they can be served while they revalidate. If a full purge is unavoidable, the origin needs to be protected first.
How do you make sure a logged-in page is never served to someone else?
The origin marks any per-user response as private or no-store, and the CDN is configured to respect origin headers and to bypass the cache for requests with a session cookie. I would not rely on rules that infer cacheability from the URL. I would also add an automated test that requests a page as two users through the CDN.
How do you ship a new JavaScript bundle without users getting a mix of old and new?
Fingerprint asset file names with a content hash and cache them for a year as immutable. The HTML references the new names and is itself revalidated or short-lived. Keep the previous build's files available so pages loaded before the deploy still work.

Common mistakes

  • Saying "cache it at the CDN" without stating the headers or the key.
  • Putting cookies, session tokens or the full User-Agent in the cache key.
  • Leaving out of the key something that changes the response, such as currency or language.
  • Giving HTML a long browser max-age, which no purge can undo.
  • Trusting the cached price at checkout.

A strong answer includes

  • Defines the key as host, path and a normalised query string plus only the inputs that change the response
  • Separates browser lifetime (max-age) from CDN lifetime (s-maxage)
  • Purges by surrogate key or tag when the product changes, triggered by the write
  • Uses validators and stale-while-revalidate to make refreshes cheap and invisible
  • Keeps per-user content out of the shared cache by splitting the page
  • Notes that browsers cannot be purged and that checkout re-reads the price

Revise: CDN caching

13. You are using Redis for more than a cache. How do you make it durable and highly available, and what can still be lost?

Seniorredispersistencereplication

What the interviewer is really testing

Whether you know what RDB, AOF, replication, Sentinel and Cluster each provide, and above all whether you can say precisely which writes can still be lost and design around that.

Show the model answer, follow-ups and checklist

Model answer

I would take durability and availability separately, and then say what is still at risk.

Durability on one node. Redis has two mechanisms. RDB writes periodic snapshots, which are compact and quick to load but lose everything since the last one. AOF logs every write, and its fsync policy sets the loss window: everysec can lose about a second on a crash, and always syncs before replying at a large cost in throughput. I would run AOF with everysec plus RDB snapshots for backups and faster recovery.

Availability. Each primary gets at least one replica in another availability zone. Failover is automatic, through Sentinel if the dataset fits on one node, or through Redis Cluster if I need to shard. Cluster divides the key space into 16,384 hash slots spread across primaries. Clients cache the slot map and are redirected with MOVED when it changes. Commands that touch several keys work only within one slot, which I arrange with hash tags.

What can still be lost.

  • Replication is asynchronous. If a primary acknowledges a write and dies before sending it to a replica, the promoted replica does not have it.
  • During a partition, an isolated primary can keep accepting writes for a short time. When it rejoins as a replica, those writes are discarded. min-replicas-to-write narrows this window.
  • WAIT lets a client block until some replicas have acknowledged, which lowers the odds of loss. It does not turn Redis into a consistent store.

So even with everything switched on, the honest guarantee is “may lose the last second or so of writes on a failover”.

Designing around it. For rate limit counters, sessions, leaderboards and queues of work that can be regenerated, that is acceptable. For money, orders or anything that must not be lost, Redis holds a derived copy and the system of record is a database with synchronous durability. If I catch myself adding more and more machinery to make Redis safe for such data, that is the sign it is the wrong store for it.

Likely follow-ups

Sentinel or Redis Cluster?
If the data fits comfortably on one node and I only need failover, Sentinel or a managed equivalent is simpler and keeps multi-key commands unrestricted. If I need more memory or write throughput than one node offers, I need Cluster, and I accept its rule that multi-key operations stay within one hash slot.
What does taking an RDB snapshot cost a busy node?
Redis forks, and the child shares memory with the parent through copy-on-write. Pages the parent modifies during the snapshot are copied, so under heavy writes memory use can approach double. The fork itself can also pause the process briefly on a large heap. I would leave memory headroom and often snapshot on a replica.
A transaction touches two keys that live in different slots. What happens?
Redis Cluster rejects it with a cross-slot error. I would give related keys a shared hash tag, so that only the tagged part is hashed and they land in one slot. Tags should be fine-grained, such as a user id, or one slot becomes a hot spot.
How do you limit the damage of a network partition that isolates the primary?
Set min-replicas-to-write so that a primary that cannot reach enough replicas stops accepting writes after a short lag threshold. In Cluster, a primary on the minority side also stops accepting writes once the node timeout passes. This narrows the window in which writes are accepted and later discarded, without closing it.

Common mistakes

  • Saying "turn on AOF" and treating Redis as fully durable.
  • Believing replication is synchronous, or that WAIT makes Redis strongly consistent.
  • Confusing Sentinel (failover) with Cluster (sharding plus failover).
  • Forgetting the single-slot restriction on multi-key commands in Cluster.
  • Not stating what happens to writes accepted by an isolated old primary.

A strong answer includes

  • Explains RDB and AOF and the data-loss window of each fsync policy
  • States that replication is asynchronous and failover can lose acknowledged writes
  • Distinguishes Sentinel from Cluster and picks one for a stated reason
  • Describes hash slots, client redirection and the multi-key restriction with hash tags
  • Mentions partition behaviour and settings that bound the loss
  • Keeps the system of record elsewhere for data that cannot be lost

Revise: Redis vs Memcached

14. You said you would use Redis for the cache. Why not Memcached? Which would you pick for this workload?

Mid-levelredismemcachedcaching

What the interviewer is really testing

Whether your technology choice is a decision with reasons tied to the workload, and whether you know the real differences between the two (data model, threading, persistence, clustering) instead of a general preference.

Show the model answer, follow-ups and checklist

Model answer

I would answer from the workload, so let me take two versions of it.

If the cache only stores serialised objects with get, set and delete, and losing its contents on a restart is acceptable, Memcached is a sound choice and arguably the simpler one. It is multi-threaded, so one process uses every core of a large machine. Its slab allocator gives predictable memory use, and there is very little to configure. Scaling is done in the client with consistent hashing across independent servers. Redis would also work here, and the difference would be small.

If the workload needs anything beyond that, I would choose Redis, and most workloads eventually do. The reasons would be specific:

  • Data structures. A feed as a sorted set, a rate limiter as a counter with an expiry, a set of online users. In Redis each is one atomic server-side command. In Memcached each is a fetch, modify and rewrite cycle with a check-and-set loop to handle conflicts.
  • Restart and failure behaviour. Redis can snapshot or log to disk and restart warm, and it has built-in replication with automatic failover. A Memcached node that restarts is empty, and its share of keys miss until they are refilled.
  • One system, several jobs. The same Redis deployment can serve the cache, rate limiting and short-lived locks, which is less to operate than two technologies.

The costs I would acknowledge are that Redis runs commands on one thread, so I must avoid slow commands and scale by adding shards, and that its replication is asynchronous, so it is not a system of record.

For the design in front of us, I chose Redis because we already need counters and a ranked list elsewhere in the system, and I would rather run one store. If the interviewer told me the only need was a 500 GB cache of rendered fragments, I would be happy to switch to Memcached and say so.

Likely follow-ups

Is Redis slower because it is single-threaded?
For simple gets and sets on a machine with many cores, one Memcached process can use all of them, while one Redis process executes commands on a single thread. Redis closes the gap with I/O threads and by running several shards per machine. For most services either is fast enough and the network round trip dominates, so I would not choose on raw speed alone.
Where would you keep user sessions?
If losing sessions on a node failure only means some users log in again and that is acceptable, either works. If sessions must survive a restart or failover, I would use Redis with replication and persistence. I would also set a TTL equal to the session lifetime.
You started with Memcached. What would make you move to Redis?
The first feature that needs server-side structure or atomicity, such as a counter with expiry for rate limiting, a ranked list or a set. Other triggers are needing the cache to restart warm, or wanting built-in replication and failover in place of client-side sharding.
Does the Redis licence change affect your choice?
It can for a company that offers Redis as a service or has a policy on source-available licences. Since 2024 there is Valkey, a BSD-licensed fork that major cloud providers offer as a managed service and that works with the same clients. I would say "Redis or Valkey" and let the organisation's policy decide.

Common mistakes

  • Answering "Redis is better" or "Redis is faster" with no reference to the workload.
  • Saying Memcached is obsolete, when it remains a sound choice for a plain blob cache.
  • Claiming Redis is entirely single-threaded or that Memcached supports persistence and replication natively.
  • Choosing Redis for durability without mentioning that failover can lose recent writes.

A strong answer includes

  • States the workload's needs first (operations, data shapes, restart and failure tolerance)
  • Compares data model, threading, persistence and clustering accurately
  • Picks one and gives a reason tied to the workload
  • Names a case where the other would be the better choice
  • Mentions operational factors such as managed offerings and running one system instead of two

Revise: Redis vs Memcached