Quick revision
The short answer
@CachePut stores the method's result as soon as the method returns, but the transaction only commits after that, and the constraint violation is raised at commit when Hibernate flushes the insert. So the cache is updated first and the database refuses second. The fix is to make the cache transaction-aware so the put waits for a successful commit; flushing inside the method helps catch constraint errors earlier but still does not cover failures at commit, and shorter TTLs only limit the damage.
What to remember
In this answer, we saw that @CachePut wrote the account to the cache when the method returned, while the INSERT was only flushed at commit, where the constraint violation rolled the transaction back and left the cache wrong for its whole TTL. The order of the two interceptors decides whether this happens, so we removed the dependence on order with a transaction-aware cache manager, saw that saveAndFlush and short TTLs are partial measures, and added a test that forces a rollback and checks the cache.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
@CachePut stores the method's result as soon as the method returns, but the transaction only commits after that, and the constraint violation is raised at commit when Hibernate flushes the insert. So the cache is updated first and the database refuses second. The fix is to make the cache transaction-aware so the put waits for a successful commit; flushing inside the method helps catch constraint errors earlier but still does not cover failures at commit, and shorter TTLs only limit the damage.
Why this question is asked
This bug is dangerous because nothing looks wrong in the code. The method saves an account and caches it, the annotations are correct, and in normal operation it works. Only when a commit fails does the cache start serving an account that does not exist, and with a one-hour TTL the wrong data stays visible long after the error. Interviewers use it to test whether we understand the order in which Spring's proxies run and when Hibernate actually talks to the database. In this answer, we will reproduce the bug, follow the order of events, look at how the interceptors are ordered, then fix it and add a test that proves the fix.
1A Quick Recap of the Moving Parts
Both annotations are applied through a Spring proxy, a wrapper object generated at runtime that runs extra code around our method. @Transactional adds a transaction interceptor that begins a transaction before the method and commits or rolls back after it. @CachePut adds a cache interceptor that always runs the method and then stores the result in the cache under the given key, here #result.id, the id of the returned account.
The third part is Hibernate's flush. When we call save() on a new entity, Hibernate usually does not send the INSERT immediately. It queues it and sends it when it flushes, which happens at commit at the latest. A database constraint, such as a unique email, is checked when the INSERT reaches the database, so the violation is often reported only at commit.
2Reproducing the Problem
Here is the method from the question, called for an email that already exists.
Notice that the id exists even though the row does not. With an identity column Hibernate might insert early to get the id, but with a sequence or UUID generator the id is assigned in memory and the INSERT waits for the flush, so the method returns normally and the caching happens.
3Following the Order of Events
In this setup the transaction interceptor is the outer layer and the cache interceptor the inner one. The call enters the transaction interceptor, which begins a transaction, then the cache interceptor, which calls our method. The method returns an Account. The cache interceptor stores it under its id. Only then does control return to the transaction interceptor, which commits, flushes the INSERT and gets the constraint violation. The transaction rolls back, the exception reaches the caller, but the cache put has already happened and nothing undoes it.
10 messages in order. Play them, or step through them one at a time.
The cache was written while the transaction was still open, so the rollback cannot reach it.
So the bug is an ordering problem, not a caching or Hibernate bug. Any side effect that is not part of the transaction and happens before commit has the same risk: sending a message, calling another service, or writing to a cache.
4What Order Do the Interceptors Run In?
Both @EnableCaching and @EnableTransactionManagement have an order attribute, and both default to the lowest precedence. When two advisors have the same order, the one that wraps the other is not something we should rely on; it depends on how the advisors were registered. If the cache interceptor happened to be the outer one, the commit would fail before the put and the bug would hide, which is why this kind of bug can appear after an unrelated configuration change.
We could set explicit orders so the cache interceptor is always outside the transaction. That works for @CachePut, but it is fragile and easy to undo by accident. A fix that does not depend on the order is better.
5Fix: Make the Put Wait for the Commit
A transaction-aware cache delays put and evict calls made inside a transaction until after a successful commit, and drops them on rollback. We enable it for the whole cache manager.
Now the order of the interceptors no longer matters. Even when the cache interceptor runs first, the decorator only registers the put, and the transaction manager runs it after the commit succeeds.
Two partial measures are worth knowing. Calling saveAndFlush() inside the method sends the INSERT before the method returns, so a constraint violation throws inside the method and @CachePut never runs. That catches this case, but a commit can still fail for other reasons, such as a deferred constraint or a lost connection, so it is not a complete fix. A shorter TTL limits how long wrong data survives but does not fix the ordering at all.
6Proving the Fix With a Test
We add an integration test that forces the failure and checks the cache afterwards. It uses a real database, for example with Testcontainers, so the constraint is real.
The test fails before the fix and passes after it, which is exactly what we want from a regression test. It also protects us if someone later rebuilds the cache manager without transactionAware().
7Follow-up questions
What order does Spring use for the cache and transaction interceptors?
Both are advisors ordered by the order attribute of @EnableCaching and @EnableTransactionManagement, which default to the lowest precedence. A lower order value runs as the outer layer. With equal values the nesting depends on registration, so we should either set the orders explicitly or, better, use a transaction-aware cache so the result does not depend on the order.
Would @CacheEvict have the same problem?
Yes, in a quieter form. An eviction before commit lets another request reload the old row and cache it again before our commit, so the cache ends up stale. The transaction-aware decorator delays evictions too, which removes most of that window.
Why not just catch the exception and evict the key?
It works for this one path, but it spreads cache repair logic into every caller and misses failures that happen elsewhere. Letting the transaction decide when cache changes apply is simpler and covers every method using that cache manager.
8Conclusion
In this answer, we saw that @CachePut wrote the account to the cache when the method returned, while the INSERT was only flushed at commit, where the constraint violation rolled the transaction back and left the cache wrong for its whole TTL. The order of the two interceptors decides whether this happens, so we removed the dependence on order with a transaction-aware cache manager, saw that saveAndFlush and short TTLs are partial measures, and added a test that forces a rollback and checks the cache.
Open with
The cache is written before the transaction finishes. With the transaction interceptor outside the cache interceptor, the method returns an account whose INSERT is still queued in Hibernate, @CachePut immediately stores it under its id, and only then does the transaction interceptor commit.
Then, if they want more
The flush at commit hits the unique constraint, the transaction rolls back, but nothing undoes the cache put, so readers see the account for the one-hour TTL. Both interceptors default to the lowest precedence, so which one is outside is not something I want to rely on. My fix is to make the cache manager transaction-aware, with RedisCacheManager.builder().transactionAware() or TransactionAwareCacheManagerProxy.
Then the put is registered as an afterCommit callback and simply dropped on rollback, whatever the interceptor order. I would mention two partial measures: saveAndFlush makes the constraint fail inside the method so the put never runs, but a commit can still fail for other reasons, and a shorter TTL only shortens the damage.
Finally I would add an integration test against a real database that forces the constraint violation and asserts that the cache has no entry for that id.
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.
- Official documentation
- Spring Framework reference, Cache abstraction
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 method annotated with @Transactional and @CachePut(cacheNames = "accounts", key =...": https://scrivio-interview-library.netlify.app/databases/caching/c85c9087f4/