Want the details?
Two problems every cache has
A cache keeps a copy so most reads skip the slow database. Two things go wrong. A stampede (also called a thundering herd or dog-pile): a very popular copy expires, and in that moment hundreds of requests miss together and all ask the database. And stale data: the database changes, but the cache keeps giving the old copy until it expires.
How to read the bench
| Part on the bench | What it means in a real system |
|---|---|
| Readers | Users or servers asking for one popular item. |
| Price card on the cache | The cached copy. Red: older than the database. |
| Row of cells | Time left until the copy expires (its TTL). |
| Balls at the database | Queries running; the dial counts them. |
| Red balls to the readers | Answers with an old price. |
The numbers
- 20 reads a second, a 5-second copy, a 0.8-second query; the database slows down above 6 queries at once.
- In 20 seconds: every reader asks, 50 queries and up to 17 at once; one fetch, 4 queries; refresh early, 5 queries and no waiting after the first load.
- Price change at 6 s with the cache left alone: 97 old answers; with delete on write: none.
In real systems
- Single flight: in one process, keep a map of fetches in flight; across many servers, take a short lock in Redis (
SET key NX PX 3000) and let others wait or serve the old copy. - Early refresh: refresh before expiry, with some randomness (“probabilistic early expiration”), so thousands of keys do not expire in the same second. Add jitter to TTLs for the same reason.
- Serve stale while revalidating: CDNs and browsers can give the old copy and refresh it in the background (the HTTP header
stale-while-revalidate). - Write strategies: cache-aside (the app reads the cache, falls back to the database, and deletes the copy on writes) is the most common. Write-through writes the cache and the database together. Write-back writes only the cache and saves to the database later: fast, but a crash can lose writes.
- Delete, don't set: on a write, delete the copy rather than writing the new value into it. Two writes racing can leave the older value in the cache for a whole TTL.
Words to know
- TTL
- Time to live: how long a copy may be used.
- Cache Stampede
- Many requests missing the same expired key at once and all hitting the database.
- Single Flight
- Only one request fetches a missing key; the others wait for its answer.
- Stale Data
- A cached copy that is older than the source.
- Cache Invalidation
- Removing or updating copies when the source changes.