Video in progress
What does this balance update code break with parallel requests, and how do you fix it?
@Transactional
public void withdraw(long accountId, long amount) {
Account a = accountRepo.findById(accountId).orElseThrow();
if (a.getBalance() < amount) throw new InsufficientFundsException();
a.setBalance(a.getBalance() - amount);
accountRepo.save(a);
}
The code reads the value, changes it in Java and writes it back — two parallel requests read the same old balance and one overwrites the other's result (a lost update). The fix is an atomic UPDATE ... SET balance = balance - ? WHERE balance >= ?, an optimistic version, or SELECT ... FOR UPDATE.
📖 Answer
The scenario: the balance is 100,000. Two withdrawals at once — 70,000 and 50,000.
T1: read 100,000 T2: read 100,000
T1: checked, wrote 30,000 T2: checked, wrote 50,000
The result: 120,000 was withdrawn and the balance is 50,000. @Transactional doesn't help here — PostgreSQL's default READ COMMITTED isolation doesn't protect against a read-then-write race like this.
Way 1 — an atomic UPDATE (the simplest and fastest):
@Modifying
@Query("update Account a set a.balance = a.balance - :amt " +
"where a.id = :id and a.balance >= :amt")
int withdraw(@Param("id") long id, @Param("amt") long amt);
// if it returns 0 — insufficient funds
The check and the change are in a single SQL statement, and the DB locks the row itself.
Way 2 — an optimistic lock, with a @Version field. The second save fails with OptimisticLockException (in Spring, ObjectOptimisticLockingFailureException), and the code retries. It's good when conflicts are rare; on a popular account, though, retries pile up.
Way 3 — a pessimistic lock, SELECT ... FOR UPDATE with @Lock(LockModeType.PESSIMISTIC_WRITE). The second transaction waits. It's reliable, but if you do long work inside the transaction, the wait queue grows.
For money I usually use option 1, in the same transaction as the ledger entry. One more thing: a long in tiyin is fine; a balance in double is a mistake of its own.
With several instances, synchronized or a Java lock isn't a solution — the race is between different JVMs.
Sign up to mark studied questions and save your progress.