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

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.

AppAppCache, 3 slots, in memoryCache3 slots, in memoryDatabase, on diskDatabaseon disk
  • App — healthy
  • Cache — 3 slots, in memory — healthy
  • Database — on disk — healthy
Reads
0
Hits
0
Database reads
0
  1. Ask the cache first. The app asks the cache for item:1 first, because memory answers in about 1 ms.
  2. A miss goes on. It is not there yet, a miss, so the app reads the database, which takes 10–20 ms.
  3. Keep a copy. The app saves item:1 in the cache, so the next read can skip the database.
  4. The next read hits. The next read of item:1 is a hit: answered from memory, with no database work.
  5. 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.
  6. Hits add up. If 9 in 10 reads hit, 10,000 reads need only 1,000 database reads.
  7. 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

  1. The app checks the cache first; only a miss goes on to the slower database.
  2. After a miss, the app saves a copy, so later reads of that key can hit.
  3. A full cache must drop a key; LRU drops the one used longest ago.
  4. A 90% hit rate turns 10,000 reads into only 1,000 database reads.

Go deeper in the Caching lab →

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 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 , 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

Live simulationOpen the full lab →

Lab · Building blocks

Caching

A cache keeps copies of popular data in memory so most reads skip the slower database. See when that works, what happens on writes, and the three classic failure modes: stale data, stampedes and cold starts.

Try it

Lab time 3.0 s
get / setreads on miss, writesClients, 100% readsClients100% reads12 ops/sApp server, Cache-asideApp serverCache-asideCache (Redis), LRU · TTL offCache (Redis)LRU · TTL off6/6 keysDatabase, source of truthDatabasesource of truth4 reads/s
About each part:
  • Clients — 100% reads — healthy — 12 ops/s
  • App server — Cache-aside — healthy
  • Cache (Redis) — LRU · TTL off — healthy — 6/6 keys
  • Database — source of truth — healthy — 4 reads/s
  • Request
  • Cache hit
  • Cache miss → DB
  • Stale data
  • Write
  • Invalidate
  • Response
Hit rate
36%
Watch: most reads miss
Database reads
4/s
Read latency,
570 ms
At the server: hits 30 ms, misses 290 ms
Stale reads
0
Write latency,
—
Lost writes
0

Numbers add up:33 reads = 12 hits + 21 misses; misses = 21 DB reads + 0 coalescedThe lab checks this sum as it runs, so a counting mistake would show here.

Controls

Traffic
12/s
0%
Key popularity

A few keys get most of the reads (typical web traffic).

Cache
6 keys
Eviction

Evict the key that was used least recently.

(TTL)
Writes & failures
Write strategy

Reads fill the cache on a miss. Writes go to the database, then delete the cached copy.

One DB read per key at a time; other misses wait for it.

What's in the cache right now

Evicted item:20
  • item:1v1 · used 5×
  • item:3v1 · used 5×
  • item:6v1 · used 2×
  • item:7v1 · used 2×
  • item:5v1 · used 1×
  • item:2v1 · used 1×

Keys are ordered by when they entered the cache. item:1 is the most popular key, item:20 the least.

Hit rate
0%25%50%75%100%1s2s3s
Show data table
TimeHit rate
1s0%
1s33%
2s57%
2s60%
3s40%
3s50%
Database reads per second
051015201s2s3s
Show data table
TimeDB reads/s
1s18
1s4
2s6
2s4
3s6
3s4

What just happened

  1. 0.3sWarning: Duplicate DB read: item:5 missed again while its first DB read was still running. With heavy traffic this becomes a stampede.
  2. 0.0sInfo: Cache ready: 6 slots, LRU eviction, Cache-aside.
What this model simplifies
  • Time is slowed: a database read takes 0.26 s here so you can watch it. Real ratios are similar in spirit — memory is roughly 10–100× faster than a database round trip.
  • The trip between client and server is slowed too, and it is the same for a hit and a miss. "At the server" leaves it out, so it shows what the cache itself saves.
  • The cache is a single node. Real deployments shard keys across many nodes and replicate them.
  • Write-behind flushes every 2.5 s in one batch. Real systems flush by time or batch size and may persist a log to survive crashes.
  • Every key has the same size and cost. In practice big or expensive-to-compute values change which keys are worth caching.

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.

  1. Cache-aside: reading

    App, the shopAppthe shopCache, in memory, NOWCachein memoryno copy of item:1NOWDatabase, the real recordDatabasethe 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 4

    Step 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 holds
    no copy
    of item:1
    Database holds
    499
    the real record
    This request waited
    1ms
    round example times

    Step 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 , 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.

  2. Cache-aside: writing

    Pick a case to follow below

    The 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 shopAppthe shopCache, in memoryCachein memoryitem:1 = 499 · staleDatabase, the real record, NOWDatabasethe real recorditem:1 = 449NOW
    • 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 5

    Step 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 holds
    499
    Watch: stale: the database has 449
    Database holds
    449
    the real record
    This request waited
    20ms
    round example times

    Step 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.

  3. Write-through

    Pick a case to follow below

    With 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 shopAppthe shopCache, in memory, NOWCachein memoryitem:1 = 449 · newNOWDatabase, the real recordDatabasethe 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 4

    Step 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 holds
    449
    Watch: new: the database has not got it yet
    Database holds
    499
    Watch: not saved yet: 449 is in the cache
    This request waited
    1ms
    round example times

    Step 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 , 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.

  4. Write-behind (write-back)

    Pick a case to follow below

    With 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 shopAppthe shopCache, in memory, NOWCachein memoryitem:1 = 449 · newNOWDatabase, the real recordDatabasethe 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 3

    Step 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 holds
    449
    Watch: new: the database has not got it yet
    Database holds
    499
    Watch: not saved yet: 449 is in the cache
    This request waited
    1ms
    round example times

    Step 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.

    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.

  5. Refresh-ahead

    Pick a case to follow below

    With 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 shopAppthe shopCache, in memoryCachein memoryitem:1 = 499 · freshDatabase, the real record, NOWDatabasethe real recorditem:1 = 499NOW
    • 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 2

    Step 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 holds
    499
    Healthy: fresh: matches the database
    Database holds
    499
    the real record
    This request waited
    –
    no request at this step
    Clock
    50s
    the copy was saved at 0 s, TTL 60 s

    Step 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 , 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.

The strategies side by side
StrategyOn a missA write waits forMain risk
Cache-asideThe app reads the database and saves a copyThe database, then a delete in the cacheA stale copy until the TTL ends, if the delete is lost
Write-throughNeeds its own read rule, often cache-asideThe cache and the databaseA stale copy if a writer skips the cache
Write-behindNeeds its own read rule, often cache-asideThe cache onlyLost writes if the cache crashes before saving
Refresh-aheadRare on busy keys, which are reloaded earlyNot a write ruleWasted 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 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

With write-through caching, what happens on a write?

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.

PlayersPlayersGame serverGame serverSorted set in RedisSorted set in RedisScores databaseScores database
  • Players — healthy
  • Game server — healthy
  • Sorted set in Redis — healthy
  • Scores database — healthy
Top of the leaderboard
RankPlayerScore
1user:91,410
2user:31,320
3user:171,260
4 (highlighted)user:421,200
5user:51,180
Steps per update
not shown yet
Comparisons to sort on each read
not shown yet
  1. A player wins. Player user:42 wins a match, and the score goes from 1,200 to 1,300.
  2. Update the sorted set. The game sends ZINCRBY, the Redis command that adds points, and user:42 moves up in about 20 steps.
  3. Top 10 is ready. Reading the top 10 walks the first 10 entries in order, with no sorting when someone reads.
  4. Your rank, fast. ZREVRANK, the command that asks for a rank counting from the top, answers in about 20 steps.
  5. Sorting on each read. Sorting 1,000,000 scores on each read instead would take about 20,000,000 comparisons every time.
  6. Save scores too. Redis keeps the set in memory, so scores also go to a database, to rebuild the set after a crash.
  7. 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

  1. A sorted set stores each player with a score, kept in order.
  2. With 1 million players, an update or a rank lookup takes about 20 steps.
  3. Without it, finding one player's rank means counting every higher score.
  4. 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 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

Every write already deletes the cached copy. Why add a TTL as well?

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?

The app uses cache-aside with a 60-second TTL. A user changes their name, and the app updates the database only. What do readers see?

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

A cache hit takes 1 ms. On a miss, the app checks the cache (1 ms) and then reads the database (15 ms). The hit rate is 90%. What is the average read time?

Apply it

With write-behind, the cache confirms 200 writes. It crashes before the worker saves them, and it keeps nothing on its own disk. What happens to those writes?

Judge a design

After a transfer, a bank's balance page must show the new balance on the next read. Which cache plan fits best?

Next: cache eviction, which decides what to remove when the cache is full, and how to survive a cache stampede.

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.