Locking and deadlocks

The previous lesson ended with SELECT ... FOR UPDATE as a way to prevent a lost update. This one is what that actually does, and what goes wrong.

Readers do not block writers

This is the most important single fact about Postgres concurrency, and the one that distinguishes it from databases that use read locks.

Postgres uses MVCC — multi-version concurrency control. A writer creates a new version of a row rather than overwriting it, so:

  • readers never block writers
  • writers never block readers
  • writers block writers, on the same row

A plain SELECT takes no row locks at all. It reads from a snapshot, and a concurrent UPDATE to the same row does not slow it down or change what it sees. Most “do I need to lock this read” questions answer themselves once that is clear: for a read, no.

The explicit row locks

SELECT * FROM employee WHERE id = 1 FOR UPDATE;

FOR UPDATE takes an exclusive row lock, held until the transaction ends. Any other transaction that tries to lock or update that row waits. This is pessimistic concurrency: prevent the conflict rather than detect it.

SELECT * FROM employee WHERE id = 1 FOR SHARE;

FOR SHARE is weaker — several transactions can hold it together, but a writer cannot. Use it for “this row must not change while I rely on it”, typically a parent row whose existence you are about to depend on.

Two modifiers matter in practice:

SELECT * FROM employee WHERE id = 1 FOR UPDATE NOWAIT;

NOWAIT fails immediately rather than waiting, which turns a latency problem into an error you can handle.

SELECT * FROM employee WHERE department_id = 3 FOR UPDATE SKIP LOCKED;

SKIP LOCKED ignores rows someone else has locked. This is the job-queue primitive, and it is worth recognising:

BEGIN;
SELECT id FROM sale WHERE amount > 10000 ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED;
COMMIT;

Ten workers running that each get a different row with no coordination, no waiting and no external queue. Before SKIP LOCKED, queue-in-a-database implementations needed advisory locks or a status column with a race in it.

How a deadlock forms

Two transactions, each holding what the other wants next:

T1: BEGIN;
T1: UPDATE employee SET salary = salary + 1 WHERE id = 1;   -- locks row 1
T2: BEGIN;
T2: UPDATE employee SET salary = salary + 1 WHERE id = 2;   -- locks row 2
T1: UPDATE employee SET salary = salary + 1 WHERE id = 2;   -- waits for T2
T2: UPDATE employee SET salary = salary + 1 WHERE id = 1;   -- waits for T1

Neither can proceed. Postgres detects the cycle after deadlock_timeout — one second by default — and kills one of them:

ERROR:  deadlock detected
DETAIL:  Process 123 waits for ShareLock on transaction 456; blocked by process 789.

The victim’s transaction is rolled back. The survivor continues.

The one rule that prevents most deadlocks

Acquire locks in a consistent order everywhere.

The deadlock above happens because T1 took row 1 then row 2, and T2 took row 2 then row 1. If both had taken them in ascending id order, the second would simply have waited for the first and then proceeded.

In code that means: when updating a set of rows, sort the keys first.

BEGIN;
UPDATE employee SET salary = salary + 1 WHERE id IN (1, 2) ;
COMMIT;

A single statement with an IN list is safer than two statements, because the engine locks rows in a single scan order rather than in the order your application happened to iterate.

The classic real-world case is a money transfer: A to B in one request and B to A in another, deadlocking. Locking the lower account id first makes it impossible.

The second rule: keep transactions short

A lock is held until the transaction ends, so the window for a conflict is the length of the transaction. Two specific things to avoid:

  • Never hold a transaction open across a network call. Opening a transaction, calling a payment API and then committing holds row locks for the duration of someone else’s outage.
  • Never hold one open across user think-time. “Lock the row while the user fills in the form” is how a single user blocks a table for ten minutes. Optimistic concurrency with a version check is the right answer there.

Lock contention without deadlock

More common than deadlock, and less obvious: everything serialising on one row.

A counter row that every request updates — UPDATE stats SET hits = hits + 1 WHERE id = 1 — means every request waits for the previous one. No deadlock, no error, just throughput capped at one update per row per round trip.

The fixes are all about spreading the write: shard the counter across N rows and sum them on read, or aggregate in the application and flush periodically, or move the counter out of the transactional store entirely.

Also a schema issue: an index on a monotonically increasing column makes every insert touch the same index page, which is contention of the same kind one level down.

Diagnosing it

  • pg_locks joined to pg_stat_activity shows who holds what and who waits.
  • log_lock_waits = on logs any wait longer than deadlock_timeout, which finds contention before it becomes a deadlock.
  • Deadlocks are always logged with both statements, so the log tells you the lock order to fix.

Try it

The SQL playground runs one connection, so it cannot produce a deadlock — two are required by definition. FOR UPDATE and SKIP LOCKED are still worth running to see they are accepted and what they return; the contention itself needs a real server with two sessions.

Drill the single-statement pattern with Claim a job from the queue, which is FOR UPDATE SKIP LOCKED in a data-modifying CTE.

Interview questions

1. Does a SELECT block an UPDATE in Postgres? No. Under MVCC readers do not block writers and writers do not block readers; a writer creates a new row version. Only writers conflict with writers on the same row.

2. What does SELECT ... FOR UPDATE do, and when would you use it? Takes an exclusive row lock held until the transaction ends, so other transactions wanting that row wait. Use it for read-modify-write where the new value depends on the old one and a lost update is unacceptable.

3. How does a deadlock form, and what does Postgres do about it? Two transactions each hold a lock the other needs next, so neither can proceed. Postgres detects the cycle after deadlock_timeout and aborts one transaction with a deadlock error; the other continues.

4. What is the single most effective way to prevent deadlocks? Acquire locks in a consistent order across all code paths — for example, always updating rows in ascending primary-key order, which usually means sorting the keys before the loop or using one statement with an IN list.

5. What is SKIP LOCKED for? Claiming work from a queue table. Each worker locks a row others have not locked, skipping contended ones, so N workers process N distinct rows with no coordination and no waiting.

6. Every request updates one counter row and throughput is capped. Why, and what do you do? Writers serialise on that row, so throughput is one update per round trip. Shard the counter across several rows and sum on read, batch in the application, or move it out of the transactional store.

Next

That closes Part 4. Keys, constraints and normalisation opens Part 5, where the question becomes what the schema should have been.