Video in progress
What does `SELECT ... FOR UPDATE` do, and what should you watch out for when you use it?
It locks the rows it read until the end of the transaction: other transactions can't modify them or run their own FOR UPDATE on them, so they wait. A plain SELECT isn't blocked. It's important to keep the transaction short and to lock rows in the same order.
📖 Answer
BEGIN;
SELECT balance FROM accounts WHERE id = 1 FOR UPDATE; -- the row is locked
-- the application checks: is the balance enough?
UPDATE accounts SET balance = balance - 500 WHERE id = 1;
COMMIT; -- the lock is released here
If another transaction runs FOR UPDATE in the meantime, it waits until the first one commits. A plain SELECT, thanks to MVCC, just keeps reading the old value without waiting: readers don't wait for writers.
What to watch out for:
- Don't do slow work inside the transaction, like an HTTP call or a file upload. The lock is held that long, and other requests pile up in a queue.
- You can limit the wait:
FOR UPDATE NOWAIT(an immediate error) orSET lock_timeout = '2s'. - If you lock several rows, always do it in the same order (for example
ORDER BY id), otherwise you risk a deadlock. - For taking work from a queue,
FOR UPDATE SKIP LOCKEDis very handy: several workers take different tasks without waiting for each other.
In Spring Data JPA you put @Lock(LockModeType.PESSIMISTIC_WRITE) on a repository method, and it only has meaning inside @Transactional.
Sign up to mark studied questions and save your progress.