Quick revision
The short answer
Both requests read the same balance, each adds its own amount in Java, and each writes back its result, so the second write overwrites the first: a lost update. Three fixes are optimistic locking with @Version plus a retry, a PESSIMISTIC_WRITE lock when reading so the second request waits, and an atomic SQL update, update account set balance = balance + :amount where id = :id, which lets the database do the arithmetic. READ COMMITTED isolation, the default in PostgreSQL, does not prevent this on its own.
What to remember
In this answer, we saw that the read-modify-write code loses a deposit because both requests compute from the same stale balance and the second write replaces the first, and that READ COMMITTED does not detect it. We fixed it three ways: @Version with a retry detects the conflict, a PESSIMISTIC_WRITE lock makes the second request wait, and an atomic SQL update lets the database apply the change to the current value. The atomic update is the simplest when the change is arithmetic.
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.
Both requests read the same balance, each adds its own amount in Java, and each writes back its result, so the second write overwrites the first: a lost update. Three fixes are optimistic locking with @Version plus a retry, a PESSIMISTIC_WRITE lock when reading so the second request waits, and an atomic SQL update, update account set balance = balance + :amount where id = :id, which lets the database do the arithmetic. READ COMMITTED isolation, the default in PostgreSQL, does not prevent this on its own.
Why this question is asked
This is the textbook concurrency bug, and it appears in real code all the time because each line looks correct. Interviewers like it at the five-year level because a good answer explains the exact interleaving, knows why the transaction does not help, and can offer more than one fix with reasons for choosing. In this answer, we will reproduce the interleaving, see why isolation does not save us, and then implement and compare the three fixes.
1Reproducing the Lost Update
Let the balance be 100. Request A deposits 50 and request B deposits 30 at the same moment. The correct result is 180.
5 messages in order. Play them, or step through them one at a time.
Both writes succeed; the second one was based on a stale read.
Each request computed its new balance from a value it read earlier. B read 100 before A's commit, so B's calculation never included A's 50. When B writes 130, it replaces 150 entirely. No error is raised; both transactions committed successfully. That silence is what makes the bug expensive.
2Why READ COMMITTED Does Not Prevent It
READ COMMITTED means each statement sees only data that was committed before the statement started. That stops us from reading another transaction's uncommitted changes, but it says nothing about a value we read earlier going stale before we write. B's read at t2 was correct at that moment, and B's write at t4 is a plain update by id with a value computed in Java. The database has no idea that 130 was derived from 100. In PostgreSQL, REPEATABLE READ would detect the conflict and abort B with a serialization error, and SERIALIZABLE would too, but then the code needs a retry anyway, and most applications run at READ COMMITTED. So we need a fix that tells the database about the dependency.
3Fix 1: Optimistic Locking With @Version and Retry
We add a version column. Hibernate then writes update account set balance = ?, version = ? where id = ? and version = ?, using the version it read. B's update matches no row, because A already moved the version on, and Hibernate raises an optimistic lock failure, which Spring reports as ObjectOptimisticLockingFailureException. We retry B's whole transaction, which reads 150 and writes 180.
This holds no locks and is ideal when conflicts are rare. Under heavy contention on one account, many attempts fail and retry, so it is not the best choice for a very busy row.
4Fix 2: A Pessimistic Write Lock When Reading
Here B waits instead of failing. We read the account with SELECT ... FOR UPDATE, so the read itself takes a row lock that lasts until commit.
The method must be @Transactional, otherwise the lock would be released immediately. It suits frequent conflicts where waiting is cheaper than retrying, but every waiting request holds a connection, so the transaction must be short, and locking several accounts needs a consistent order to avoid deadlocks.
5Fix 3: An Atomic SQL Update
The simplest fix moves the arithmetic into the database. Instead of reading, adding in Java and writing, we send one statement that adds to whatever the current value is.
The database evaluates balance + 30 against the latest committed value while holding the row lock for just that statement, so no update can be lost and the lock is held for about a millisecond. The trade-offs are that the logic lives in the query instead of the entity, an already loaded entity in the persistence context is now stale (clearAutomatically = true on @Modifying clears it), and rules that need more than arithmetic, such as checking a daily limit, need a WHERE condition or one of the other fixes.
6Follow-up questions
Which fix would you choose for a bank account?
For a simple deposit, the atomic update: it is correct, fast and holds the lock briefly. For a withdrawal with rules, the same update with a condition such as and balance >= :amount still works. If the business logic is complex, a pessimistic lock on a hot account or optimistic locking with retry on a quiet one.
Would synchronized in Java fix it?
Only with a single instance of the application, and even then it serialises every account, not just one. With two instances behind a load balancer, the two requests run in different JVMs and synchronized does nothing. The fix must be in the database.
How would you test that the fix works?
With a concurrency test against a real database, for example Testcontainers PostgreSQL: start 20 threads that each deposit 10 into the same account at the same moment, wait for all of them, and assert the balance is exactly 200. The original code fails this test reliably.
7Conclusion
In this answer, we saw that the read-modify-write code loses a deposit because both requests compute from the same stale balance and the second write replaces the first, and that READ COMMITTED does not detect it. We fixed it three ways: @Version with a retry detects the conflict, a PESSIMISTIC_WRITE lock makes the second request wait, and an atomic SQL update lets the database apply the change to the current value. The atomic update is the simplest when the change is arithmetic.
Open with
This is a lost update. Both requests read the balance, say 100, before either writes. A adds 50 and writes 150, B adds 30 to the 100 it read and writes 130, and B's write simply replaces A's.
Then, if they want more
Both commit without errors, so A's deposit vanishes. The transaction does not help because at READ COMMITTED each statement only sees committed data; it does not notice that a value I read earlier went stale, and the update by id has no idea it was computed from 100. I would give three fixes.
First, optimistic locking: add @Version, so the update includes where version equals the one I read; B's update matches zero rows, Spring throws ObjectOptimisticLockingFailureException, and I retry B in a new transaction, which then writes 180. Good when conflicts are rare.
Second, pessimistic locking: read with a @Lock PESSIMISTIC_WRITE query inside the transaction, which is SELECT FOR UPDATE, so B waits until A commits and then reads 150. Good for busy rows, with short transactions.
Third, and simplest here, an atomic update: update account set balance = balance + :amount where id = :id, so the database adds to the current value under a very short lock. I would pick the atomic update for a deposit, and prove it with a concurrent test against a real database.
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 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 "Two requests run this code at the same time for the same account:": https://scrivio-interview-library.netlify.app/databases/locking-and-concurrency-control/b1c3acefcf/