Quick revision
The short answer
It tells us optimistic locking worked: the entity has a @Version, and when our transaction tried to update the row, another transaction had already changed or deleted it since we read it, so our UPDATE matched no row. We respond per use case: retry the whole read-modify-write in a new transaction when the operation is safe to repeat, or return 409 Conflict so the user can reload. Then we reduce contention (smaller aggregates, no shared parent updated on every child change, atomic SQL for counters), never catch it inside the same transaction, and measure the rate, because frequent conflicts point to a hot-row design problem.
What to remember
In this answer, we saw that StaleObjectStateException, surfaced by Spring as ObjectOptimisticLockingFailureException, means @Version caught a concurrent change. We chose the response per use case: retry the full read-modify-write in a new transaction when the system makes the decision and it is safe to repeat, and return 409 when a user's stale decision would overwrite someone else's. We saw why catching it in the same transaction fails, and how smaller aggregates, fewer shared-parent updates, atomic SQL for counters and a conflict metric address the cause.
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.
It tells us optimistic locking worked: the entity has a @Version, and when our transaction tried to update the row, another transaction had already changed or deleted it since we read it, so our UPDATE matched no row. We respond per use case: retry the whole read-modify-write in a new transaction when the operation is safe to repeat, or return 409 Conflict so the user can reload. Then we reduce contention (smaller aggregates, no shared parent updated on every child change, atomic SQL for counters), never catch it inside the same transaction, and measure the rate, because frequent conflicts point to a hot-row design problem.
Why this question is asked
Optimistic lock failures under load are alarming in a log, but they are a safety feature doing its job: without them, two users would overwrite each other's changes silently. Interviewers ask this because the response requires judgement. Blindly retrying can repeat side effects, blindly returning errors annoys users, and neither fixes a design that makes everyone write the same row. In this answer, we will recap how @Version works, reproduce the failure with two transactions, decide between retry and conflict, see why catching it in the same transaction fails, and reduce contention at its source.
1A Quick Recap of Optimistic Locking
Optimistic locking assumes conflicts are rare, so it does not lock rows when reading. Instead each row carries a version number, mapped with @Version. When Hibernate writes an update, it includes the version it read in the WHERE clause and increments it in the SET clause.
So the exception means exactly one thing: the row we read is no longer the row in the database. JPA reports it as OptimisticLockException, Hibernate's own type is StaleObjectStateException, and Spring translates both into ObjectOptimisticLockingFailureException, a subclass of OptimisticLockingFailureException, when the exception passes through a repository or the transaction commit.
2Reproducing the Conflict
Two requests withdraw from the same account at nearly the same moment. Both read version 5, both compute a new balance, and both try to write.
6 messages in order. Play them, or step through them one at a time.
The losing transaction is told, instead of silently overwriting.
The second request loses the race. Its UPDATE carries version = 5 in the WHERE clause, but the row is now at version 6, so zero rows match and Hibernate throws. Notice that this is precisely the case where, without @Version, the second request would have overwritten the first withdrawal and the balance would be wrong.
3Deciding: Retry or Return a Conflict
The right response depends on who made the decision that is now stale. If the change is computed by the system from current data, such as adding a line to a balance or reserving one unit of stock, the decision can be remade from fresh data, so a retry is correct. The retry must repeat the whole read-modify-write in a new transaction: re-read the row, re-check the business rules, write again. It is safe only when the operation is idempotent or has no external side effects inside the transaction, such as sending an email or calling a payment provider.
If a human made the decision based on what they saw, such as editing a customer's address on a form that showed version 5, retrying would overwrite whatever the other person changed. Here we return HTTP 409 Conflict with a message like this record was changed by someone else, and let the user reload and decide.
This example uses Spring Retry; Spring Framework 7 also has its own retry support, so check your version. The order matters: the retry advice must wrap the transactional method from outside, so that each attempt starts a fresh transaction and a fresh persistence context. A small random backoff stops the competing requests from colliding again in lockstep.
4Why Catching It Inside the Transaction Fails
A tempting fix is to wrap the save in try and catch inside the same @Transactional method and try again. It does not work. When the exception is thrown, Hibernate marks the transaction for rollback, and the persistence context still holds the stale entity, which may be in an inconsistent state after a failed flush. Reloading it with findById returns the same cached stale instance, not fresh data. The only reliable recovery is to let the transaction roll back and start a new one, which is why the retry belongs outside the transactional boundary.
5Reducing Contention at the Source
Retries treat the symptom. If the log shows many conflicts, the design is making many transactions write the same row. Three patterns cause most of it. The first is an aggregate that is too big: one Order with 200 lines where every line change bumps the order's version means two people editing different lines conflict. Smaller aggregates, or versioning lines independently, remove that. The second is a shared parent updated on every child change, such as a Customer.lastActivity column updated on every order, which turns the customer row into a hot spot; move such fields elsewhere or update them asynchronously.
The third is a counter or balance read into Java and written back. An atomic SQL update lets the database do the arithmetic under its own row lock, with no read in between and nothing to go stale.
Note that a JPQL bulk update bypasses the persistence context and does not increment @Version unless we write that in the statement, so loaded Product entities in the same transaction are now stale. Finally, measure: count these exceptions per endpoint and entity with a metric. A handful a day is optimistic locking working as intended; hundreds per minute on one entity is a hot row that needs one of the redesigns above.
6Follow-up questions
Would pessimistic locking be better here?
Sometimes. SELECT ... FOR UPDATE, via @Lock(PESSIMISTIC_WRITE), makes competing transactions wait instead of fail, which suits short transactions on a row that is genuinely hot. It costs blocking and the risk of deadlocks, so it is a deliberate choice for specific operations, not a general replacement.
Can the exception also mean the row was deleted?
Yes. An update or delete with WHERE id = ? AND version = ? also matches zero rows if another transaction deleted the row. The message says updated or deleted for that reason, and the response should handle both, often with 409 or 404.
How many retries are reasonable?
Usually two or three with a short random backoff. If an operation still conflicts after that, more retries only add load to the hot row; the request should fail and the metric should alert us.
7Conclusion
In this answer, we saw that StaleObjectStateException, surfaced by Spring as ObjectOptimisticLockingFailureException, means @Version caught a concurrent change. We chose the response per use case: retry the full read-modify-write in a new transaction when the system makes the decision and it is safe to repeat, and return 409 when a user's stale decision would overwrite someone else's. We saw why catching it in the same transaction fails, and how smaller aggregates, fewer shared-parent updates, atomic SQL for counters and a conflict metric address the cause.
Open with
It tells me optimistic locking is working. The entity has a @Version, Hibernate's update includes WHERE version equals the value we read, and zero rows matched because another transaction updated or deleted the row in between.
Then, if they want more
Spring translates it to ObjectOptimisticLockingFailureException. How I respond depends on the use case. If the system computes the change from current data, like reserving stock, I retry the whole read-modify-write in a new transaction, two or three attempts with a small random backoff, and only if the operation is safe to repeat, so no emails or payment calls inside it.
If a user made the decision from a stale screen, I return 409 Conflict and let them reload, because a retry would overwrite the other person's change. I'd never catch it and retry inside the same transaction: it's marked rollback-only and the persistence context still holds the stale entity, so the retry has to wrap the transaction from outside.
Then I'd look at why there's contention: an aggregate that's too large, a shared parent row updated on every child change, or a counter read into Java instead of an atomic update like stock = stock - 1 where stock is enough. And I'd put a metric on the rate, because frequent conflicts mean a hot row design problem.
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 "Logs show 'org.hibernate.StaleObjectStateException: Row was updated or deleted by...": https://scrivio-interview-library.netlify.app/databases/jpa-fundamentals/aefbea22e7/