Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Handbooks  /  Caching Patterns
Handbook~15 min readPerformanceworked math + runnable code
The Caching Patterns Handbook

Keep the answer
close.

The fastest database query is the one you never run. A cache keeps a copy of expensive data somewhere fast, so most requests skip the slow source entirely. But a cache is only as good as its hit rate — the fraction of requests it can actually serve — because average latency is a weighted blend of the quick path and the slow one. Miss too often and the cache is dead weight; hit often and latency collapses. This handbook is the arithmetic of that blend, the patterns that fill the cache, and the two famously hard problems that break it.

01

Hit or miss

A cache sits between your application and a slow source of truth — a database, an external API, a disk — and keeps a copy of recently or frequently used data in a fast store, usually memory. When a request arrives, one of two things happens. Either the data is in the cache, a hit, and you return it in about a millisecond over the network (microseconds if the cache is in-process); or it isn't, a miss, and you pay the full cost of the slow source, then typically store the result so the next request for that key hits.

That's the entire mechanism, and it's a bet: you're wagering that data fetched once will be wanted again soon, so keeping it close pays off. The payoff isn't guaranteed — a cache full of things nobody re-requests is just wasted memory — which is why the fraction of hits, not the raw speed of the cache, is what actually determines whether caching was worth it. The next section makes that precise.

The one-sentence version

Average latency is the hit-rate-weighted blend of the fast path and the slow path — so a cache's whole value rides on one number, the hit rate, and the hard part is keeping that copy correct.

02

Why hit rate is everything

Suppose a fraction h of requests hit the cache and cost t_cache, while the rest miss and cost t_source. The average latency is just the weighted average: h·t_cache + (1−h)·t_source. Because the source is usually far slower than the cache — a millisecond of memory versus a hundred milliseconds of database — the miss term dominates. Almost all of your average latency is the tax you pay on the requests that missed.

That's why hit rate is the metric that matters. Push it from 50% to 90% and you've cut the number of expensive misses fivefold, dragging average latency down toward the cache's speed. Let it slip toward zero and the cache does nothing but add a lookup before every slow fetch. This is also why a small increase in hit rate at the high end is so valuable: going from 95% to 99% cuts the miss traffic — and the load on your source — by five times. The whole discipline of caching is a fight to raise that one number without serving stale data.

03

The patterns

How data gets into and out of the cache defines the pattern, and each trades consistency, write speed, and durability differently:

Reading and writing through a cache
Cache-asideApp checks cache; on miss, loads from source and populates it. Simple, most common; first request per key always misses.
Read-throughLike cache-aside, but the cache library does the loading, not the app.
Write-throughWrites go to cache and source together → consistent, but slower writes.
Write-backWrites hit cache, flush to source later → fast, but risks loss if the cache dies first.

Most systems use cache-aside for reads: it's simple, and the cache only holds what's actually been requested. The write patterns are about keeping the copy honest — write-through pays latency for consistency, write-back pays a durability risk for speed. There's no universally right answer; you pick based on whether stale reads or slow writes or lost writes hurt your workload the most. And underneath all of them sits an eviction policy — usually LRU, evict the least-recently-used — because the cache is finite and something has to leave when it fills.

04

The latency math

The average request latency is the hit-rate-weighted blend of the two paths, and it's dominated by the miss term because the source is slow:

hit rate  h =  hits / total     avg latency  =  h·tcache + (1−h)·tsource

h=0.9, t_cache=1 ms, t_source=100 ms → 0.9·1 + 0.1·100 = 10.9 ms. At h=0 it's the full 100 ms; the cache earns its keep entirely through h.

Rearranging tells you the hit rate you'd need to meet a latency target, and the speedup over always hitting the source:

speedup  =  tsource / avg     h ≥ (tsource − target) / (tsource − tcache)  to hit the target

To get avg ≤ 20 ms with those numbers you need h ≥ (100−20)/(100−1) = 80/99 ≈ 0.81. The runnable version below computes hit rate, effective latency, speedup, and the required hit rate.

RUN IT YOURSELF

Hit rate decides everything

A cache's average latency is a weighted blend of two paths: a fraction h of requests hit the fast cache, and the rest miss and pay the slow source. Because the source dominates, the average is mostly the miss term (1−h)·t_source — so raising the hit rate collapses latency toward the fast path, and a low hit rate makes the cache almost worthless. You can also invert it: to meet a latency target you need a minimum hit rate. Change the hit rate or the two path latencies and watch the average, the speedup, and the required hit rate move.

CPython · WebAssembly
05

The two hard problems

There's an old joke: there are only two hard things in computer science — cache invalidation and naming things. The first is real and it's the deep problem of caching. A cache holds a copy, and the moment the source changes, that copy is stale — serving old data until it expires or is explicitly removed. You manage staleness with a TTL (time-to-live: expire the entry after N seconds) and with explicit invalidation on writes (delete or update the cached key when the source changes). Both are trade-offs: a short TTL keeps data fresh but lowers hit rate; a long TTL is fast but risks serving stale answers. There's no free lunch — you're always choosing where on the freshness-versus-hit-rate curve to sit.

The second classic is the cache stampede (thundering herd). A single popular key expires, and in that instant every in-flight request for it misses at once — and all of them hit the slow source simultaneously, potentially overwhelming the very database the cache was protecting. The fixes are about coordination: a lock so only one request refills while others wait, request coalescing so duplicate misses share one fetch, or early/staggered expiry so hot keys refresh before they expire and never all fall due at once. Both problems come from the same root — a cache is a copy that can be wrong or can vanish — and handling them is what separates a cache that speeds things up from one that occasionally takes the whole system down.

06

Pitfalls

The first mistake is caching without measuring the hit rate. A cache with a 10% hit rate is adding a lookup before nearly every slow fetch — negative value — and you won't know unless you instrument hits and misses. The second is caching things that change constantly: if a key is written as often as it's read, the cache is stale most of the time and you pay invalidation cost for almost no benefit. Cache what's read far more than written.

Two more. Unbounded caches: memory is finite, so a cache with no eviction policy and no size limit eventually consumes all of it and crashes the process — always set a max size and an eviction policy (LRU is the sane default). And the cold-start / first-request miss: cache-aside means the very first request for any key is always a miss, so a freshly deployed or restarted cache has a 0% hit rate and offers no protection exactly when a cold system is most fragile — warm critical caches ahead of traffic if you can. Get the hit rate high, the invalidation honest, and the size bounded, and a cache turns a slow, overloaded system into a fast, calm one. The whole handbook is one sentence: latency is the blend, hit rate is the dial, and the copy must stay correct.

Worth knowing

Instrument the hit rate — it's the number that decides everything. Cache read-heavy data, bound the size with an eviction policy, manage staleness with TTL + invalidation, and defend hot keys against stampedes. A cache you don't measure is as likely to hurt as help.

By the numbers

Worked example: a product-page cache under load

Use the page’s numbers, 1 ms for the cache and 100 ms for the database, and add a load: say 2,000 requests/s, against a database that is comfortable at about 400 queries/s. Trace what each hit rate does to latency and to the database.

StepSituationArithmeticResult
1No cache2,000 × 1.0 misses2,000 queries/s, 5× what the DB can take; 100 ms average
2h = 0.800.8 × 1 + 0.2 × 100; 2,000 × 0.220.8 ms; 400 queries/s, exactly at the limit
3h = 0.950.95 × 1 + 0.05 × 100; 2,000 × 0.055.95 ms; 100 queries/s
4h = 0.990.99 × 1 + 0.01 × 100; 2,000 × 0.011.99 ms; 20 queries/s; 50× faster than no cache
5One hot key at 300 req/s, TTL 60 s1 expiry miss per 300 × 60 requests1 miss in 18,000: a 99.994% hit rate on that key
6That key expires, refill takes 100 ms, no coalescing300 req/s × 0.1 s30 identical queries hit the DB at once
7Same, with a refill lock or coalescingone fetch; the others wait for it1 query
8Cache restarts emptyh falls to 0back to step 1: 2,000 queries/s until it warms

Step 2 is the line that matters for capacity. At 80% the latency looks fine, yet the database is at its limit, so a dip of a few points in hit rate overloads it. That is why you size the database for the miss traffic, not for the average. Steps 5 and 6 show the stampede is not a hit-rate problem: the key’s hit rate is near perfect, and the damage happens in a 100 ms window once a minute. Step 8 is the cold-start pitfall in numbers. A restart puts the whole load on a database that was sized for one fifth of it.

Trade-offs

Cost and trade-offs: the patterns side by side

Time is the latency on the read and write paths. Space is the memory or durability cost. Why is what you are trading.

CaseTimeSpaceWhy
Cache-asideHit: one cache round trip. Miss: cache + source + a setOnly keys that were readSimple, and the app owns it. A slow reader can write an old value back after a newer write deleted it, so pair it with a TTL.
Read-throughSame as cache-asideSameOne loading path in the cache library instead of in every caller. The library must handle errors and timeouts from the source.
Write-throughWrite: source + cache, both on the request pathCaches every written key, read or notReads see fresh data. Writes are slower, and write-once data takes up memory.
Write-backWrite: cache only, flushed laterDirty entries exist only in the cache until flushedFastest writes, and repeated writes to a key collapse into one. A crash before the flush loses them.
Write-aroundWrite: source only; the next read missesOnly keys that were readKeeps write-once data, such as logs and uploads, out of the cache, at the cost of one miss per key.
LRU evictionO(1) get and put, with a hash map and a doubly linked listO(capacity), plus two pointers per entryA good default. One full scan of cold keys can push out the whole hot set.
Short vs long TTLShort: more misses. Long: fewerLong TTLs keep more keys residentThe freshness-versus-hit-rate curve from the page. Explicit invalidation on write lets you use a longer TTL safely.

Read patterns decide when data enters the cache. Write patterns decide which copy is the truth between a write and the next read. Most systems combine cache-aside reads with delete-on-write, and a TTL as the safety net for any invalidation that gets missed.

In the wild

Where this shows up in production and interviews

  • Redis or Memcached in front of a database

    The most common setup is the one on this page: cache-aside reads, and on a write you update the database, then delete the key rather than set it. Deleting avoids two concurrent writers leaving the older value in the cache. The next read refills it from the source.

  • HTTP and CDN caching

    Cache-Control: max-age is a TTL set by the server. stale-while-revalidate lets a cache serve the old copy while it refreshes in the background, which is the early-refresh fix for stampedes, applied at the edge. Fingerprinted static files, such as app.3f9a.js, can be cached as immutable because a change gives them a new URL.

  • Memcache at Facebook

    The paper “Scaling Memcache at Facebook” (NSDI 2013) describes leases: on a miss, the cache gives one client a token to refill the key and asks the others to wait briefly. That one mechanism handles both of the page’s hard problems, stale sets and thundering herds.

  • CPU caches and the interview

    Hardware uses the same blend, written as average access time = hit time + miss rate × miss penalty. In a system design interview, state the hit rate you are assuming and the source load it leaves (step 2 above). Then say how you invalidate, what happens when a hot key expires, and how the cache is bounded.

Self-check

Check yourself

Cache 2 ms, database 50 ms, and you need an average of 10 ms. What hit rate do you need?

h ≥ (50 − 10) ÷ (50 − 2) = 40 ÷ 48 ≈ 0.833, so about 83%. Check the database load at that rate too: one request in six still reaches it.

Hit rate improves from 98% to 99%. Latency barely moves. Was it worth it?

For the database, yes. Misses fall from 2% to 1% of traffic, so source load halves. On the page’s numbers average latency drops from 2.98 ms to 1.99 ms, but the halved load is the real gain: it is headroom for a traffic spike or a cold restart.

A key is read 10 times a second and written 10 times a second, alternating, and every write deletes it. What hit rate will it get?

Close to zero. Each read follows a write that just removed the key, so nearly every read misses and refills a value that is about to be deleted. Do not cache this key, or cache it with a short TTL and accept stale reads.

Write-back or write-through: for a page-view counter, and for an order’s payment status?

The view counter can be write-back. Losing a few increments in a crash is acceptable, and collapsing thousands of writes into one flush is a big saving. Payment status must be write-through or written to the database directly. A lost or stale value there is a real bug, not a rounding error.

Frequently asked

Quick answers

What is caching?

Keeping a copy of expensive-to-fetch data somewhere fast, so future requests skip the slow source — a hit is fast, a miss pays full cost.

Why does hit rate matter most?

Average latency is h·t_cache + (1−h)·t_source, dominated by the miss term — so raising the hit rate is what makes a cache worth having.

What are the main patterns?

Cache-aside (load on miss), write-through (write both, consistent), write-back (write cache, flush later, fast but riskier).

What's the hardest part?

Invalidation — a cached copy goes stale when the source changes — and cache stampedes when a hot key expires and everyone misses at once.

▶  Watch it explained

Caching patterns: cache-aside, write-through, write-back (and TTLs)

Finished this one? 0 / 209 Handbooks done
NextDesign a Distributed Cache Next in “System Design in 30 Days” · step 9 of 21

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Handbooks