TheScalableDev
System DesignIntermediate30 minhit O(1) · miss O(1) + DB readFree

System Design - Caching

Status

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.
01

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.

StorageTypical read (assumed)Relative cost
In-memory cache (Redis)~1 ms1×
Database (indexed read)~10–100 ms10–100×
Disk scan / cold queryseconds1,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…

02

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.

needed miss rate = 3,000 ÷ 30,000 = 10% → needed hit rate = 90%
The database limit and the traffic together dictate the hit rate you must reach.

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 holdsProfilesRaw size at 1 KBAssumed hit rateDB reads/s at 30,000
Hottest 10%5 million5 GB80%6,000
Hottest 20%10 million10 GB90%3,000
Hottest 30%15 million15 GB95%1,500
10 M profiles × 1 KB = 10 GB · add ~30% overhead for keys and bookkeeping (assumed) → about 13 GB
The 20% row meets the 3,000 reads/s target. Round up and spread the memory over several nodes.

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?

03

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.

  1. 01Check the cache

    The app asks the cache for the key. If present, return it - that is a hit.

  2. 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.

  3. 03Fill the cache

    Write the value back into the cache with a time to live (TTL) so the next request hits.

  4. 04Return the value

    Serve the freshly loaded value to the caller. The refill cost is paid once.

Cache-aside in a function.
1async function get(key) {
2 const cached = await cache.get(key);
3 if (cached !== null) return cached; // hit: O(1)
4
5 const value = await db.read(key); // miss: source of truth
6 await cache.set(key, value, { ttl: 300 }); // fill for the next 5 min
7 return value;
8}
90% hit rate · 1,000 queries per second (QPS) → 900 served from cache, 100 reach the DB
The one number that decides whether the database survives.
requestlookupmissfillClientApp ServiceCacheDatabase

Click a node to inspect it.

Cache-aside: the app drives lookup and fill.

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?

04

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.

How writes flow
Risk
Best when
Cache-aside
Write DB, delete cache key
Brief stale window
Read-heavy data
Write-through
Write cache and DB together
Slower writes
Critical writes
Write-behind
Write cache, flush later
Loss on crash
Write bursts
Refresh-ahead
Prefetch before expiry
Wasted refreshes
Predictable hot keys

Which write pattern matches your risk tolerance?

Write strategies compared.
  • 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.

10,000 writes/s ÷ 1,000 distinct keys = 10 writes per key per flush → DB sees 1,000 writes/s (10× fewer)
Coalescing is the real benefit of write-behind; the risk is the unflushed buffer.

Check yourself

Which strategy writes cache and DB together?

05

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.

StrategyPrimary riskGood when
cache-asideServing stale dataRead-heavy, staleness tolerable
write-throughSlower writesWrites must never be lost
write-behindLosing data on crashWrite bursts, loss tolerable
Refresh-aheadOver-fetchingPredictable 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?

06

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 orderWhat can go wrongHow likely
Update DB, then delete keyA slow reader that read before the commit refills the old valueRare: reader must be slower than the whole write
Delete key, then update DBAny reader in the gap refills the old value from the not-yet-updated DBCommon: the gap is the entire DB write
Update DB, then set cacheTwo concurrent writers can set out of orderPossible under concurrent writes

Check yourself

Which write order has the smaller stale window?

07

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.

5,000 reads/s on one key · refill takes 50 ms → 5,000 × 0.05 = 250 requests miss before the first refill lands
Without protection, 250 identical database reads run for one row. With request coalescing, 1 does.

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…

08

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.

  1. 01

    Browser cache - a user's own page and assets; ~0 ms.

  2. 02

    CDN edge cache

    - static assets and cacheable APIs, near the user; ~10 ms (assumed).

  3. 03

    App-local L1 cache - hot values in the app process; ~0.1 ms.

  4. 04

    Redis L2 cache - shared in-memory store; ~1 ms.

  5. 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…

09

What breaks, and how you survive it

FailureImpactDefense
Cache node diesWith 10 nodes and even load, 10% of keys miss: +2,700 DB reads/s on top of 3,000Replicas, consistent hashing so only a slice moves, rate limits and request coalescing in front of the database
Whole cache cluster downEvery read goes to the database: 30,000 reads/s against a 3,000 limitLoad shedding, serve degraded data, per-request circuit breaker, pre-warmed standby
Stampede on a hot keyHundreds of identical DB readsCoalescing, leases, stale-while-revalidate, TTL jitter
Stale value after a writeUsers see old data until the TTLDelete on write, short TTLs on volatile data, versioned keys
write-behind buffer lostAcknowledged writes never reach the DBPersist the buffer, replicate it, or avoid write-behind for critical data
Cold cache after deployhit rate near 0 and a DB spikeWarm the cache before shifting traffic; ramp traffic slowly
Cache poisoning with a bad valueWrong data served to many usersValidate before set, short TTLs, a fast purge path

Check yourself

Your cache cluster restarts empty at peak. What protects the database most directly?

10

How to run this in an interview

  1. 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.

  2. 02Size it (5 min)

    Derive the hit rate the database needs, then the working set and memory. Show the arithmetic out loud.

  3. 03Read path (7 min)

    Draw client, app, cache and database. Explain cache-aside, the TTL and what a miss costs.

  4. 04Write path (8 min)

    Compare the four strategies. Choose one for the data and name the risk you accept: staleness or loss.

  5. 05Invalidation (5 min)

    Delete on write, TTL as a safety net, and the slow-reader race. Mention versioned keys.

  6. 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.

  1. FixEvery cached value is a staleness liability and a memory cost. Cache the hot working set that serves most of the traffic - measure first.

  2. FixUniform TTLs align expiries into stampedes. Jitter TTLs and tier them by data volatility.

  3. FixAn unbounded cache exhausts its host's memory. Set a memory limit with an eviction policy such as allkeys-lru from day one.

  4. 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.

  5. 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.