Video in progress
How do optimistic and pessimistic locking differ, and when do you choose which?
Pessimistic locking locks the row with FOR UPDATE when you read it, and others wait. Optimistic locking takes no lock: it checks a version column at write time and raises an error on a conflict. If collisions are rare, use optimistic; if they are frequent, or waiting is cheaper, use pessimistic.
📖 Answer
Optimistic looks like this at the SQL level:
-- read
SELECT id, title, version FROM article WHERE id = 7; -- version = 3
-- write: only if nobody has changed it
UPDATE article
SET title = 'Yangi', version = version + 1
WHERE id = 7 AND version = 3;
-- 0 rows updated => someone wrote first, we tell the user
In JPA this is the @Version field, and on a conflict OptimisticLockException is thrown.
Pessimistic:
BEGIN;
SELECT * FROM account WHERE id = 1 FOR UPDATE; -- others wait on this row
UPDATE account SET balance = balance - 100 WHERE id = 1;
COMMIT;
How I choose:
- a user opens a form and edits for 5 minutes: optimistic only. You can't hold a lock that long;
- a hot row with many parallel writes (say, stock in a warehouse): optimistic leads to a storm of retries, and pessimistic or an atomic
UPDATE ... SET qty = qty - 1 WHERE qty >= 1is better; - a short backend transaction with few conflicts: optimistic is simpler and doesn't cause deadlocks.
With pessimistic, set lock_timeout or NOWAIT, otherwise a query can wait forever.
Sign up to mark studied questions and save your progress.