Scrivio Interview library
DebuggingFoundations7 min read · updated 12 November 2026

A Spring Boot service uses @Cacheable on getProduct(id) with Redis and @CacheEvict on updateProduct. After updates, users sometimes still see the old price for minutes. Both methods are @Transactional. What could cause this?

The most likely cause is that @CacheEvict runs before the transaction commits: a concurrent getProduct misses the cache, reads the old row that is still committed, and puts it back into Redis, where it stays until the TTL. We fix it by evicting after commit, with a transaction-aware cache manager, @TransactionalEventListener(phase = AFTER_COMMIT), or a transaction synchronization callback. We also check for self-invocation that bypasses the proxy so the eviction never runs, key expressions that differ between @Cacheable and @CacheEvict, and other caches such as a local Caffeine layer or a CDN, with TTLs as the safety net.

Why this question is asked

Stale prices are a bug users notice and businesses care about, and this one is tricky because each annotation looks correct on its own. The problem lives in how Spring's caching and transaction proxies interact, and in timing that only shows under concurrent traffic. Interviewers ask it because the answer shows whether we understand proxies, transaction boundaries and the cache-aside race in practice. In this answer, we will recap how the two annotations work together, reproduce the race, fix it with after-commit eviction, and then go through the other three causes: self-invocation, key mismatch and other cache layers.

1A Quick Recap of the Setup

Both @Cacheable and @Transactional work through a proxy, a wrapper object Spring generates around our bean at startup. When another bean calls productService.getProduct(7), it actually calls the proxy, which runs interceptors around the real method. The caching interceptor checks Redis, and on a miss calls the method and stores the result. The transaction interceptor begins a transaction before the method and commits after it.

For updateProduct, both interceptors wrap the call. The order matters. If the caching interceptor runs inside the transaction interceptor, which is common because both have the same default order, then @CacheEvict, which by default runs after the method returns, evicts the entry while the transaction is still open. The commit only happens afterwards, when control returns to the transaction interceptor.

2Reproducing the Race

Here is the timeline that produces the stale price. Notice that the database read in step 3 returns the old price, because the writer's update is not committed yet and PostgreSQL's default READ COMMITTED isolation only shows committed data.

Java
// Writer thread: updateProduct(p7 with price 12)
// 1. tx begins, UPDATE product SET price = 12 WHERE id = 7 (not committed)
// 2. @CacheEvict removes products::7 from Redis
// Reader thread: getProduct(7)
// 3. Redis miss -> SELECT price FROM product WHERE id = 7 -> 10 (old, committed)
// 4. puts products::7 = price 10 into Redis
// Writer thread:
// 5. tx commits -> database now says 12
// Every read for the next TTL period -> 10 <- the stale price
Step throughEviction before commit
WriterDatabaseRedisReader
UPDATE price = 12 (uncommitted)
evict products::7
get products::7: miss
SELECT product 7
price 10 (last committed)
put products::7 = 10
COMMIT
later reads: 10 until TTL

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

The eviction did run, but too early. Any read between the eviction and the commit refills the cache with the old row. Under load, with many readers of popular products, that window is hit regularly, which matches the symptom of sometimes, for minutes: minutes is the TTL.

3Fix: Evict After the Commit

The fix is to move the eviction after the commit, so any read after the eviction sees the new row. Spring offers a direct way: a transaction-aware cache manager, which wraps each cache so that puts and evictions inside a transaction are deferred until after a successful commit, and are skipped on rollback.

Java
@Bean
RedisCacheManager cacheManager(RedisConnectionFactory cf) {
return RedisCacheManager.builder(cf)
.cacheDefaults(RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofMinutes(5)))
.transactionAware() // evict and put run after commit
.build();
}
// Alternative: evict explicitly after commit
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
public void on(ProductUpdated e) {
cacheManager.getCache("products").evict(e.productId());
}

The second option publishes a ProductUpdated event with ApplicationEventPublisher inside updateProduct and evicts in a listener that Spring only calls after the commit. A TransactionSynchronization registered with TransactionSynchronizationManager does the same at a lower level.

But there is a catch: after-commit eviction narrows the race without fully closing it. A reader that read the old row just before the commit can still put it after the eviction. That window is much smaller, microseconds rather than the whole transaction, and a short TTL bounds it. For prices that must never be stale, a second delayed eviction or versioned cache values close it.

4Other Cause: Self-Invocation Skips the Proxy

If the update goes through another method of the same bean, the eviction never runs at all. A call on this goes straight to the real object, not through the proxy, so no interceptor sees it.

Java
@Service
class ProductService {
@Transactional
public void applyDiscount(long id, BigDecimal pct) {
Product p = repo.findById(id).orElseThrow();
p.discount(pct);
updateProduct(p); // this.updateProduct(): proxy bypassed
}
@CacheEvict(cacheNames = "products", key = "#product.id")
public void updateProduct(Product product) { repo.save(product); }
}
// applyDiscount(7, 10%) -> DB updated, products::7 NOT evicted

We confirm it by logging cache operations, for example logging.level.org.springframework.cache=TRACE, and seeing no eviction for the update path. The fix is to call the method through the proxy, by moving it to another bean, or to evict explicitly with the CacheManager in the outer method.

5Other Causes: Key Mismatch and Other Caches

The annotations must compute the same key. If @Cacheable uses the default key, the method parameter 7 of type long, and @CacheEvict uses key = "#product.id" returning an Integer or a String, the entries may be stored under different keys, depending on how the key serializer turns them into Redis keys. The eviction then removes a key that does not exist. Checking the actual Redis keys with redis-cli, for example SCAN 0 MATCH products*, shows whether both sides agree; an explicit key expression on both annotations, with the same type, avoids the trap.

Finally, Redis may not be the only cache. A local Caffeine cache in each pod, a two-level cache library, an HTTP cache in front of the API or a CDN caching product pages for several minutes will all keep serving the old price after Redis is correct. Each layer needs its own invalidation, or a TTL short enough for the business, because TTLs are the safety net that bounds every cause we have discussed.

6Follow-up questions

Why might deleting the cache entry be safer than writing the new value into it?

Because a put can store a value that is wrong in ways an eviction cannot. If we write the new price into the cache before the commit and the transaction rolls back, the cache shows a price that never existed. If two updates run concurrently, their puts can arrive in the opposite order to their commits and leave the older price cached. Evicting avoids both: the next read loads whatever is actually committed. That is why @CacheEvict is the usual choice for updates, and @CachePut needs more care.

Does setting beforeInvocation = true on @CacheEvict help?

No, it makes it worse. It evicts before the method even runs, so the window in which a reader can re-cache the old row covers the entire method and transaction. The goal is to evict as late as possible, after the commit.

How would you verify the fix?

With an integration test using Testcontainers for PostgreSQL and Redis: start an update transaction, pause it after the update, run a read on another thread, then commit, and assert that a later read returns the new price. Before the fix the test fails; with a transaction-aware cache manager it passes.

7Conclusion

In this answer, we saw that the stale price comes mainly from @CacheEvict running inside the transaction, before the commit, so a concurrent read refills the cache with the old committed row until the TTL expires. Evicting after commit, with a transaction-aware RedisCacheManager, an AFTER_COMMIT transactional event listener or a transaction synchronization, fixes the main window. We also checked for self-invocation that bypasses the proxy, key expressions that differ between the two annotations, and other cache layers such as Caffeine or a CDN, with TTLs bounding staleness everywhere.

What to say in the interviewAbout 90 seconds aloud

Open with

My first suspect is the order of the eviction and the commit. Both annotations work through Spring proxies, and commonly the cache interceptor runs inside the transaction, so CacheEvict removes the entry before the transaction commits.

Then, if they want more

If a user reads that product in between, getProduct misses Redis, reads the database, and gets the old price because the update is not committed yet, then puts that old price back into the cache. It stays there until the TTL, which explains minutes of stale prices only some of the time.

The fix is to evict after commit: configure the RedisCacheManager as transaction aware, so evictions are deferred until after a successful commit, or publish an event and evict in a TransactionalEventListener with phase AFTER_COMMIT. That still leaves a tiny race, so a short TTL stays important. Then I would check three other causes.

Self-invocation: if updateProduct is called from another method in the same bean, the call bypasses the proxy and the eviction never runs, which I can see with cache trace logging. Key mismatch: the Cacheable and CacheEvict keys must produce the same Redis key, including the type, so I would look at the actual keys in Redis.

And other caches: a local Caffeine layer, an HTTP cache or a CDN can serve the old price even when Redis is correct, so each needs invalidation or a TTL.

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 "A Spring Boot service uses @Cacheable on getProduct(id) with Redis and @CacheEvict on...": https://scrivio-interview-library.netlify.app/spring-boot/distributed-data/057fcd4fa8/