Stage 2 · Building blocks · Easy · 22 min
Caching strategies
Keep a copy of data that is read again and again, so most reads are answered from memory. Learn five common ways to fill that copy and keep it correct.
What each interview level is expected to know
Learn first: Vertical and horizontal scaling
In AI systems: Caching for AI features
After this lesson you can:
- Explain cache-aside, write-through, write-behind and refresh-ahead, and when each fits.
- Predict how long readers see an old value after a write, from the TTL.
- Keep the cache and the database in step, and name the risk of write-behind.
Start here
See it in 60 seconds
How a cache saves the database
The app checks a small, fast cache before the database, so repeated reads get answered from memory.
Scene 1 of 6 · Ask the cache first
The app asks the cache for item:1 first, because memory answers in about 1 ms.
- App — healthy
- Cache — 3 slots, in memory — healthy
- Database — on disk — healthy
- Reads
- 0
- Hits
- 0
- Database reads
- 0
- Ask the cache first. The app asks the cache for item:1 first, because memory answers in about 1 ms.
- A miss goes on. It is not there yet, a miss, so the app reads the database, which takes 10–20 ms.
- Keep a copy. The app saves item:1 in the cache, so the next read can skip the database.
- The next read hits. The next read of item:1 is a hit: answered from memory, with no database work.
- Full: drop the oldest. After reads of item:2, item:3 and item:1, the cache is full; reading item:4 removes item:2, used longest ago.
- Hits add up. If 9 in 10 reads hit, 10,000 reads need only 1,000 database reads.
- Now you try. Tap keys to read them in order, and watch a 3-slot LRU cache hit and miss. For example, tapping item:1, item:2, item:3, item:1 and item:4 gives this: 1 of 5 reads hit and 4 missed; the cache now holds item:4, item:1 and item:3. When the cache was full, reading item:4 removed item:2, the key used longest ago.
Scene 1 of 6: Ask the cache first. The app asks the cache for item:1 first, because memory answers in about 1 ms.
Key points
- The app checks the cache first; only a miss goes on to the slower database.
- After a miss, the app saves a copy, so later reads of that key can hit.
- A full cache must drop a key; LRU drops the one used longest ago.
- A 90% hit rate turns 10,000 reads into only 1,000 database reads.
In plain words
Say the shop page for one popular item is opened 10,000 times. Each time, the app asks the database the same question and gets the same answer. A (A small, fast store that keeps copies of popular data, so most reads skip the slower database.) is a small, fast store that keeps a copy of that answer in memory, under a key such as item:1. While the copy is there, readers get it and the database is not asked.
Three words come up again and again. A hit means the cache had a copy, so the answer came from memory in about a millisecond. A miss means it did not, so the app asked the database and usually kept a copy for next time. A (How long a cached copy is kept before it is thrown away.), short for time to live, is how long a copy may stay before the cache drops it.
The problem it solves
A database can answer only so many queries at once. Each query takes a connection, and many need a slow read from disk. When thousands of people open the same popular page, the database repeats the same work for each of them. It slows down for everyone, even for users who want something else.
Why it matters
A cache is often the first fix when a site gets slow. It takes load off the database without changing the database itself. It is also where many bugs start: a shopper sees an old price, or a saved change goes missing. In an interview, drawing a cache is the easy part. Saying how its copies stay correct is what earns the points.
A worked example
A profile page gets 10,000 reads a second. The database answers in 20 ms and the cache in 1 ms. If 90% of reads find their copy in the cache, only 1,000 reads a second reach the database. The average read takes 0.9 × 1 + 0.1 × 20 = 2.9 ms instead of 20 ms.
Think of it like…
Think of a cafe that keeps its five best-selling cakes on the counter, not in the kitchen at the back. Most customers are served at once.
Where this analogy stops working
Keeping popular things close is the useful part. But a cake on the counter is the real cake. A cache holds a copy, and the copy can go out of date. When the data changes, readers get the old value until the copy is deleted or times out.
Try it
See it working
Mechanics
How it works
A cache needs two rules. The read rule says how a copy gets into the cache. The write rule says what happens to that copy when the real data changes.
Each strategy below is one choice of rules, shown on the same small shop. It sells one item, item:1, priced at 499 until the shop lowers it to 449. Press Play or Next step on each picture, then read what it showed.
Cache-aside: reading
App, the shop App the shop Cache, in memory, NOW Cache in memory no copy of item:1 NOW Database, the real record Database the real record - App — the shop — healthy
- Cache — in memory — healthy — NOW — no copy of item:1
- Database — the real record — healthy
- Cache miss
- Read
- Copy saved in the cache
- Cache hit
Step 1 of 4Step 1 of 4 · Cache
Done: A shopper asks the cache for item:1: a miss
- What happens
- The app checks the cache first, and the cache has no copy of item:1.
- Why
- Memory answers in about 1 ms, so the cache is always the first place the app looks.
- What changes
- A miss. The app has to go to the database.
- Next
- The app reads item:1 from the database
Cache holdsno copyof item:1Database holds499the real recordThis request waited1msround example timesStep 1 of 4: Cache. A shopper asks the cache for item:1: a miss. The app checks the cache first, and the cache has no copy of item:1.
In (Cache-aside is a caching pattern where the app reads the cache first. If the value is missing, it reads the database, then saves the result in the cache for later.), the app does all the work. The cache is only a store: it keeps what the app puts in it, and it never talks to the database.
The picture follows two shoppers. The first read is a miss, because nothing has asked for item:1 yet. The app reads the price from the database, then saves a copy in the cache with a TTL of 60 seconds.
The second read is a hit. The copy is there, so the answer comes from memory, and the database does no work for that read.
This is also called lazy loading, because a copy is made only when someone asks for it. So the cache fills up with the data people really read. If the cache goes down, the app can still read the database. Every read then waits for the database, and the database has to take all of them.
The cost is the first read of each key. It pays for the trip to the cache, the trip to the database and the save.
Best for: Most data that is read far more often than it changes, such as product pages and user profiles. It is the usual place to start.
Cache-aside: writing
Pick a case to follow belowThe usual way.
With this case: Every read after the write saw 449. The cost was one extra miss, which waited about 22 ms.
App, the shop App the shop Cache, in memory Cache in memory item:1 = 499 · stale Database, the real record, NOW Database the real record item:1 = 449 NOW - App — the shop — healthy
- Cache — in memory — healthy — item:1 = 499 · stale
- Database — the real record — healthy — NOW — item:1 = 449
- Write
- Delete the copy
- Cache miss
- Read
- Copy saved in the cache
Step 1 of 5Step 1 of 5 · Database
Done: The app saves the new price, 449, in the database
- What happens
- The shop changes the price of item:1 from 499 to 449. The app writes it to the database first.
- Why
- The database is the real record, so it changes first. If this write fails, nothing else should change.
- What changes
- The database has 449. The cache still holds 499, so its copy is now stale.
- Next
- The app deletes the cached copy
Cache holds499Watch: stale: the database has 449Database holds449the real recordThis request waited20msround example timesStep 1 of 5: Database. The app saves the new price, 449, in the database. The shop changes the price of item:1 from 499 to 449. The app writes it to the database first.
Now the shop lowers the price of item:1 to 449. The app saves it in the database, but the cache still holds 499. Switch between the two cases to see what the app should do next.
Pick "Update the database only". The next shopper gets a hit on the old copy and sees 499. A copy that no longer matches the database is called stale. It stays until its TTL ends, up to 60 seconds later.
So the usual rule is this: update the database, then delete the key from the cache. The next read misses, loads 449, and saves a fresh copy. The cost is one extra miss.
Why delete the copy instead of writing 449 into it? Two price changes can arrive close together. They can reach the database in one order and the cache in the other, and the cache then keeps the older price. A deleted copy cannot hold a wrong price. It can only be missing. One rare race is left: a read that began before the change can put the old price back. That is one reason to keep a TTL as well.
Deleting does not close every gap. A slow read can fetch 499 from the database a moment before the write, then save it in the cache right after the delete. The TTL is the safety net: it puts a time limit on any stale copy that slips through.
Write-through
Pick a case to follow belowWith this case: The first read after the write already saw 449. The cost was a write that waited about 21 ms for both the cache and the database.
App, the shop App the shop Cache, in memory, NOW Cache in memory item:1 = 449 · new NOW Database, the real record Database the real record - App — the shop — healthy
- Cache — in memory — healthy — NOW — item:1 = 449 · new
- Database — the real record — healthy
- Write
- Done
- Cache hit
Step 1 of 4Step 1 of 4 · Cache
Done: The app sends the new price, 449, to the cache
- What happens
- The shop changes the price of item:1 to 449. The app writes it to the cache, not to the database.
- Why
- In write-through, every write goes in through the cache.
- What changes
- The cache holds 449. The database still has 499, and the app is still waiting.
- Next
- The cache writes the price to the database
Cache holds449Watch: new: the database has not got it yetDatabase holds499Watch: not saved yet: 449 is in the cacheThis request waited1msround example timesStep 1 of 4: Cache. The app sends the new price, 449, to the cache. The shop changes the price of item:1 to 449. The app writes it to the cache, not to the database.
In (A write strategy that updates the cache and the database together before telling the caller it is done.), every write goes to the cache first. The cache saves it in the database, and only then tells the app the write is done.
Follow the price change in the first case. When the write finishes, the cache already holds 449, so the next read is a hit with the right price. In this case there is no stale copy at all.
Writes do not get faster. Each one still waits for the database, plus the trip to the cache. What you get is a cache that is up to date the moment a write ends.
Now pick the second case. A nightly price import writes 429 straight to the database and skips the cache. The cache keeps 449, and shoppers see the wrong price. Write-through only works if every writer goes through the cache.
It can also fill the cache with data nobody reads. A delivery app might save a driver's location every few seconds, but show it only while someone watches the order. Each of those writes takes cache memory. A TTL limits how long that waste stays.
Best for: Data that is often read right after it is written, where a slightly slower write is fine and every writer can go through the cache.
Write-behind (write-back)
Pick a case to follow belowWith this case: The write waited about 1 ms, and the database caught up later. Until then, the new price lived only in the cache's memory.
App, the shop App the shop Cache, in memory, NOW Cache in memory item:1 = 449 · new NOW Database, the real record Database the real record - App — the shop — healthy
- Cache — in memory — healthy — NOW — item:1 = 449 · new
- Database — the real record — healthy
- Write
- Done
Step 1 of 3Step 1 of 3 · Cache
Done: The app sends the new price, 449, to the cache
- What happens
- The shop changes the price of item:1 to 449. The app writes it to the cache only.
- Why
- In write-behind, the cache takes the write now and saves it to the database later.
- What changes
- The cache holds 449. The database still has 499.
- Next
- The cache answers at once: done
Cache holds449Watch: new: the database has not got it yetDatabase holds499Watch: not saved yet: 449 is in the cacheThis request waited1msround example timesStep 1 of 3: Cache. The app sends the new price, 449, to the cache. The shop changes the price of item:1 to 449. The app writes it to the cache only.
(A write strategy that updates the cache right away and writes to the database later, in a batch.) answers the app as soon as the cache has the write. A background worker saves it in the database later.
In the first case, the app waits only for the cache, so the write is fast. The worker then saves changes in batches. Say a popular video gets 500 likes in 5 seconds. The worker can save them as one update of the like count, not 500 separate writes.
Pick the second case to see the danger. The cache crashes before the worker runs. The shop was told the new price was saved, but the database still says 499, and the change is gone.
Some caches can also write each change to their own disk. That makes the gap smaller, but it may not close it. Check what yours promises before you trust it with data you cannot lose.
Best for: Counters, likes and view counts: data written very often, where losing the last few seconds of changes is acceptable.
Refresh-ahead
Pick a case to follow belowWith this case: The reader at second 61 got a hit in about 1 ms. The reload cost one database read that no user waited for.
App, the shop App the shop Cache, in memory Cache in memory item:1 = 499 · fresh Database, the real record, NOW Database the real record item:1 = 499 NOW - App — the shop — healthy
- Cache — in memory — healthy — item:1 = 499 · fresh
- Database — the real record — healthy — NOW — item:1 = 499
- Copy saved in the cache
- Cache hit
Step 1 of 2Step 1 of 2 · Database
Done: At second 50, the cache reloads item:1
- What happens
- The copy has 10 seconds left. The cache reads the price from the database again, before it runs out.
- Why
- item:1 is read all the time, so the cache keeps it loaded and nobody has to wait for a miss.
- What changes
- The cache has a new copy of 499, with a fresh TTL of 60 seconds.
- Next
- A shopper at second 61 reads item:1: a hit
Cache holds499Healthy: fresh: matches the databaseDatabase holds499the real recordThis request waited–no request at this stepClock50sthe copy was saved at 0 s, TTL 60 sStep 1 of 2: Database. At second 50, the cache reloads item:1. The copy has 10 seconds left. The cache reads the price from the database again, before it runs out.
What these pictures simplify. Each picture follows one key through one app, one cache and one database. The times, 1 ms for the cache and 20 ms for the database, are round examples, not measurements. A real shop has many servers and many keys, and many requests arrive at once. The Caching lab above runs that.
Refresh-ahead is for keys that are read all the time. The cache reloads such a key from the database a little before its TTL runs out.
Compare the two cases. With no refresh, the copy expires at 60 seconds, so the shopper at 61 seconds misses and waits for the database. With refresh-ahead, the cache fetched a new copy at 50 seconds, so the same shopper gets a hit.
This matters most on a busy key. When its copy expires, every reader at that moment misses and goes to the database together. That pile-up is called a (A burst of requests that all miss the cache for the same key at once and hit the database together.), and the next lesson covers it.
The cost is extra work. The cache reloads keys whether or not anyone reads them again, so it has to guess which keys are worth it. Not every cache can reload on its own. Sometimes the app runs a small job that does it.
Best for: A small set of keys read many times a second, such as a home page feed or a top-10 list.
| Strategy | On a miss | A write waits for | Main risk |
|---|---|---|---|
| Cache-aside | The app reads the database and saves a copy | The database, then a delete in the cache | A stale copy until the TTL ends, if the delete is lost |
| Write-through | Needs its own read rule, often cache-aside | The cache and the database | A stale copy if a writer skips the cache |
| Write-behind | Needs its own read rule, often cache-aside | The cache only | Lost writes if the cache crashes before saving |
| Refresh-ahead | Rare on busy keys, which are reloaded early | Not a write rule | Wasted reloads of keys nobody reads |
Use it when
- Data that is read far more often than it changes: product pages, user profiles, home feeds.
- Results that are slow to work out, such as a report query that takes 2 seconds.
- Short-lived data that needs fast reads, such as login (A record the server keeps for a logged-in user. The browser holds only its id, and sends it with every request.) and leaderboards.
Skip it when
- Data that changes more often than it is read: each copy is out of date before anyone uses it.
- A value that must be exact at that moment, such as an account balance during a payment: read it from the database.
Check yourself
Also
More in 60 seconds
A live leaderboard with a sorted set
A sorted set keeps players in score order as scores change, so the top 10 and any player's rank come back in a few steps.
Scene 1 of 6 · A player wins
Player user:42 wins a match, and the score goes from 1,200 to 1,300.
- Players — healthy
- Game server — healthy
- Sorted set in Redis — healthy
- Scores database — healthy
| Rank | Player | Score |
|---|---|---|
| 1 | user:9 | 1,410 |
| 2 | user:3 | 1,320 |
| 3 | user:17 | 1,260 |
| 4 (highlighted) | user:42 | 1,200 |
| 5 | user:5 | 1,180 |
- Steps per update
- not shown yet
- Comparisons to sort on each read
- not shown yet
- A player wins. Player user:42 wins a match, and the score goes from 1,200 to 1,300.
- Update the sorted set. The game sends ZINCRBY, the Redis command that adds points, and user:42 moves up in about 20 steps.
- Top 10 is ready. Reading the top 10 walks the first 10 entries in order, with no sorting when someone reads.
- Your rank, fast. ZREVRANK, the command that asks for a rank counting from the top, answers in about 20 steps.
- Sorting on each read. Sorting 1,000,000 scores on each read instead would take about 20,000,000 comparisons every time.
- Save scores too. Redis keeps the set in memory, so scores also go to a database, to rebuild the set after a crash.
- Now you try. How many players are on the leaderboard? For example: An update takes about 20 steps and the top 10 about 30; sorting on each read takes about 20,000,000 comparisons. The steps grow with log2 of the players, so each 1,000 times more players adds only about 10 steps.
Scene 1 of 6: A player wins. Player user:42 wins a match, and the score goes from 1,200 to 1,300.
Key points
- A sorted set stores each player with a score, kept in order.
- With 1 million players, an update or a rank lookup takes about 20 steps.
- Without it, finding one player's rank means counting every higher score.
- The set lives in memory, so scores are also saved to a database.
Judgement
Trade-offs and how it fails
What you give up
- Performance
- A (A read that the cache can answer by itself, without asking the database.) takes around 1 ms. The same read from the database often takes 10–20 ms.
- Consistency
- The cache can hold an old copy. If a write does not also update or delete that copy, readers see stale data until the TTL ends.
Failure modes
- Cache and database disagree: a write changes the database, but the delete of the cached copy fails or arrives late. Readers get the old value until the TTL ends.
- Lost writes with write-behind: writes wait in the cache's memory before they reach the database. If the cache crashes first, and it keeps nothing on its own disk, those writes are lost.
In the real world
- Twitter kept each user's home timeline in Redis, ready to read. A 2012 talk by its engineers gave about 300,000 timeline reads a second, home and search together. Source: High Scalability: Twitter's architecture (2013) (checked 14 October 2026)
- Stack Overflow has described using two cache layers: memory inside each web server first, then a shared Redis.
Trade-offs to be ready to discuss: Cache aside vs write through
Check yourself
Interview
What interviewers look for
- Start with cache-aside and a TTL. Move to write-through only if readers must not see an old value after a write.
- Say how the copy stays fresh: delete the key after each database write, and let the TTL catch any delete that is lost.
Say it out loud: What is the main risk of write-behind caching?
Expected depth by interview level
Levels describe the depth interviewers probe, not years of experience. Choose a level on the learning path to highlight it.
- JuniorCore
- Add a cache for repeated reads.
- MidCore
- Cache-aside vs write-through, TTLs, and what to cache.
- SeniorCore
- Invalidation, consistency and stampedes.
- StaffExpected
- Cache layers, hit-rate economics and the impact of a cache failure.
Practice
Apply it
Three harder questions
The first two use the idea on a new case. The last asks you to judge a design.
Apply it
Apply it
Judge a design
Go deeper
Sources and further reading
First-hand sources to check this page against and to go further. They are standards, official docs, original papers, and guides from engineering and security teams. Each link was opened on 8 November 2026.
- Official docsCaching strategiesAmazon ElastiCache documentationLazy loading (cache-aside) and write-through compared, and how a TTL limits stale data.
- Research paperScaling Memcache at Facebook (2013)Nishtala et al., USENIX NSDIHow Facebook keeps a huge cache close to its database, including deleting keys after writes.