System designDeep dives8 min read

Caching in Depth

This lesson is for software engineers who can say "add a cache" in a system design interview and want to survive the follow-up questions. Interviewers rarely ask whether to cache. They ask what happens when the cached value is wrong, when it expires under load, or when one key gets most of the traffic.

By the end you will be able to place a cache, pick a read and write pattern and explain its consistency cost, choose TTLs and eviction, handle the classic failure modes, and size the effect on your database with simple arithmetic.

How caching shows up in the interview

Caching appears in almost every system design interview, usually once you have estimated a read-heavy workload. On SmartIntervu's system design rubric it feeds "deep dive and scalability" (does the cache actually remove the bottleneck?) and "trade-offs" (what staleness or complexity did you accept?). A cache drawn as a box with no pattern, TTL or invalidation plan gets little credit.

Where caches sit

A request can hit a cache at several layers, and each layer has a different invalidation story:

  • Client cache. The browser or app keeps responses according to HTTP headers such as Cache-Control: max-age=60. It is free for you, but you cannot invalidate it once it is cached, so use short lifetimes for anything that changes.

  • CDN. Edge servers close to users cache static assets and cacheable responses. Great for images, scripts and public pages. Purging is possible but takes time to propagate.

  • Application in-process cache. A small map inside each server process. Fastest possible lookups, but every server holds its own copy, so copies drift and memory is limited.

  • Distributed cache. A shared tier such as Redis or Memcached that all application servers read. This is what interviewers usually mean by "the cache." A lookup takes well under a millisecond inside a data center, versus several milliseconds or more for a database query.

  • Database buffer cache. The database keeps hot pages in memory on its own. It is why a database with a working set that fits in RAM is fast, and why your application cache must be justified by more than "the database is slow."

Read and write patterns

Cache-aside (lazy loading)

The application checks the cache; on a miss it reads the database, then writes the value into the cache. On a write it updates the database, then deletes the cache entry. This is the default for most systems because the cache only holds what is actually read, and a cache outage degrades to slower reads rather than failure.

Its consistency cost is a race. Reader A misses and reads the old value from the database. Writer B updates the database and deletes the cache entry. Reader A then writes the old value into the cache, where it stays until its TTL expires. Short TTLs bound how long that lasts. Deleting on write rather than updating the cache avoids a second race between two concurrent writers.

Read-through

The same as cache-aside, except the cache library loads from the database on a miss. It simplifies application code but has the same consistency behavior.

Write-through

Every write goes to the cache and the database synchronously. Reads right after a write see fresh data, at the cost of slower writes and caching data that may never be read. It still needs a TTL or eviction, because the cache cannot hold everything.

Write-behind (write-back)

Writes go to the cache and are flushed to the database asynchronously, in batches. Writes are very fast and the database sees far fewer operations, which suits counters and metrics. The cost is durability: if the cache node fails before flushing, those writes are lost. Only use it where losing a few seconds of writes is acceptable.

Write-around

Writes go straight to the database and skip the cache; the cache fills on the next read. Useful when written data is rarely read soon after, such as logs or bulk imports, so they do not push hot entries out of the cache.

TTLs and invalidation

Pick a TTL from how stale the data may be, not from habit. A product price shown in a listing might tolerate 60 seconds; a user's own account balance tolerates none and should not be cached on the read path at all. For data that is immutable once written, such as a short-code to URL mapping, use a long TTL and delete explicitly when the record is removed.

Two invalidation tools are worth naming:

  1. Explicit delete on write, as in cache-aside. Simple, and correct as long as every writer remembers to do it.

  2. Versioned keys. Include a version in the key (product:42:v7). A write bumps the version, and old entries simply stop being read and age out. This avoids the delete race entirely at the cost of storing a version somewhere.

Add random jitter to TTLs, for example 300 seconds plus or minus 30, so entries written together do not all expire together.

Eviction

When memory fills, the cache evicts entries. LRU (least recently used) evicts what has not been touched longest and suits most workloads. LFU (least frequently used) keeps entries with high long-run popularity, which helps when a one-off scan of many keys would otherwise flush the genuinely hot entries out of an LRU cache. Redis supports approximations of both. Saying which one you would choose and why is enough; implementing LRU is a separate coding question.

Failure modes interviewers ask about

Stampede (thundering herd)

A popular key expires, and thousands of concurrent requests all miss and hit the database at once. Fixes: request coalescing, where only one request per key loads from the database and the others wait for its result; serving stale while revalidating, where an expired value is returned while one background request refreshes it; and jittered or early expiration, so hot keys refresh before they expire.

Hot keys

A distributed cache shards keys across nodes, so one extremely popular key lands on one node. At high enough request rates that single node saturates while the others sit idle. Fixes: replicate the hot key under several names (key#0 to key#9) and read one at random, or keep a tiny in-process cache with a TTL of a second or two for the hottest keys so most requests never leave the server.

Cache penetration

Requests for keys that do not exist always miss and always reach the database. That is wasteful, and attackers can exploit it. Fixes: negative caching, where "not found" is cached with a short TTL such as 60 seconds, and a bloom filter of existing keys that rejects lookups for keys that cannot exist.

Cold start

After a deploy, a cache flush or a new region launch, the cache is empty and the database takes the full load. Warm the cache from recent access logs before shifting traffic, or ramp traffic gradually.

Hit-ratio arithmetic

This is the calculation that justifies a cache. Suppose 50,000 reads per second:

hit ratio 90%: 50,000 x 0.10 = 5,000 reads/s reach the database
hit ratio 99%: 50,000 x 0.01 =   500 reads/s reach the database

Going from 90 to 99 percent cuts database load tenfold, which is why the last few points of hit ratio matter so much. Average latency improves too. With a 1 ms cache lookup and a 10 ms database read on a miss:

90% hits: 0.90 x 1 ms + 0.10 x (1 + 10) ms = 2.0 ms average
99% hits: 0.99 x 1 ms + 0.01 x (1 + 10) ms = 1.1 ms average

The flip side: if the cache fails, the database suddenly receives all 50,000 reads per second, ten times what it handles at 90 percent hits. Say how you protect it: cache replicas, a circuit breaker that sheds load, or rate limits on the database path.

Worked example: caching URL redirects

The prompt is the URL shortener: about 4,000 redirects per second on average, and the interviewer asks you to make redirects fast and keep load off the database.

Weak answer: "Put Redis in front of the database so redirects are fast."

Strong answer:

  1. Pattern. Cache-aside on the redirect path, keyed by short code. Mappings never change after creation, so the main consistency risk is deletion; the delete path removes the cache entry explicitly.

  2. TTL. Long, such as 24 hours with jitter, because the data is immutable. Expired links are checked against their expiry time on read, so a cached entry never outlives its link.

  3. Sizing. Link traffic is typically skewed toward a small set of popular links. If we cache the 10 million most-requested mappings at about 600 bytes each including overhead, that is around 6 GB, which fits on a single cache node. We run replicas for availability, not capacity.

  4. Penetration. Random or mistyped codes are cached as "not found" for 60 seconds, so scanners cannot hammer the database.

  5. Hot keys. A link that goes viral can reach one cache node at a very high rate. Each redirect server keeps a small in-process cache with a 5-second TTL for the hottest codes.

  6. CDN and HTTP status. We could let browsers and the CDN cache redirects with a 301 status, removing most traffic entirely, but then clicks never reach us and analytics break. A 302 with a short Cache-Control keeps click counts accurate. That is a product decision, and saying so earns trade-off points.

  7. Failure. If the cache tier fails, the database would see the full 4,000 reads per second plus peaks. That is within reach of a sharded key-value store, but we also cap database concurrency so a cache outage slows redirects instead of taking the store down.

Mistakes that cost points

  • Caching without a reason. State the read rate and the hit ratio you expect, and show what load the cache removes.

  • No invalidation story. Every cached value needs an answer to "what happens when the source changes?"

  • Caching data that must be exact. Account balances, inventory at checkout and permissions need the source of truth.

  • Ignoring what happens when the cache is down. Your database must survive a cold or failed cache, or you must shed load.

Practice it

Take a read path from any system you know, write its read rate, and compute database load at 90 and 99 percent hit ratios. Then name its TTL and invalidation rule in one sentence each.

Next in this series: Load Balancing in Depth.

Practise this in a mock interview

Try what this lesson covers out loud: the AI interviewer asks one of these questions, follows up, and scores your answer.

Read next

  • Load Balancing in Depth

    Choose between Layer 4 and Layer 7, match the algorithm to the traffic, design health checks, drain long-lived connections, remove the load balancer as a single point of failure, and route users across regions.

    8 min read

  • Queues and Event Streams in Depth

    Choose between a message queue and an event log, state delivery semantics and ordering scope, size partitions and consumers, and handle lag, poison messages and the dual-write problem.

    9 min read

  • Search and Geospatial Indexes in Depth

    Explain inverted indexes, analyzers and ranking, keep a search index in sync with change data capture, support partial-word search, and size a find-nearby feature with geohashes or quadtrees.

    8 min read

  • How to Run a Deep Dive in a System Design Interview

    Pick the riskiest part of your design and work through it in five steps (numbers, options, trade-off, decision, failure mode), with a chat message fan-out as the worked example.

    9 min read