Scrivio Interview library
ScenarioIntermediate6 min read · updated 12 November 2026

An order service method annotated @Transactional and @CacheEvict(cacheNames = "orders", key = "#id") updates an order. Under load, readers sometimes see the old order for the whole TTL after the update succeeded. Explain the race and how to fix it.

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.

Depending on the order of the two interceptors, the cache eviction can run when the method returns but before the transaction commits. In that gap a concurrent reader misses the cache, reads the old committed row from the database and puts it back, and when the commit lands the cache holds the old order until the TTL expires. The fix is to make cache operations transaction-aware, with TransactionAwareCacheManagerProxy or transactionAware() on the RedisCacheManager builder, so evictions run after commit; an after-commit event listener and short TTLs are alternatives and safety nets.

Why this question is asked

This bug is a classic because each piece is correct on its own. The update is transactional, the eviction is there, and in a single-user test everything works. Only under concurrent load does a stale order appear, and then it stays for the whole TTL, which makes it look like eviction is broken. Interviewers ask it to see whether we can reason about two concurrent timelines and about when a commit really happens. In this answer, we will recap how the two annotations wrap the method, walk through the race step by step, fix it with transaction-aware caching, look at an event-based alternative, and see why even after-commit eviction leaves a smaller gap.

1A Quick Recap: Two Interceptors Around One Method

Both @Transactional and @CacheEvict are applied by proxies: a wrapper object Spring generates around our bean, which runs extra logic before and after our method. When a method has both annotations, the same proxy runs two interceptors, the transaction interceptor and the cache interceptor, one inside the other.

The order matters. If the transaction interceptor is outside, the sequence is: begin transaction, then the cache interceptor runs our method and evicts the entry, then the transaction commits. If the cache interceptor is outside, the transaction commits first and the eviction happens afterwards. Both advisors have the lowest precedence by default, so unless we set an order explicitly, we should not assume which one wins. And even when committing first, the database commit is the moment other transactions can see the new row, so anything that happens before it sees the old one.

2Walking Through the Race

Take the ordering where eviction runs inside the transaction. Writer and reader run at the same time on different threads, perhaps on different instances.

Step throughEviction before commit lets a reader put the old row back
WriterCacheDatabaseReader
BEGIN; UPDATE order 7 (status SHIPPED)
evict(7), method returned
get(7)
miss
SELECT order 7
status PAID: old committed row
put(7, PAID)
COMMIT: SHIPPED now visible
later reads: PAID until TTL

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

The eviction worked; the reader simply refilled the cache from data that was about to change.

Notice the key step: the reader's SELECT runs after the eviction but before the commit. Under the default READ COMMITTED isolation, it cannot see the uncommitted update, so it reads PAID and stores it. When the writer finally commits, nobody evicts again. Every later reader hits the cache and sees PAID until the TTL expires or the order is updated again. With a one hour TTL, that is an hour of stale data from a race that lasted a few milliseconds. The busier the order, the more likely a reader falls into that gap.

3Fix 1: Make the Cache Transaction-Aware

Spring has a decorator for exactly this case. TransactionAwareCacheDecorator wraps a Cache, and when a Spring-managed transaction is active it delays put and evict until the transaction has committed, using a transaction synchronization callback. If the transaction rolls back, the deferred operations are dropped. TransactionAwareCacheManagerProxy applies the decorator to every cache a manager returns, and RedisCacheManager can do it through its builder.

Java
// Redis: one builder flag
@Bean
RedisCacheManager cacheManager(RedisConnectionFactory cf) {
return RedisCacheManager.builder(cf)
.cacheDefaults(RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofMinutes(10)))
.transactionAware() // puts and evicts wait for the commit
.build();
}
// Any other CacheManager: wrap it
@Bean
CacheManager cacheManager() {
CaffeineCacheManager target = new CaffeineCacheManager("orders");
return new TransactionAwareCacheManagerProxy(target);
}
// The service does not change:
@Transactional
@CacheEvict(cacheNames = "orders", key = "#id")
public void ship(long id) { repo.markShipped(id); } // evict(7) now runs after COMMIT

Now the order of the interceptors no longer matters. Even if eviction is requested inside the transaction, it is executed only after the new row is visible, so a reader that misses afterwards loads SHIPPED. Note one detail: eviction requested with beforeInvocation = true uses an immediate evict, so leave that attribute at its default when we want after-commit behaviour. Check your version for which Cache methods the decorator defers.

4Fix 2: Evict From an After-Commit Event Listener

If we prefer to keep cache handling out of the service method, we publish an event inside the transaction and evict from a listener that only runs once the commit has succeeded.

Java
public record OrderChanged(long id) {}
@Transactional
public void ship(long id) {
repo.markShipped(id);
events.publishEvent(new OrderChanged(id)); // held until the transaction ends
}
@Component
class OrderCacheEvictor {
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
void on(OrderChanged e) { cacheManager.getCache("orders").evict(e.id()); }
}

This has the same effect as the transaction-aware cache, and it makes the invalidation explicit and easy to extend, for example to also publish the change to other instances. Whichever fix we choose, keeping the TTL short for data that has this risk limits the damage of any race we did not think of.

5Follow-up questions

Does after-commit eviction fully remove the race?

No, it makes the window much smaller but does not close it. A reader can miss the cache and read the old row just before the commit, then be delayed, by a garbage collection pause for example, while the writer commits and evicts. The reader then puts the old value after the eviction, and it stays until the TTL. Common mitigations are a short TTL as an upper bound, a second delayed eviction a short time after the first, or storing a version with each value and refusing to put an older version over a newer one. For data that must never be stale, read from the database.

Why not use @CachePut with the new order instead of evicting?

Putting the new value has its own race: two concurrent updates can complete in one order and write the cache in the other, leaving the older value cached. And inside a transaction, a put before commit could publish a value that is later rolled back. Eviction is the safer default because the worst case is an extra database read, not a wrong value. If we put, it should be after commit, ideally with a version check.

Can we fix it by ordering the advisors so the cache interceptor is outside?

It helps, because the commit then happens before the eviction, and we can set it with the order attribute of @EnableCaching and @EnableTransactionManagement. But it relies on configuration that is easy to change by accident, and it does not help when the transaction was started by an outer caller, because then our method returns long before the real commit. The transaction-aware cache is tied to the actual commit, so it is the more robust fix.

6Conclusion

In this answer, we saw how @Transactional and @CacheEvict on one method can evict the entry before the transaction commits. A concurrent reader then misses, reads the old committed row and stores it again, and that stale entry survives until the TTL. Making the cache transaction-aware, with transactionAware() on the RedisCacheManager builder or a TransactionAwareCacheManagerProxy, defers the eviction until after commit, and an AFTER_COMMIT event listener achieves the same thing explicitly. Even then a small race remains, so short TTLs, a delayed second eviction or version checks are the safety net for data with this risk.

What to say in the interviewAbout 90 seconds aloud

Open with

The race is between the eviction and the commit. Both annotations are applied by interceptors on the same proxy, and depending on their order, the cache eviction can run when the method returns but before the transaction commits.

Then, if they want more

In that gap a reader misses the cache, queries the database, and under read committed it still sees the old committed row, so it puts the old order back into the cache. Then the writer commits, nobody evicts again, and every reader gets the old order until the TTL expires.

Even with the opposite ordering, if an outer caller owns the transaction, the commit happens later than our method's return. The fix is to tie cache operations to the commit. Spring has TransactionAwareCacheDecorator, applied through TransactionAwareCacheManagerProxy or the transactionAware() option on the RedisCacheManager builder, which defers puts and evicts until after a successful commit and drops them on rollback.

An alternative is to publish an event and evict in a @TransactionalEventListener with phase AFTER_COMMIT. I would also say honestly that after-commit eviction does not close the race completely: a reader that read just before the commit can still put the old value after the eviction.

So for this data I would keep the TTL short, and for critical cases add a delayed second eviction or version checks.

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 "An order service method annotated @Transactional and @CacheEvict(cacheNames = "orders"...": https://scrivio-interview-library.netlify.app/databases/caching/ac5bc420db/