Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Two requests withdraw money from the same account at the same time. Write the SQL and the Spring Data JPA repository method that prevent a lost update with pessimistic locking, and explain how long the lock is held.

We read the account row with SELECT ... FOR UPDATE inside a transaction, so the second request waits until the first commits and then sees the new balance. In Spring Data JPA that is a repository method annotated with @Lock(LockModeType.PESSIMISTIC_WRITE), called from a @Transactional service method. The lock is held until the transaction commits or rolls back, so the transaction must be short, contain no remote calls, and use a lock timeout.

Why this question is asked

Two withdrawals racing on the same account is the textbook lost update, and nearly every backend team meets it in some form: stock counts, seat bookings, credit limits. Interviewers ask for the code because it shows whether we know where the lock comes from, how long it lasts, and the Spring pieces that have to line up for it to work. In this answer, we will reproduce the lost update, fix it in SQL with FOR UPDATE, write the Spring Data JPA version, discuss how long the lock is held and how to bound the wait, and look at the lock-free atomic UPDATE alternative.

1Reproducing the Lost Update

A lost update happens when two transactions read the same value, both compute a new value from it, and the second write overwrites the first. Say the balance is 100 and two requests withdraw 70 and 50 at the same moment. Both read 100, both decide there is enough money, and both write.

SQL
-- T1 -- T2
BEGIN; BEGIN;
SELECT balance FROM account WHERE id = 1; -- 100
SELECT balance FROM account WHERE id = 1; -- 100
UPDATE account SET balance = 30 WHERE id = 1;
COMMIT;
UPDATE account SET balance = 50 WHERE id = 1;
COMMIT;
-- final balance: 50, but 120 was withdrawn from 100

Notice that the database did nothing wrong at READ COMMITTED: each statement saw committed data. The bug is that the decision was made on a value that changed before the write.

2The SQL Fix: SELECT ... FOR UPDATE

FOR UPDATE takes an exclusive row lock at read time. A second transaction asking for the same lock waits until the first ends, and when it continues, it reads the committed balance after the first withdrawal.

SQL
BEGIN;
SELECT balance FROM account WHERE id = 1 FOR UPDATE; -- T1: 100, row locked
-- T2's SELECT ... FOR UPDATE on id = 1 now waits
UPDATE account SET balance = balance - 70 WHERE id = 1; -- 30
COMMIT; -- lock released
-- T2 resumes: SELECT returns 30; 30 < 50, so it rejects the withdrawal
Step throughTwo withdrawals with a row lock
Request ADatabaseRequest B
SELECT ... FOR UPDATE (id 1)
balance 100, row locked
SELECT ... FOR UPDATE (id 1)
B waits for A's lock
UPDATE balance = 30; COMMIT
balance 30, row locked for B
30 < 50: ROLLBACK, insufficient funds

7 messages in order. Play them, or step through them one at a time.

The second request decides on the balance after the first withdrawal.

3The Spring Data JPA Version

In JPA, LockModeType.PESSIMISTIC_WRITE asks the provider for an exclusive row lock, which Hibernate renders as FOR UPDATE (or the dialect's equivalent). The hint jakarta.persistence.lock.timeout bounds the wait in milliseconds. The service method must be @Transactional, because the lock lives exactly as long as the transaction; without one, Spring Data runs the query in its own short transaction and the lock is gone before we update.

Java
public interface AccountRepository extends JpaRepository<Account, Long> {
@Lock(LockModeType.PESSIMISTIC_WRITE)
@QueryHints(@QueryHint(name = "jakarta.persistence.lock.timeout", value = "2000"))
@Query("select a from Account a where a.id = :id")
Optional<Account> findForUpdate(@Param("id") Long id);
}
@Service
class WithdrawalService {
private final AccountRepository accounts;
WithdrawalService(AccountRepository accounts) { this.accounts = accounts; }
@Transactional
public void withdraw(long id, BigDecimal amount) {
Account a = accounts.findForUpdate(id).orElseThrow(); // select ... for update
if (a.getBalance().compareTo(amount) < 0) throw new InsufficientFundsException(id);
a.setBalance(a.getBalance().subtract(amount)); // flushed as UPDATE at commit
} // commit releases the lock
}

Notice that we never call save(): the entity is managed, so Hibernate writes the change at flush time, just before commit. How the timeout hint is applied depends on the database and Hibernate version. A value of 0 usually becomes NOWAIT, while other values may be ignored on some databases, so on PostgreSQL it is worth also setting lock_timeout for the transaction and testing what the logged SQL shows.

4How Long the Lock Is Held

The row lock is taken when the SELECT runs and released only when the transaction commits or rolls back. Everything that happens between those two points extends it: the business checks, building audit records, and above all any remote call. If withdraw() also called a fraud service that takes 800 milliseconds, every other withdrawal on that account would wait 800 milliseconds, and each waiting request would also hold a pooled database connection.

So the rules are short and simple. Lock as late as possible, do the remote work before or after the transaction, never inside it, and bound the wait with a lock timeout so a stuck holder produces a fast PessimisticLockException or LockTimeoutException rather than a thread pile-up.

5The Alternative: One Atomic UPDATE

For a simple withdrawal we can avoid the explicit lock entirely. A single UPDATE that does the check in its WHERE clause is atomic: the database locks the row, evaluates the condition on the current committed value, and writes, all in one statement. The update count tells us whether it worked.

Java
@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") BigDecimal amt);
// in a @Transactional service method:
if (accounts.withdraw(1L, new BigDecimal("50")) == 0) throw new InsufficientFundsException(1L);
// request A: 1 (balance 30); request B: 0 (rejected)

This holds the lock only for the duration of one statement plus the rest of the transaction, needs one round trip instead of two, and cannot be broken by someone forgetting @Transactional. Pessimistic locking remains the better tool when the decision needs more than a single condition, for example several rows or rules computed in Java.

6Follow-up questions

When would you choose optimistic locking with @Version instead?

When conflicts are rare and the read and the write are far apart in time, such as a user editing a form for two minutes. With a @Version column, the UPDATE includes WHERE version = :old, and if someone else changed the row first it updates nothing and JPA throws an OptimisticLockException, which we retry or show to the user. No lock is held while the user thinks. For a hot account with many concurrent withdrawals, conflicts would be frequent and retries wasteful, so pessimistic locking or the atomic UPDATE fits better.

What happens if findForUpdate() is called outside a transaction?

With Spring Data JPA the repository call runs in its own transaction, or the provider may reject the lock with a TransactionRequiredException, depending on the setup. Either way the lock is released when the repository call returns, so the later update is not protected. Always call locking queries from a @Transactional method of another bean.

Should transfers between two accounts lock both rows the same way?

Yes, but in a consistent order, for example by ascending account id, so that a transfer from 1 to 2 and a transfer from 2 to 1 do not each hold one lock and wait for the other, which is a deadlock.

7Conclusion

In this answer, we saw that two concurrent withdrawals lose an update when both decide on the same stale balance. SELECT ... FOR UPDATE, or @Lock(PESSIMISTIC_WRITE) on a Spring Data JPA query called from a @Transactional method, makes the second request wait and decide on the new balance. The lock lasts until commit or rollback, so the transaction must be short, free of remote calls and bounded by a lock timeout, and for simple cases a single conditional UPDATE does the job without an explicit lock.

What to say in the interviewAbout 80 seconds aloud

Open with

The bug is a lost update: both requests read the same balance and both write. With pessimistic locking I'd read the row with SELECT balance FROM account WHERE id = ?

Then, if they want more

FOR UPDATE inside a transaction, check the balance, update it, and commit. The second request's FOR UPDATE waits for the first commit and then sees the reduced balance.

In Spring Data JPA I'd add a repository method with @Lock(LockModeType.PESSIMISTIC_WRITE) and a JPQL query by id, plus a jakarta.persistence.lock.timeout hint, and call it from a @Transactional service method in another bean, because the lock only lives as long as the transaction. Then I just change the managed entity and Hibernate flushes the update at commit.

The lock is held from the select until commit or rollback, so I'd keep that window tiny: no HTTP calls or slow work inside it, and a lock timeout so waiting requests fail fast instead of piling up connections. I'd check how the timeout hint is applied on our database, and on PostgreSQL I might set lock_timeout too.

For a plain withdrawal I'd actually consider a single UPDATE with balance >= amount in the WHERE clause and check the update count, which is atomic with no explicit lock.

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.
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 withdraw money from the same account at the same time. Write the SQL and...": https://scrivio-interview-library.netlify.app/databases/database-locking/2de8b363ec/