Lesson 225 of 296
Locks, deadlocks, optimistic vs pessimistic
What you will learn
- The lost update problem, demonstrated
- Fix 1: atomic updates
- Fix 2: pessimistic locking with SELECT FOR UPDATE
- Fix 3: optimistic locking with a version column
- Deadlocks and how to avoid them
- SKIP LOCKED for job queues
On this page
The lost update, demonstrated
Aisha has 10000 pence. Two requests run at the same time: one spends 3000, the other 2000. The application code reads the balance, calculates, then writes the new value:
| Step | Transaction A | Transaction B |
|---|---|---|
| 1 | Reads 10000 | |
| 2 | Reads 10000 | |
| 3 | Writes 10000 - 3000 = 7000, commits | |
| 4 | Writes 10000 - 2000 = 8000, commits |
Run on a real PostgreSQL server with two connections, the final balance was 8000. The correct answer is 5000: A's £30 payment was lost. Read Committed does not prevent this.
Fix 1: atomic updates
Let the database do the arithmetic in one statement:
UPDATE accounts SET balance_pence = balance_pence - 3000 WHERE id = 1;The second UPDATE waits for the first transaction's row lock, then reads the new value. In the test, two concurrent atomic updates gave 5000: correct. Use this whenever the change can be expressed in SQL (counters, stock levels, balances). Add a condition to stop overselling: UPDATE products SET stock = stock - 1 WHERE id = $1 AND stock > 0 and check that one row was updated.
Fix 2: pessimistic locking (SELECT FOR UPDATE)
When the logic must happen in application code, lock the row while reading it:
BEGIN;
SELECT balance_pence FROM accounts WHERE id = 1 FOR UPDATE;
-- application checks rules, calculates the new value
UPDATE accounts SET balance_pence = $1 WHERE id = 1;
COMMIT;FOR UPDATE takes a row lock: another transaction that tries to lock or update the same row waits until the first commits or rolls back. In the test, transaction B's SELECT ... FOR UPDATE blocked until A committed, then read 7000 (A's result), and the final balance was the correct 5000.
It is called pessimistic because it assumes conflicts are likely and prevents them up front. Cost: other users wait. Variants: FOR UPDATE NOWAIT (fail immediately instead of waiting), FOR SHARE (others may read-lock but not change).
Fix 3: optimistic locking (version column)
Assume conflicts are rare; do not lock; detect a conflict at write time. Add a version column, and update only if the version is still the one you read:
ALTER TABLE products ADD COLUMN version integer NOT NULL DEFAULT 1;UPDATE products SET price_pence = 949, version = version + 1
WHERE id = 1 AND version = 1
RETURNING id, price_pence, version;| id | price_pence | version |
|---|---|---|
| 1 | 949 | 2 |
A second editor who also read version 1 then tries to save:
UPDATE products SET price_pence = 999, version = version + 1
WHERE id = 1 AND version = 1
RETURNING id, price_pence, version;| id | price_pence | version |
|---|
Zero rows updated: the version is now 2. The application detects this and tells the user "This product was changed by someone else; reload and try again" (HTTP 409 Conflict, or 412 with ETag and If-Match, Lesson 198). Nothing is silently overwritten.
| Pessimistic | Optimistic | |
|---|---|---|
| How | Lock when reading | Check a version when writing |
| Best when | Conflicts are frequent; short operations | Conflicts are rare; long edit sessions (a user editing a form for 10 minutes) |
| Cost | Waiting, possible deadlocks | Retries or "reload" messages on conflict |
| Works across HTTP requests | No (locks only last inside one transaction) | Yes (the version travels with the form or ETag) |
ORMs support optimistic locking (a @VersionColumn in TypeORM; in Prisma, updateMany with the version in where, checking the count).
Deadlocks
A deadlock: transaction A holds a lock B needs, and B holds a lock A needs. Neither can continue. In the test:
| Step | A | B |
|---|---|---|
| 1 | Locks account 1 (update) | |
| 2 | Locks account 2 (update) | |
| 3 | Wants account 2: waits for B | |
| 4 | Wants account 1: waits for A. Deadlock |
PostgreSQL detects the cycle (after deadlock_timeout, 1 second by default) and aborts one transaction with deadlock detected (error code 40P01); the other continues. In the test, A was aborted and B succeeded.
Preventing deadlocks:
- Lock rows in a consistent order (for example, always the lower account ID first in a transfer). Then two transfers between the same accounts queue up instead of deadlocking.
- Keep transactions short.
- Touch as few rows as needed.
- Retry on 40P01, because deadlocks can never be ruled out completely.
SKIP LOCKED: a queue in PostgreSQL
Several workers taking jobs from a jobs table must not take the same job. FOR UPDATE SKIP LOCKED locks the rows it selects and skips rows other transactions have already locked:
SELECT id FROM jobs WHERE status = 'queued' ORDER BY id LIMIT 2 FOR UPDATE SKIP LOCKED;In the test with two workers at the same time: worker A got jobs 1 and 2, worker B got jobs 3 and 4. No waiting, no duplicates. This is how PostgreSQL-based queues like pg-boss work (Lesson 204).
How to say it in an interview
"A lost update happens when two transactions read a value and both write a result based on it; I reproduced it on PostgreSQL and lost a payment under the default isolation level. Fixes: atomic SQL updates like balance minus amount, ideally with a guard condition; pessimistic locking with SELECT FOR UPDATE when the logic is in code; or optimistic locking with a version column checked in the UPDATE's WHERE, returning a conflict when zero rows change, which suits long edits across HTTP requests. Deadlocks happen when transactions lock rows in opposite orders; PostgreSQL aborts one with 40P01, so I lock in a consistent order, keep transactions short and retry. FOR UPDATE SKIP LOCKED lets several workers take different jobs from a table."
Key words
| Word | Meaning |
|---|---|
| Lost update | One concurrent write silently overwrites another |
| Row lock | A lock on specific rows held until the transaction ends |
| SELECT FOR UPDATE | Read rows and lock them for changing |
| Pessimistic locking | Prevent conflicts by locking first |
| Optimistic locking | Detect conflicts at write time with a version |
| Deadlock | Transactions waiting on each other forever |
| SKIP LOCKED | Skip rows other transactions have locked |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.