Quick revision
The short answer
We loop up to three times, and in each attempt we call transactionTemplate.execute(status -> doWork()), so every attempt is a brand-new transaction that reads fresh data. We catch ObjectOptimisticLockingFailureException, or its parent OptimisticLockingFailureException, outside the transaction, wait with a backoff plus random jitter, and rethrow after the last attempt. Declarative retry with Spring Framework 7's @Retryable or Spring Retry also works, as long as the retry wraps the transaction from outside.
What to remember
In this answer, we saw that an optimistic lock failure means our transaction used outdated data, and the only way to get fresh data is a new transaction. The retry loop therefore sits outside the transaction and calls TransactionTemplate on each attempt, catches OptimisticLockingFailureException, waits with exponential backoff and jitter, and rethrows after the third attempt. Declarative retry works on the same principle when the retry wraps the transactional proxy from outside.
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.
We loop up to three times, and in each attempt we call transactionTemplate.execute(status -> doWork()), so every attempt is a brand-new transaction that reads fresh data. We catch ObjectOptimisticLockingFailureException, or its parent OptimisticLockingFailureException, outside the transaction, wait with a backoff plus random jitter, and rethrow after the last attempt. Declarative retry with Spring Framework 7's @Retryable or Spring Retry also works, as long as the retry wraps the transaction from outside.
Why this question is asked
Optimistic locking detects conflicts instead of preventing them, which means some transactions will fail and need to run again. The retry looks trivial, but there is one rule that many implementations get wrong: the retry has to happen outside the failed transaction. Interviewers use this question to check that we know why. In this answer, we will recap what the exception means, see why retrying inside the transaction cannot work, write the retry loop with backoff and jitter, and then do the same declaratively.
1A Quick Recap: What the Exception Means
With optimistic locking, each row has a version column, mapped with @Version. When Hibernate updates the row, it adds where version = ? with the version it read. If another transaction changed the row in between, no row matches, and Hibernate throws an exception at flush or commit. Spring translates it into ObjectOptimisticLockingFailureException, a subclass of OptimisticLockingFailureException.
The exception tells us that our transaction worked on data that is now outdated. The right reaction is to read the current data again and redo the work, which is exactly what a new transaction does.
2Why Retrying Inside the Transaction Does Not Help
A tempting mistake is to put the retry inside a @Transactional method, around the code that failed.
Three things go wrong. The persistence context, Hibernate's cache of entities loaded in this transaction, still holds the stale Account, so findById() returns the same old object instead of reading the row again. Hibernate's session is unusable after this exception anyway. And Spring has marked the transaction rollback-only when the exception passed through the repository, so even if a later attempt succeeded, the commit would fail. The only clean way to read fresh data is to throw this transaction away and start a new one.
3The Retry Loop Around TransactionTemplate
So the loop lives outside the transaction, and each attempt calls the template. The calling method must not itself be @Transactional, or the template would join the outer transaction and we would be back to the broken case.
- Start a new transactionNothing cached from earlier attempts
- Read the row and apply the changeFresh version number
- Commit succeeded?YesReturn to the callerNoCatch the conflict outside
- Attempts left?YesWait with backoff and jitter, start againNoRethrow the exception
4 steps in order. Play them, or step through them one at a time.
The retry decision is always made outside a transaction.
Notice that the catch is on the broader OptimisticLockingFailureException. It covers the JPA case and also other Spring data access code that reports the same kind of conflict. The backoff grows with each attempt, and the jitter, a random part of the wait, matters as much as the growth: two requests that collided once would collide again if they both waited exactly 50 milliseconds.
4Doing It Declaratively
Spring Framework 7 adds its own @Retryable annotation in org.springframework.resilience.annotation, enabled with @EnableResilientMethods; Spring Retry offers a similar @Retryable for earlier versions. Check your version for the exact attribute names. The rule stays the same: the retry interceptor must run outside the transaction interceptor. The safest way is to put @Retryable on a method of one bean that calls a @Transactional method on another bean, so each retry goes through the transactional proxy again.
Putting both annotations on the same method can work if the interceptor order is configured so that retry is outermost, but the two-bean version makes the order impossible to get wrong.
5Follow-up questions
Should every optimistic lock failure be retried?
No. A retry is right when the work can be recomputed from fresh data, such as adding points. When a user edited a form based on what they saw, retrying would silently overwrite the other person's change with the user's old view, so there we report a conflict instead.
Is it safe to retry if the transaction also calls another service?
Only if that call is idempotent or outside the retried block. Each attempt would repeat the call, so a payment or an email inside the transaction would be sent up to three times. Keep side effects outside the retry or make them idempotent with a request id.
What about serialization failures under SERIALIZABLE isolation?
They are retried the same way, a new transaction per attempt. In Spring they usually arrive as CannotAcquireLockException or another PessimisticLockingFailureException subclass, depending on the driver and version, so check what your stack throws and include it in the retry condition.
6Conclusion
In this answer, we saw that an optimistic lock failure means our transaction used outdated data, and the only way to get fresh data is a new transaction. The retry loop therefore sits outside the transaction and calls TransactionTemplate on each attempt, catches OptimisticLockingFailureException, waits with exponential backoff and jitter, and rethrows after the third attempt. Declarative retry works on the same principle when the retry wraps the transactional proxy from outside.
Open with
The key point is that each retry has to be a new transaction. If I retry inside the same transaction, the persistence context still holds the stale entity, Hibernate's session is no longer reliable after the exception, and Spring has already marked the transaction rollback-only, so it will fail at commit anyway.
Then, if they want more
So I write a loop in a method that is not transactional. For attempt one to three, I call transactionTemplate.executeWithoutResult with a lambda that loads the account and applies the change. The version check happens at commit.
If I catch OptimisticLockingFailureException, which is the parent of ObjectOptimisticLockingFailureException, I check whether attempts are left; if yes I sleep with exponential backoff, 50 then 100 milliseconds, plus random jitter so the two colliding requests do not collide again, and if not I rethrow so the caller can report a conflict.
Declaratively, Spring Framework 7 has its own @Retryable and older versions can use Spring Retry, but I put the retry on one bean and the @Transactional method on another, so every retry goes through the transaction proxy again. I would only retry work that can be recomputed from fresh data, and keep non-idempotent side effects out of the retried block.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Spring Framework 7
- 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 Data JPA reference, Hibernate ORM documentation, Spring Framework reference, Transaction management
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 "Write code that retries a whole transaction up to three times when an...": https://scrivio-interview-library.netlify.app/databases/transactions/c60957726a/