A cache keeps a copy of data somewhere faster than where it really lives. Reading a value from memory takes a fraction of a millisecond. Asking a database can take tens of milliseconds and uses up capacity the database needs for writes.
The hard parts are all about the copy: when to make it, when to throw it away, what to keep when you run out of room, and what happens when the real data changes and the copy does not. This page shows each one happening, then the fix.
In the labs after the walkthrough, every chip is a single read in a simulation running in your browser, and the letter is the key it asks for. The most popular keys are coloured; the long tail is grey. Each slot in the cache shows which key it holds and that copy’s version. The database on the right shows its workers and the line of queries waiting for one.
00 The life of one cached key
Before the live labs, follow one key from its first read to the day it is evicted. Step through at your own pace, or press Play all.
Step 1 of 10
Meet the pieces
The app server runs your code and needs data. The cache keeps copies of a few rows in memory, where reading is fast. The database holds every row and is the source of truth, but each query is slower.
01 Why cache: speed and load
A cache helps in two ways. Reads that find their key in the cache (a hit) are answered fast. And every hit is a query the database does not have to run, so the database has room for the reads that do reach it (the misses) and for writes.
The second effect is often the one that matters. A database that can serve a few thousand reads a second can sit behind a cache that answers a hundred thousand, as long as the hit rate is high.
- Hit rate
- 0%
- Average read
- 0 ms
- Database reads/s
- 0.0
- Waiting at database
- 0
Click any read to follow it.
Hit rate is the number to watch, and the top of the range matters most. At 99% hits, 1 read in 100 reaches the database. At 98%, it is 2 in 100: a one-point drop doubles the database load. Real traffic is usually skewed, a few keys get most reads, which is why a cache much smaller than the data can still catch most reads.
A cache is a capacity tool as much as a speed tool. Size it for the hit rate you need, and plan for what the database sees when the hit rate drops.
02 The read path: cache-aside
The most common pattern is cache-aside, also called lazy loading. The application, not the cache, does the work:
- Look for the key in the cache. If it is there, use it. That is a hit.
- If not, that is a miss: query the database.
- Store the answer in the cache, so the next read hits.
The cache only ever holds keys someone asked for, and a cache that is down or empty only makes reads slower, not wrong. The cost is that every key’s first read is slow, and the cache needs a way to learn that data changed (sections 03 and 04).
- Hit rate
- 0%
- Average read
- 0 ms
- Database reads/s
- 0.0
Click any read to follow it.
Cache-aside: read the cache, on a miss read the database and fill the cache. Simple, and the default unless you have a reason to pick something else.
03 The write paths
When data changes, the database gets the new value. The question is what happens to the copy in the cache. Three common answers:
- Write, then delete (invalidate). Save to the database, then delete the key from the cache. The next read misses and loads the new value. Simple and safe, at the cost of one extra miss per write.
- Write-through. Save to the database, then put the new value in the cache. The next read hits. Writes take a little longer, and you may cache values nobody reads.
- Write-behind (write-back). Put the new value in the cache and answer at once. The cache saves it to the database later, often in batches. Writes are fast, but if the cache dies before it saves, the write is gone.
- Hit rate
- 0%
- Average write
- —
- Stale reads
- 0
- Lost writes
- 0
Click any read to follow it.
- Warm-up: a job loaded 4 keys into the cache at once.
Invalidate on write is the safe default. Use write-through when reads right after a write must hit, and write-behind only for data you can afford to lose or rebuild, like counters and view counts.
04 TTL and stale data
Sometimes the cache is not told about a change. Another service wrote to the database, a job ran a bulk update, or the code that deletes keys has a bug. The cache then serves the old value, a stale read, for as long as it keeps that copy.
A time to live (TTL) puts a limit on that. Each entry expires a fixed time after it was stored, so even a copy nobody invalidates is replaced eventually. The TTL is your answer to “how old may this data be?”
- Stale reads
- 0
- Old values cached
- 0
- Hit rate
- 0%
- Database reads/s
- 0.0
Click any read to follow it.
- Warm-up: a job loaded 4 keys into the cache at once.
Short TTLs mean fresher data and more database load; long TTLs the reverse. Invalidate on write for correctness, and keep a TTL anyway as a safety net for the writes you did not know about.
05 Eviction: what to drop when full
A cache has a fixed amount of memory. When it is full and a new key arrives, something must go. The eviction policy picks the victim:
- LRU (least recently used) drops the key that has gone longest without a read. It adapts quickly when popularity changes, but a one-off scan of many cold keys can push out every hot key.
- LFU (least frequently used) drops the key with the fewest reads. It holds on to steady favourites and shrugs off scans, but a key that used to be popular can sit there long after everyone stopped reading it.
- FIFO (first in, first out) drops the oldest entry, however popular. Cheap to run, and usually the worst hit rate.
- Hit rate
- 0%
- Evictions
- 0
- Database reads/s
- 0.0
Click any read to follow it.
LRU is the usual default. Real caches blend recency and frequency, and LFU in practice decays its counts over time, to get the best of both.
06 Cold starts and keys that expire together
An empty cache, after a restart, a deploy or a new node, misses on everything. The database suddenly gets all the reads the cache used to absorb, often far more than it was sized for. A team that runs at a 95% hit rate has built a database for 5% of the traffic.
A common fix is to warm the cache: a job loads the popular keys before traffic arrives. That brings its own trap. Keys stored at the same moment with the same TTL also expire at the same moment, and the database gets a wave of misses every TTL. Adding a little randomness to each TTL, jitter, spreads the expiries out.
- Hit rate
- 0%
- Waiting at database
- 0
- Database reads/s
- 0.0
- Expired
- 0
Click any read to follow it.
- Warm-up: a job loaded 12 keys into the cache at once.
Never assume the cache is warm. Know what your database sees at a 0% hit rate, warm caches gradually, and add jitter to TTLs that are set in bulk.
07 The stampede on a hot key
When one very popular key expires, every read in the next few hundred milliseconds misses. Each of those readers asks the database for the same row, and each one stores the same answer. This is a cache stampede (or thundering herd). For a key read thousands of times a second, it can be thousands of identical queries at once.
Fixes, from simplest:
- Coalesce loads. Only the first miss queries the database. Others for the same key wait for that one answer. This is a per-key lock, or Go’s singleflight, or request collapsing in a CDN.
- Refresh early. When a key is read close to its expiry, reload it in the background while the old value is still served. Popular keys never actually expire. The XFetch approach makes the timing random, so servers do not all refresh at once.
- Serve stale while revalidating. Keep serving the expired value for a short grace period while one request refreshes it. HTTP caches support this with
stale-while-revalidate.
- Misses on A
- 0
- Extra loads of A
- 0
- Waiting at database
- 0
- Hit rate
- 0%
Click any read to follow it.
Any key that is read far more often than it is reloaded needs stampede protection. Coalescing is the minimum; early refresh avoids the miss entirely.
08 Invalidation races
“Write the database, delete the key” looks simple, but the writer and the readers run at the same time and their steps can interleave badly. Two classic cases:
- Delete, then write. The writer deletes the key, then starts its database write. A reader misses in that gap, reads the old value from the database, and puts it back in the cache. The write lands, but the cache now holds the old value until its TTL ends, or forever if there is none.
- Write, then delete, with a slow reader. A reader misses and reads the old value. Before it stores it, perhaps paused by garbage collection, the writer writes and deletes. Then the reader stores the old value. Rare, because the reader must miss and be slow at just the wrong time, but at scale rare things happen daily.
Facebook’s memcache paper describes the fix for the second case: leases. A miss hands the reader a token, a delete cancels outstanding tokens, and a store with a cancelled token is refused. Versioned values (store only if newer) work the same way.
- Old values cached
- 0
- Stale reads
- 0
- Stores refused
- 0
Click any read to follow it.
- Warm-up: a job loaded 3 keys into the cache at once.
Write the database first, then delete the key. Add leases or version checks if stale data is costly, and always keep a TTL so that any mistake heals itself.
09 Where caches live
A request can pass several caches before it reaches the database, each nearer the user than the last:
- Browser. The user’s own device keeps responses, as the server’s
Cache-Controlheader allows. Free and instant, but only for that one user, and you cannot delete it from the server. - CDN. Servers near users cache public responses such as images, scripts and pages that look the same for everyone. They cut the long trip to your servers. Most CDNs let you purge a URL, but it takes time to reach every location.
- App memory. A map inside each server process. The fastest cache you control, but each server has its own copy, so servers can disagree and each one warms up on its own.
- Shared cache such as Redis or Memcached. One network hop away and shared by every server, so one delete reaches everyone.
- From browser
- —
- From CDN
- —
- From app memory
- —
- From Redis
- —
- From database
- —
- Stale answers
- 0
Click any request to follow it through the layers.
The nearer a cache is to the user, the faster it is and the harder it is to invalidate. Cache public, slow-changing data near the edge and user-specific or fast-changing data in a shared cache you can delete from.
10 Choosing a cache
A rough map of the common choices:
| Cache | What it is | Eviction | Shared | Good for |
|---|---|---|---|---|
| Redis / Valkey | In-memory server with data structures (strings, hashes, sorted sets, streams), TTL per key, optional persistence and replication | Configurable: approximate LRU or LFU, over all keys or only keys with a TTL, or none | Yes | The default shared cache; also counters, rate limits, leaderboards, sessions |
| Memcached | Simple multi-threaded key-value store, no persistence; clients spread keys across servers | LRU (segmented) | Yes | Large, plain key-value caches with very simple operations |
| In-process caches | A map in your process: Caffeine (Java), an LRU cache library in Node or Python | LRU, or a mix such as W-TinyLFU in Caffeine | No, one per server | Very hot, small, slow-changing data; config, feature flags |
| CDN caches | Cloudflare, Fastly, CloudFront, Akamai and others cache HTTP responses at the edge | Provider-managed, guided by Cache-Control | Per location | Static files, images, public pages and API responses |
Check the current docs before you choose: features, limits and licences change. Redis changed its licence in 2024, and Valkey is a community fork that started from the last open-source release.
11 Check yourself
Your cache hit rate drops from 95% to 90%. Roughly what happens to the number of reads reaching the database?
You update a product price in the database and delete its cache key. Which order is safer?
One very popular key expires and the database briefly falls over. What is this, and what is a fix?
A nightly report reads every row once. Next morning the cache hit rate is terrible. Which eviction policy made this worse?
You cache user profiles in each app server’s memory for 5 minutes and in Redis. A user changes their name and you delete it from Redis. What do they see?