Scrivio Interview library
ConceptFoundations5 min read · updated 12 November 2026

Compare these strategies for keeping a cache consistent with a database: TTL-only expiry, evict on write, update (put) on write, and write-through. When would you choose each?

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.

TTL-only expiry is the simplest and bounds staleness, but it serves stale data for up to the TTL after every change. Evicting on write removes the entry so the next read loads fresh data, which is the usual default because it never writes a wrong value into the cache. Putting the new value on write keeps the cache warm but can race, so an older value may overwrite a newer one. Write-through sends writes to cache and store together through one layer, keeping them aligned at the cost of write latency. Most systems combine eviction on write with a TTL as a safety net.

Why this question is asked

Phil Karlton's old joke that cache invalidation is one of the two hard things in computer science survives because it keeps being true. Every cache is a copy, and the strategy we choose for keeping the copy honest decides which bugs we will have. Interviewers ask this comparison to see whether we know the trade-off behind each strategy rather than just its name. In this answer, we will recap what consistency means for a cache, go through each of the four strategies with a small example, look at the race that makes put-on-write risky, and see why the common answer is a combination.

1A Quick Recap: What Consistency Means Here

The database is the source of truth, and the cache holds copies of some of its values. A read from the cache is stale if the database has a newer value. No practical strategy makes staleness impossible across processes without giving up most of the cache's speed, so each strategy is really a promise about how stale a value can be and for how long. A good answer names that promise for each one.

2TTL-Only Expiry

Each entry has a time to live, and nothing else removes it. If a product's price changes at 10:00:05 and its entry was cached at 10:00:00 with a 60 second TTL, readers see the old price until 10:01:00. The promise is simple: no value is older than the TTL. The strategy needs no coordination with writers, which makes it the only option when changes come from somewhere we do not control, such as another team's database or an external feed. It fits data where a bounded delay is acceptable, like exchange rates on a display page.

3Evict on Write

When our code changes the data, it also removes the cache entry. The next read misses and loads the fresh value. In Spring this is @CacheEvict on the update method.

Java
@CacheEvict(cacheNames = "products", key = "#p.id")
public void update(Product p) { repo.save(p); }
find(42); // cache: Product 42 v1
update(product42v2); // cache: entry 42 removed
find(42); // miss: loads v2 from the database, cache: Product 42 v2

This is the usual default because the worst case is an extra database read. The cache never receives a value computed by the writer, so it cannot be filled with something wrong by the write itself. It still has a small race with concurrent readers, especially if the eviction happens before the transaction commits, which is why it is done after commit and paired with a TTL.

4Put on Write and Its Race

Instead of removing the entry, the writer stores the new value, with @CachePut in Spring. The cache stays warm: the next reader gets a hit with the new value. The problem appears with two concurrent writers.

Step throughTwo updates, cache ends up with the older one
Writer ADatabaseWriter BCache
UPDATE price = 10
UPDATE price = 12 (commits last)
put(42, 12)
put(42, 10): delayed, arrives last
cache says 10, database says 12

5 messages in order. Play them, or step through them one at a time.

The database order and the cache order can differ, and nothing reconciles them until the TTL.

The database applied A then B, so it holds 12. But A's cache write was delayed, by a garbage collection pause for example, and arrived after B's. The cache now says 10 and keeps saying it until the TTL. Put on write is reasonable when there is a single writer per key or when values carry a version and the cache refuses older versions; otherwise eviction is safer.

5Write-Through

In write-through, the application writes to one layer that updates both the cache and the store as part of the same operation, so they move together. Some cache products offer this with a writer component behind the cache, for example a JCache CacheWriter or a data grid that persists to a database. Reads always find the latest written value in the cache, and the cache is warm for recently written data.

The costs are write latency, since every write goes to both places, and coupling, since all writes must go through that layer. Any write that bypasses it, such as a batch job or an admin SQL fix, leaves the cache wrong. Spring's cache annotations do not provide write-through by themselves; @CachePut is the nearest equivalent but runs in our code, not in a single layer that owns both writes.

6Choosing and Combining

The table puts the four side by side. In practice, most systems use evict on write, done after the commit, with a TTL as a safety net, because each covers the other's weakness: eviction handles the changes we know about immediately, and the TTL bounds the damage from races, failed evictions and writes we did not know about.

Four strategies compared
StrategyStaleness promiseMain riskChoose when
TTL onlyat most the TTLstale for the whole TTLchanges come from outside our code
Evict on writeuntil the next read, plus small racesextra miss after each writethe default for our own writes
Put on writenone under concurrent writersolder value overwrites newersingle writer per key, or versioned values
Write-throughaligned for writes through the layerwrite latency; bypassing writesa cache layer owns all writes
Evict on write + TTLusually fresh, never older than TTLsmall, boundedmost systems

7Follow-up questions

Why not just use a very short TTL instead of eviction?

A short TTL lowers staleness but also lowers the hit ratio, because every entry expires whether it changed or not. For data that changes rarely, eviction on write lets us keep a long TTL and a high hit ratio while still showing changes immediately. Short TTLs are the right tool when we cannot hook into the writes.

What is the difference between write-through and write-behind?

Write-through updates the store synchronously as part of the write, so when the call returns both are updated. Write-behind updates the cache immediately and writes to the store later, often in batches. Write-behind is faster for writers, but data can be lost if the cache node fails before flushing, so it suits data where that risk is acceptable.

8Conclusion

In this answer, we compared four strategies for keeping a cache consistent with a database. TTL-only expiry is simple and bounds staleness at the TTL. Evict on write removes the entry so the next read loads fresh data, and it is the usual default because the write never puts a wrong value in the cache. Put on write keeps the cache warm but can let an older value overwrite a newer one under concurrent writers. Write-through keeps cache and store aligned through one layer at the cost of write latency and coupling. Most systems combine after-commit eviction with a TTL as a safety net.

What to say in the interviewAbout 90 seconds aloud

Open with

I would frame each strategy by the staleness it promises. TTL-only means every entry simply expires; it needs no coordination and bounds staleness at the TTL, but after a change readers see old data for up to the TTL.

Then, if they want more

It is the right choice when changes come from somewhere I cannot hook into, like an external feed. Evict on write means the update method removes the entry, @CacheEvict in Spring, and the next read loads fresh data.

It is the usual default because the worst case is one extra database read; the writer never puts a value into the cache that might be wrong.

Put on write, @CachePut, stores the new value directly, which keeps the cache warm, but with two concurrent writers the cache writes can arrive in a different order than the database commits, so an older value can overwrite a newer one and stay until the TTL. I would only use it with one writer per key or with versioned values.

Write-through means one layer writes both the cache and the store together, so they stay aligned, at the cost of write latency and the risk that any write bypassing the layer leaves the cache wrong.

In practice I combine eviction on write, done after commit, with a TTL as a safety net for races and writes I do not know about.

About this answer

Last updated
12 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 documentation below. 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 "Compare these strategies for keeping a cache consistent with a database: TTL-only...": https://scrivio-interview-library.netlify.app/databases/caching/ba612ff37b/