System Design - Caching
Serve hot data from memory and pick the write strategy that matches your risk tolerance.
A cache is a small, fast notebook sitting on top of a huge, slow filing cabinet. Instead of walking to the cabinet for every answer, you check the notebook first. Most requests never leave the desk - and that is the whole performance story. The craft is deciding what goes in the notebook, when a page is out of date, and what happens when everyone asks for the same missing page at the same moment.
Builds on
- Big-O notation — cache hits are O(1) and the point is to remove O(n) or O(log n) database work.
- Hash maps — caches are key-value stores at heart - a hash map with an eviction policy.
Why a cache changes everything
Imagine a profile page that is opened 30,000 times a second. Every open needs the same few fields: name, photo, bio. If each open runs a query, the database does the same work over and over for answers that barely change. A cache is a fast copy of those answers kept close to the code that needs them, usually in memory.
The database is usually the slowest, most expensive part of the stack. In this lesson we assume an indexed database read takes about 50 ms end to end, and each one spends database CPU and network. A cache read is an in-memory hash lookup - about 1 ms including the network hop to a cache server such as Redis. Those two figures are working assumptions; real systems vary, but the order-of-magnitude gap is what matters.
| Storage | Typical read (assumed) | Relative cost |
|---|---|---|
| In-memory cache (Redis) | ~1 ms | 1× |
| Database (indexed read) | ~10–100 ms | 10–100× |
| Disk scan / cold query | seconds | 1,000×+ |
If 90% of reads hit the cache, the database only sees 10% of the traffic. That one number lets a single database absorb a system ten times its size.
Check yourself
A cache's two main benefits are…
Sizing a cache: numbers first
Before choosing a strategy, state what the cache must achieve. Take a profile service as the running example. These are assumptions, not facts about any real product: 30,000 profile reads per second at peak, 50 million profiles, about 1 KB per profile, and a database that stays comfortable at 3,000 reads per second.
Next, how much memory buys that hit rate? Popularity is skewed: a small share of profiles gets most of the views. The working set is the hot part you actually need to hold. The table assumes a skewed curve (hottest 10% of profiles gets 80% of reads, 20% gets 90%, 30% gets 95%). You should measure your own curve before trusting any of it.
| Cache holds | Profiles | Raw size at 1 KB | Assumed hit rate | DB reads/s at 30,000 |
|---|---|---|---|---|
| Hottest 10% | 5 million | 5 GB | 80% | 6,000 |
| Hottest 20% | 10 million | 10 GB | 90% | 3,000 |
| Hottest 30% | 15 million | 15 GB | 95% | 1,500 |
Memory is finite, so a full cache must decide what to throw away. That rule is the eviction policy. Least recently used (LRU) drops the key untouched the longest; least frequently used (LFU) drops the key requested the fewest times; a time to live (TTL) expires a key after a fixed time regardless of use. Redis lets you set a memory limit and a policy; its documentation suggests allkeys-lru as a good default when you have no reason to prefer another.
Check yourself
Peak traffic is 40,000 reads/s and the database is safe at 2,000 reads/s. What hit rate do you need?
The read path: cache-aside
The most common pattern is cache-aside, also called lazy loading. The application, not the cache, is in charge. It looks in the cache first, and only on a miss does it go to the database and then store the answer for next time.
01Check the cache
The app asks the cache for the key. If present, return it - that is a hit.
02On a miss, read the database
The key is not in the cache, so the app reads it from the database, the source of truth.
03Fill the cache
Write the value back into the cache with a time to live (TTL) so the next request hits.
04Return the value
Serve the freshly loaded value to the caller. The refill cost is paid once.
async function get(key) { const cached = await cache.get(key); if (cached !== null) return cached; // hit: O(1) const value = await db.read(key); // miss: source of truth await cache.set(key, value, { ttl: 300 }); // fill for the next 5 min return value;}Click a node to inspect it.
cache-aside is popular because the cache can fail without taking the system down: if Redis is unreachable, the app can still read the database, only slower. The cost is that every code path that reads data must remember to use the helper, and two concurrent misses on the same key both go to the database.
Check yourself
What happens on a cache miss?
Four ways to handle writes
Reads are the easy half. Writes are where caching gets hard, because you must keep two copies of the truth from drifting apart. Four strategies trade write latency against the risk of stale or lost data.
Which write pattern matches your risk tolerance?
Cache-aside
writes go only to the DB; the cache entry is deleted (or left to expire). Simple, but a brief window serves stale data.
Write-through
write the cache and DB together. Always consistent, but every write pays for two stores.
Write-behind
write the cache, flush to DB asynchronously. Blazing for bursts, but a crash can lose the buffered writes.
Refresh-ahead
predict expiry and preload before the key dies. Great for predictable hot keys, more machinery.
write-behind has a useful side effect: coalescing. Suppose 10,000 writes per second land on only 1,000 distinct hot keys (an assumption, for example live counters). If the buffer flushes once per second and keeps only the latest value per key, the database receives at most 1,000 writes per second - a tenfold reduction. The price is that a crash can lose up to one second of buffered writes, about 10,000 updates at that rate.
Check yourself
Which strategy writes cache and DB together?
Staleness versus loss
Every write strategy gives up something. Two failure kinds matter. Stale means a reader sees an older value than the truth. Lost means a write was acknowledged but never reached the database. Stale is usually fixable by waiting; lost is permanent.
| Strategy | Primary risk | Good when |
|---|---|---|
| cache-aside | Serving stale data | Read-heavy, staleness tolerable |
| write-through | Slower writes | Writes must never be lost |
| write-behind | Losing data on crash | Write bursts, loss tolerable |
| Refresh-ahead | Over-fetching | Predictable hot keys |
Match the choice to the data. A shop that can show a stale price for a minute is different from a bank that cannot lose a single transfer. Page-view counters can tolerate losing a second of writes; an order confirmation cannot. When in doubt, start with cache-aside and keep the database as the only place that acknowledges a write.
Check yourself
Which data is the best fit for write-behind?
Invalidation: the hardest part
There are only two hard problems in computer science - cache invalidation and naming things. The line is usually credited to Phil Karlton, though no primary source is known. You must decide when a cached value is no longer true, and remove or refresh it before users notice.
TTL
every key carries an expiry. Automatic and safe, but a short TTL reduces your hit rate and a long one serves stale data.
Explicit invalidation
delete the key the moment the data changes. Precise, but easy to forget in one of many code paths.
Versioned keys
bake the version into the key (
user:42:v3). New data is simply a new key - old entries expire naturally and invalidation becomes a non-issue.
Prefer deleting the key on a write rather than setting the new value. A delete is safe to repeat, and the next read refills from the database, which is always right. If two writers race to set the cache, the slower one can overwrite a newer value with an older one and leave it there until the TTL ends.
Even deletes have a race. Suppose a reader misses, reads the old row from the database, and gets paused. A writer then updates the database and deletes the key. The reader wakes and fills the cache with the old row. Now the cache is stale until the TTL expires. This needs a slow reader and a fast writer, so it is rare, which is exactly why a TTL is still your safety net.
| Write order | What can go wrong | How likely |
|---|---|---|
| Update DB, then delete key | A slow reader that read before the commit refills the old value | Rare: reader must be slower than the whole write |
| Delete key, then update DB | Any reader in the gap refills the old value from the not-yet-updated DB | Common: the gap is the entire DB write |
| Update DB, then set cache | Two concurrent writers can set out of order | Possible under concurrent writes |
Check yourself
Which write order has the smaller stale window?
Cache stampede and hot keys
Two classic failures, both caused by too much traffic on too few keys. A stampede (also called a thundering herd) is many requests missing the same expired key at once and all hitting the database. A hot key is one key (a celebrity, a viral item) that is just too popular for a single server.
A second stampede cause is aligned expiry. If one million keys are loaded together with a 300-second TTL, they all die together. Adding TTL jitter of plus or minus 10% spreads the expiry across 60 seconds (270 to 330 s), which is about 1,000,000 ÷ 60 ≈ 16,700 expiries per second instead of one million at once.
Drag the sliders: watch how a short TTL at high traffic collapses the hit rate and pushes load back onto the database.
Request coalescing
the first miss takes a lock and refills; the others wait for that result. One database read instead of hundreds.
Leases
a variant where the cache hands out a token to one client allowed to refill. Facebook's paper on scaling memcached describes leases that address both stale sets and thundering herds.
Stale-while-revalidate
serve the old value while one request refreshes it, so users never wait. HTTP defines a header form of this idea in RFC 5861.
Hot-key replication
copy the key to several nodes, or keep a local in-process copy with a 1-5 second TTL so most requests never leave the app server.
Cache hit rate
100.0%
DB load
0/s
One hot key, Poisson arrivals: a longer TTL absorbs more requests before the next database read.
Check yourself
One million keys were loaded at once with a 300 s TTL, and the database spikes every 5 minutes. The best fix is…
Caching is a stack, not a box
Production systems cache at every layer, each trading freshness for proximity. Draw the stack from the user inward and assign a TTL to each layer. A content delivery network (CDN) is a set of edge servers near users that cache responses.
- 01
Browser cache - a user's own page and assets; ~0 ms.
- 02
CDN edge cache
- static assets and cacheable APIs, near the user; ~10 ms (assumed).
- 03
App-local L1 cache - hot values in the app process; ~0.1 ms.
- 04
Redis L2 cache - shared in-memory store; ~1 ms.
- 05
Database - source of truth; ~10–100 ms.
A layered stack multiplies hit rates. If the L1 cache catches 50% of reads and Redis catches 90% of the REST, the database sees 0.5 × 0.1 = 5% of reads, the same as one cache with a 95% hit rate. The catch is that every layer adds its own staleness, so the worst case is the sum of the TTLs: an L1 TTL of 5 s over a Redis TTL of 60 s can serve data up to about 65 s old.
Check yourself
An L1 cache with a 5 s TTL sits in front of Redis with a 60 s TTL. The worst-case age of data served is about…
What breaks, and how you survive it
| Failure | Impact | Defense |
|---|---|---|
| Cache node dies | With 10 nodes and even load, 10% of keys miss: +2,700 DB reads/s on top of 3,000 | Replicas, consistent hashing so only a slice moves, rate limits and request coalescing in front of the database |
| Whole cache cluster down | Every read goes to the database: 30,000 reads/s against a 3,000 limit | Load shedding, serve degraded data, per-request circuit breaker, pre-warmed standby |
| Stampede on a hot key | Hundreds of identical DB reads | Coalescing, leases, stale-while-revalidate, TTL jitter |
| Stale value after a write | Users see old data until the TTL | Delete on write, short TTLs on volatile data, versioned keys |
| write-behind buffer lost | Acknowledged writes never reach the DB | Persist the buffer, replicate it, or avoid write-behind for critical data |
| Cold cache after deploy | hit rate near 0 and a DB spike | Warm the cache before shifting traffic; ramp traffic slowly |
| Cache poisoning with a bad value | Wrong data served to many users | Validate before set, short TTLs, a fast purge path |
Check yourself
Your cache cluster restarts empty at peak. What protects the database most directly?
How to run this in an interview
01Clarify (3 min)
Ask what data is cached, how stale it may be, read and write rates, and whether lost writes are acceptable. State assumptions as numbers.
02Size it (5 min)
Derive the hit rate the database needs, then the working set and memory. Show the arithmetic out loud.
03Read path (7 min)
Draw client, app, cache and database. Explain cache-aside, the TTL and what a miss costs.
04Write path (8 min)
Compare the four strategies. Choose one for the data and name the risk you accept: staleness or loss.
05Invalidation (5 min)
Delete on write, TTL as a safety net, and the slow-reader race. Mention versioned keys.
06Failure modes (7 min)
Stampede, hot key, cold cache and node loss. Give a defense for each.
Recap
A cache serves hot data from memory; a hit avoids the database entirely.
Size first: the database limit divided by peak traffic tells you the hit rate; the working set tells you the memory.
cache-aside reads the cache first, and on a miss fills it from the DB.
Write strategies trade latency against the risk of stale (cache-aside) or lost (write-behind) data.
invalidation = TTL, explicit delete after the database commit, or versioned keys.
Cache stampedes and hot keys are the two failure modes; coalescing, jitter, and replication fix them.
Cache at every layer - browser, CDN, L1, L2 - and remember worst-case staleness is the sum of the TTLs.
Terms in this lesson
Every acronym and concept, expanded. Tap a term to open it.
consistent hashing
Mapping keys and servers onto the same ring so adding or removing a server only moves the keys in its arc.
cache stampede
Many requests miss the same expired key at once and all hit the database together, potentially taking it down.
latency
The time a single request takes from start to finish.
stack
A last-in-first-out structure: you push on top and pop from the top.
RESTRepresentational State Transfer
An API style built on plain HTTP verbs (GET, POST, PUT, DELETE) where each URL names a resource.
CDNContent Delivery Network
A network of edge servers scattered around the world that cache static files close to users so requests travel a short distance.
TTLTime To Live
How long a cached value is allowed to be served before it is considered stale and refreshed.
LRULeast Recently Used
A cache eviction policy that drops the item nobody has read for the longest time - the classic 'use it or lose it' rule.
LFULeast Frequently Used
A cache eviction policy that drops the item with the fewest total reads, regardless of when they happened.
QPSQueries Per Second
How many requests a system must answer every second - the basic unit of load.
p99
The latency 99% of requests are faster than; it exposes the slow tail that averages hide.
cache hit
The requested key is in the cache, so the database is not touched.
cache miss
The key is not in the cache, so the database must be read and the cache filled.
cache-aside
The app reads the cache, and on a miss reads the database and writes the value back itself.
write-through
Every write updates the cache and the database together, keeping them in sync at the cost of write latency.
write-behind
Writes go to the cache first and are flushed to the database later - fast, but a crash can lose buffered writes.
eviction policy
The rule for which key to drop when the cache is full - LRU, LFU, or TTL expiry.
hit rate
The fraction of requests served from the cache - the single most important cache metric.
stale-while-revalidate
Serve the old value while one request refreshes it in the background, hiding the refill latency.
invalidation
Removing or replacing a cached value because the data behind it changed.
request coalescing
Letting one request fetch a missing key while identical concurrent requests wait for that single result.
TTL jitter
Adding a small random amount to each key's time to live so keys do not all expire at the same instant.
negative caching
Caching the fact that something does not exist, briefly, so repeated lookups for it skip the database.
RFCRequest for Comments
A numbered document published by the Internet standards community; RFC 5861 defines the stale-while-revalidate HTTP header.
working set
The portion of the data that is actually requested during a period of time - the part worth keeping in cache.
Where you will see it
Real systems that use this exact idea. Tap a card to open it.
Common traps
The mistakes interviewers watch for. Guess the fix, then reveal it.
FixEvery cached value is a staleness liability and a memory cost. Cache the hot working set that serves most of the traffic - measure first.
FixUniform TTLs align expiries into stampedes. Jitter TTLs and tier them by data volatility.
FixAn unbounded cache exhausts its host's memory. Set a memory limit with an eviction policy such as allkeys-lru from day one.
FixA reader in the gap refills the old value. Update the database first, then delete the key, and keep a TTL as a safety net.
FixAverages hide the tail. Report the hit rate and p99 latency, and watch DB load when the cache is cold.
Interview prep
Questions you could be asked, with the depth an interviewer wants to hear.
Cache-aside has the app check the cache and fill it on a miss; writes go to the database and delete the key. Write-through writes cache and database together. Write-behind writes the cache and flushes to the database asynchronously.
staleness vs latency
Real worldCache-aside is the most common pattern because the app stays in control; Facebook's published memcached design is look-aside in this sense.
DeeperEach trades staleness risk against write latency or loss risk - know which you are accepting.