Scrivio Interview library
ConceptFoundations7 min read · updated 13 November 2026

Cache-aside with delete-on-write is the most common way to keep a cache and a database in step, and it is often described as safe. It still has a race that can leave a stale value in the cache.

Walk through the interleaving of one reader and one writer that leaves a stale value in the cache, and explain why it is rare, what bounds it, and how it can be reduced.

Try it yourself

Cache-aside: one read, three cache states

See what a cache hit saves, what a miss costs, and why a write deletes the cached entry instead of updating it.

Read this example as text

When the entry is in the cache (a hit)

  1. A request arrives. A caller asks the service for product 42. The cache already holds it.
  2. Ask the cache first. The service always asks the cache before the database. It sends GET product:42.
  3. Hit: the value comes back. The entry is there and still fresh, so the cache answers at once. The database is never touched.

1 cache call, 0 database reads.

When it was never cached (a miss)

  1. A request arrives. A caller asks the service for product 42. Nobody has asked for it before, so the cache holds nothing.
  2. Ask the cache first. The service always asks the cache before the database. It sends GET product:42.
  3. Miss: nothing comes back. The key was never stored. The cache answers nil, and the service must find the value itself.
  4. Read the database. The service runs SELECT ... FROM products WHERE id = 42. This is the slow, authoritative read the cache exists to avoid.
  5. The row comes back. The database returns the row. The service now has the value, but the cache is still empty.
  6. Store it for next time. Before answering, the service writes the value into the cache with a time to live: SET product:42 ... EX 300. The next read inside 300 seconds will be a hit.
  7. Answer the caller. The caller gets the value. It cost one database read, which a hit would have saved.

2 cache calls, 1 database read.

When its time to live has run out

  1. A request arrives. A caller asks the service for product 42. The cache held it once, but its time to live ran out 12 seconds ago.
  2. Ask the cache first. The service always asks the cache before the database. It sends GET product:42.
  3. Miss: nothing comes back. An expired key is the same as a missing one: Redis no longer returns it, and removes it. The cache answers nil, and the service must find the value itself.
  4. Read the database. The service runs SELECT ... FROM products WHERE id = 42. This is the slow, authoritative read the cache exists to avoid.
  5. The row comes back. The database returns the row. The service now has the value, but the cache is still empty.
  6. Store it for next time. Before answering, the service writes the value into the cache with a time to live: SET product:42 ... EX 300. The next read inside 300 seconds will be a hit.
  7. Answer the caller. The caller gets the value. It cost one database read, which a hit would have saved.

2 cache calls, 1 database read.

When the price changes afterwards

  1. The price changes. Later, someone updates the price to 25. The service writes the database first: UPDATE products SET price = 25 WHERE id = 42.
  2. Delete the cached entry. Then it deletes the key: DEL product:42. It does not write 25 into the cache. Deleting is simpler and safer: the next read misses and loads whatever the database holds then.
  3. The next read will miss. The cache is empty for this key again, so the next request repeats the miss path and stores 25.

3 cache calls, 1 database read, 1 database write.

What this example leaves out
  • One request at a time. Two requests missing at the same moment (a stampede) are not shown.
  • The write deletes the key. Some systems update the cache instead, which this example does not model.
  • The numbers are counts of round trips, not measured times.

A reader misses the cache and reads the old value from the database; before it writes that value into the cache, a writer updates the database and deletes the key; then the reader's late set puts the old value back, and it stays stale until the TTL expires or the next write. It is rare because the reader's read must come before the write and its set after the delete, but hot keys and slow readers make it happen, so we always keep a TTL as a bound and can shrink the risk with a delayed second delete, versioned sets or lease tokens.

Background to this question

Cache-aside with delete-on-write is the pattern most teams use with Redis or Memcached, and it is usually described as safe because the writer deletes the key instead of writing a value into it. It is much safer than the alternatives, but it is not perfectly safe, and knowing exactly why is a good test of whether someone can reason about concurrency rather than repeat a pattern. In this answer, we will recap the pattern, walk through the one interleaving that leaves a stale value, see why it is rare and what bounds it, look at three ways to reduce it, and compare it with updating the cache instead of deleting.

1A Quick Recap of Cache-Aside With Delete-on-Write

In cache-aside, the application talks to both the cache and the database itself. To read, it looks in the cache; on a miss, it reads from the database and writes the value into the cache with a TTL, a time to live after which the cache drops the key. To write, it updates the database and then deletes the key from the cache, so the next reader misses and loads the new value.

Java
// read path
String get(long id) {
String v = redis.opsForValue().get("user:" + id);
if (v != null) return v; // hit
v = db.loadUserJson(id); // miss: read from the database
redis.opsForValue().set("user:" + id, v, Duration.ofMinutes(10)); // fill with a TTL
return v;
}
// write path
void update(long id, String json) {
db.saveUserJson(id, json); // 1. commit to the database
redis.delete("user:" + id); // 2. delete the cached copy
}

Notice that the read path is not atomic. Between reading the database and setting the cache, time passes, and anything can happen in that gap. That gap is where the race lives.

2The Interleaving That Leaves a Stale Value

Let the stored value be name = Ann, and suppose the key is not in the cache. A reader and a writer run at the same time, and their steps interleave like this.

Reader and writer interleaving on key user:7
TimeReaderWriterCache after the step
t1GET user:7 -> missempty
t2SELECT -> name = Ann (old)empty
t3UPDATE name = Bea, commitempty
t4DEL user:7 (nothing to delete)empty
t5SET user:7 = Ann, TTL 10 minAnn (stale)
t6next readers: GET -> AnnAnn until TTL or next write

The writer did everything right: it committed and then deleted. But its delete came while the key was empty, so it removed nothing, and the reader's set, carrying the value it read before the update, arrived afterwards. From then on every reader gets Ann, while the database says Bea. The stale value survives until the TTL expires or another write deletes the key again.

3Why It Is Rare, and Why It Still Happens

Look at what the race requires. The reader's database read at t2 must happen before the writer's commit at t3, and the reader's cache set at t5 must happen after the writer's delete at t4. So the whole write, commit plus delete, has to fit inside the reader's short gap between reading the database and setting the cache. That gap is usually a millisecond or two, while a write with its commit often takes longer, so most of the time the reader sets the cache before the writer deletes, and the delete then removes the old value correctly.

But there is a catch. At high traffic on a hot key, with thousands of reads and frequent writes a second, rare coincidences happen many times a day. And anything that stretches the reader's gap widens the window: a garbage collection pause in the reader's JVM, a slow network hop to Redis, a reader thread descheduled under CPU pressure. A two-second pause turns a one-millisecond window into a two-second one.

4What Bounds the Damage: the TTL

The stale value is not permanent, because the reader set it with a TTL. That is the reason delete-on-write still needs a TTL on every cached key, even if we invalidate carefully. The TTL is the upper bound on how long any missed or raced invalidation can leave wrong data, so we choose it from the business: ten minutes may be fine for a display name, but too long for a price.

5Reducing the Race: Second Delete, Versions, Leases

The simplest mitigation is a delayed second delete. After the first delete, the writer schedules another delete of the same key a short time later, longer than a typical read takes, for example 500 milliseconds. A reader that raced the first delete has usually set its stale value by then, so the second delete removes it. It is cheap to add with a scheduled executor or a delayed message.

A stronger mitigation is a version check on set. The database row carries a version that increases on every update, the reader loads the version with the value, and the cache only accepts a set whose version is newer than the one it holds; this needs an atomic compare-and-set, such as a small Redis Lua script. The strongest is a lease, the approach Facebook described for Memcached: on a miss, the cache hands the reader a lease token; a delete invalidates any outstanding tokens; and a set with an invalidated token is rejected. In our interleaving, the delete at t4 would cancel the reader's lease from t1, so the set at t5 would fail.

Ways to reduce the race
ApproachHow it stops the stale setCost
TTL onlyDoes not stop it; bounds its lifetimeNone
Delayed second deleteRemoves a stale set made within the delayExtra delete, extra misses; slow readers still win
Version check on setRejects a set older than the cached versionVersion column, Lua script
Lease tokensDelete cancels the lease; late set failsNeeds cache support or custom logic

6Why Not Update the Cache Instead of Deleting?

It is tempting to have the writer put the new value into the cache directly. But then two writers race each other, and the result is worse. Writer 1 commits name = Bea, writer 2 commits name = Cal, writer 2 sets the cache to Cal, and then writer 1, delayed, sets it to Bea. The database says Cal, the cache says Bea, and no reader miss was needed at all: two concurrent writes are enough, which is much more common than the narrow reader-writer window. Updating also wastes work writing values nobody reads. So deletion is the default, and the cache is filled only by readers who loaded from the database.

7Follow-up questions

Why does a delayed second delete not fully remove the race?

Because it only covers readers that finish within the delay. If the reader is paused for longer, for example a two-second garbage collection pause against a 500-millisecond delay, its stale set lands after the second delete too and stays until the TTL. The second delete itself can also fail or be lost if the writer crashes before it runs. It narrows the window; version checks or leases close it.

Should the writer delete before or after the database commit?

After. If it deletes before committing, a reader can miss, read the old committed value and set it in the cache before the commit happens, which is a much wider window than the race we described. Deleting after commit, ideally triggered from the committed transaction, keeps the window as narrow as possible.

Would a distributed lock around the read path solve it?

It can, if writers take the same lock, but it serialises reads and writes for each key, adds latency and a failure mode when the lock holder dies. Version checks give the same safety without blocking, which is why they are usually preferred.

8Conclusion

In this answer, we saw the one interleaving that breaks cache-aside with delete-on-write: a reader reads the old value, a writer commits and deletes an empty key, and the reader's late set stores the old value until the TTL or the next write. It needs the whole write to fit inside the reader's gap, so it is rare, but hot keys and pauses make it real. The TTL bounds it, a delayed second delete narrows it, and version checks or lease tokens close it. Updating the cache instead of deleting suffers a more common race between two writers, which is why deletion is the default.

What to say in the interviewAbout 90 seconds aloud

Open with

The race needs one reader and one writer. The reader misses the cache and reads the old value from the database. Before it sets the cache, the writer commits the new value and deletes the key, but the key is not there yet, so the delete does nothing.

Then, if they want more

Then the reader's set arrives with the old value, and every reader after that gets stale data until the TTL expires or another write deletes it. It is rare because the reader's database read must come before the commit and its set must come after the delete, so the whole write has to fit in the reader's millisecond gap.

But on hot keys at high traffic it happens, and garbage collection pauses or slow networks widen that gap a lot. That is why delete-on-write still needs a TTL: it is the bound on how long a raced invalidation can last.

To reduce it, the cheapest step is a delayed second delete, say 500 milliseconds after the first, though a reader paused longer than that still wins.

Stronger options are a version check on set, so the cache only accepts a newer version through an atomic script, or lease tokens, where the delete invalidates the reader's lease and its late set is rejected. And I would not update the cache on write, because two writers racing is even more likely to leave the wrong value.

About this answer

Last updated
13 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Walk through the interleaving of one reader and one writer that leaves a stale value in...": https://scrivio-interview-library.netlify.app/architecture/caching-strategies/9ed51e5803/