a system design guide
Caching explained: cache-aside, TTLs and stampedes
By Majid Ali, founder of Bytecrest · · 8-minute read
Short answer
Caching means keeping copies of often-read data in fast memory, so most requests never reach the database. In cache-aside, the app checks the cache first, reads the database only on a miss, then stores the result. Traffic is skewed, so a small cache catches most reads: with 10,000 keys, the top 100 take about 53% of them.
Caching is the cheapest way to take load off a database, and the easiest way to introduce bugs. This guide works through the numbers step by step: what a cache saves, how big it needs to be, and the three ways it bites back. All figures come from the free caching Lesson in ByteLab, a simulator for system design, so you can reproduce each one.
What problem does a cache solve?
A cache solves repeated work. If the same rows are read again and again, the database does the same job over and over. A cache answers the repeats from memory.
Take a product page. 600 reads per second arrive, and the database spends about 10 ms of CPU on each. It has 4 vCPUs.
- Capacity = vCPUs ÷ CPU time per read = 4 ÷ 0.010 s = 400 reads per second.
- Offered load = 600 reads per second, which is 150% of capacity.
- The extra 200 reads every second join a queue and wait. Latency climbs and then requests fail.
The app server is fine here. It is only about 30% busy. The database is the bottleneck, and most of what it is asked is repeated.
How does cache-aside work?
Cache-aside puts the application in charge. The cache is a fast, small store such as Redis. It sits beside the database, not in front of it as a gate. The app follows four steps:
- Ask the cache for the key.
- On a hit, return the value. Done.
- On a miss, read the database.
- Store the answer in the cache, then return it.
A hit costs about 1 ms. A miss costs the cache lookup, plus the database read, plus the write back: about 12 ms in the ByteLab model. So average latency is a blend: hit ratio × 1 ms + miss ratio × 12 ms. At a 76% hit ratio that is 0.76 × 1 + 0.24 × 12 ≈ 3.6 ms. A higher hit ratio lowers latency and database load together.
Why does a small cache catch most reads?
Because real traffic is skewed. A few items get most of the reads. This shape is called a Zipf law: the most popular key gets a share proportional to 1, the second to 1/2, the third to 1/3, and so on.
With an exponent of 1.0 and 10,000 keys, those shares add up to about 9.8. So the single hottest key takes 1 ÷ 9.8, about 10% of reads. The top 100 keys take about 53%. A cache holding just 100 keys already removes half the database load.
Here is what each cache size buys on the 600-reads-per-second example. The database can do 400.
| Cache holds | Hit ratio | Database reads/s | Database busy |
|---|---|---|---|
| 100 keys | 53% | 282 | 70% |
| 500 keys | 69% | 186 | 47% |
| 1,000 keys | 76% | 144 | 36% |
| 2,000 keys | 84% | 96 | 24% |
| 5,000 keys | 93% | 42 | 10% |
Read the 1,000-key row: 24% of 600 reads still miss, so the database sees 144 reads a second, which is 36% of its 400. Nothing about the database changed. These are the ideal figures. A real LRU cache sits a few points lower, because it does not know which keys are truly popular.
Notice the diminishing returns. The first 100 keys bought 53 points. Every doubling after that adds only about 7. So size a cache for the head of the distribution, not the whole dataset. Flatter traffic helps less: with no head, the same cache hits far less.
What do TTL and eviction do?
TTL (time to live) makes every entry expire after a set time, so a changed value cannot be served forever. Eviction decides what to drop when the cache is full. LRU drops the key unused for longest. LFU drops the key used least often.
A short TTL keeps data fresh but lowers the hit ratio, because entries expire before their next reader arrives. A long TTL does the opposite. Freshness and hit ratio pull in opposite directions.
What is a cache stampede?
A stampede is a burst of misses when many hot keys expire together. Every hot key was first loaded in the opening second. With a 5-second TTL, they all expire in the same second.
- The top 100 keys carry 53% of 600 reads: about 318 reads per second.
- For a moment, every one of those is a miss and goes to the database, on top of its normal misses. Its capacity is 400.
- The queue makes each refill slower, so more requests arrive while a key is still empty, and each asks for the same value.
There are two fixes, for two different halves of the problem.
- Coalescing: when many requests miss the same key at once, only the first goes to the database and the rest wait for its answer. Those 318 reads become about 100 queries, one per key.
- TTL jitter: give each entry a TTL of 5 s ± 20%, so keys stop expiring together.
Coalescing shrinks the stampede. Jitter breaks up its timing. Both are cheap and almost always worth turning on.
How does a cache serve stale data?
A write updates the database, but the cached copy lives on until its TTL runs out. Reads in that window return an old value. That is a stale read.
The worst case is easy to estimate: reads per second of that key × TTL. The hottest key takes 10% of 600 reads, so 60 per second. With a 5-second TTL, up to 60 × 5 = 300 stale answers after one write. With a 60-second TTL, up to 3,600.
The fix is to delete the cached key when you write. The next reader refills it from the database. This is exact, but easy to forget on one code path, so keep the TTL as the backstop.
Write-through or write-behind?
So far the cache only handled reads. If writes also go through the cache, there are two common policies.
| Policy | How it works | Trade-off |
|---|---|---|
| Write-through | Every write goes to the cache and the database, and succeeds only when both have it. | Never stale and nothing is lost. Writes are as slow as the database. |
| Write-behind | A write is stored in the cache, acknowledged at once, and flushed to the database later in batches. | Fast writes and fewer database writes. A crash loses what was not yet flushed. |
With write-behind, for a moment the only copy of an acknowledged write sits in the memory of one machine. At 6 writes a second, every second of unflushed buffer is 6 lost writes if the cache crashes, and those users were told they succeeded.
When is a cache not worth it?
A cache is not free capacity. It trades freshness and durability for speed and load. In the ByteLab example, the cache machine costs $0.252 an hour (simulated prices). Doubling the database from 4 to 8 vCPUs costs $0.192 an hour more and also clears the overload at 600 reads a second. At this scale, a bigger database is cheaper.
The cache wins as load grows. At an 84% hit ratio, the database sees 16% of the traffic. A database that can do 400 reads a second can sit behind 400 ÷ 0.16 = 2,500 reads a second of users, and the cache answers in 1 ms instead of 10. Only read-heavy, skewed, tolerably stale data belongs in a cache. A page unique to each user gets almost no hits.
Common mistakes
- Sizing the cache for the whole dataset. The head of the traffic is what matters. Returns shrink fast.
- Giving every key the same TTL. They expire together and cause a stampede. Add jitter.
- Forgetting to invalidate on one write path. Stale data survives until the TTL ends.
- Treating the cache as a safe place for the only copy of data. Memory is lost on a crash.
- Ignoring the cold start. A restarted cache is empty, so the full read load lands on the database at once. Size the database to survive it, or warm the cache first.
- Caching data that is barely re-read. A low hit ratio costs money and adds a failure mode for no gain.
Try it yourself
Reading numbers is one thing. Watching a database drown and then recover is better. The caching Lesson is free and takes about 20 minutes. No sign-up is needed.
Add a cache, watch the hit ratio climb, then break it with a stampede, stale reads and a crash.
Frequently asked questions
What is cache-aside?
Cache-aside is a pattern where the application, not the cache, manages the data. It asks the cache first. On a miss it reads the database, stores the answer in the cache and returns it. The next reader of that key gets a hit.
How big should a cache be?
Size it for the head of your traffic, not for the whole dataset. With 10,000 keys and a Zipf exponent of 1.0, 100 keys catch about 53% of reads and 1,000 keys catch about 76%. Each doubling after that adds only about 7 points. Measure your real hit ratio before buying more memory.
What is a cache stampede?
A stampede happens when many hot keys expire at the same moment, so many requests miss together and all go to the database. Two cheap fixes help: coalesce concurrent misses for the same key into one database read, and add jitter so TTLs differ by a random amount.
Write-through or write-behind?
Pick write-through when you cannot lose a write. Pick write-behind when you need fast writes and can accept losing the last unflushed batch if the cache crashes. Most systems start with write-through or with no write caching at all.
Related guides
- Load balancing explainedRound robin against least connections, health checks and the capacity maths behind adding servers.
- How to practise for the system design interviewThe steps every interview follows, with a URL shortener worked through.
- All system design guidesThe full set, each with a hands-on Lesson.
- ByteLabThe system design simulator behind these numbers.