Topic 4 of 5 · 5 min read
Row locks, deadlocks and lock timeouts
Goal: Read a deadlock log, explain the lock order that caused it and change the code so it cannot happen again.
A deadlock happens when two transactions each hold a lock the other needs, and the cure is to make every code path take locks in the same order and keep transactions short. PostgreSQL detects the cycle after deadlock_timeout (one second by default) and aborts one transaction.
Check yourself · 1 of 3
What happens when a second transaction updates a row that another open transaction has already updated?
Why it matters
Locks are how the database keeps writers from clobbering each other. Usually you never see them. When a slow transaction sits on a row, every request that needs that row queues behind it, and the symptom is a slow or frozen endpoint, not an error.
How locks behave
- An
UPDATE,DELETEorSELECT ... FOR UPDATEtakes a row lock that lasts until commit or rollback. Plain reads do not block on it. - A second writer on the same row waits. It does not fail.
- Many schema changes take a table lock.
ALTER TABLEcan wait behind a long transaction, and then everything else queues behind theALTER. FOR UPDATE SKIP LOCKEDlets workers pick different rows from a job queue.NOWAITfails at once instead of waiting.
A deadlock, step by step
Transfer A to B and B to A at the same time:
- Transaction 1 locks account 1.
- Transaction 2 locks account 2.
- Transaction 1 asks for account 2 and waits.
- Transaction 2 asks for account 1 and waits.
Neither can move. PostgreSQL aborts one with SQLSTATE 40P01 and logs both queries and the process ids.
Fixing it
- Consistent order. Always lock the lower id first: sort the ids, then lock them in that order, whatever the direction of the transfer.
- Short transactions. Less time holding locks means fewer collisions.
- Retry on 40P01. The aborted transaction did nothing; run it again.
- Fail fast.
SET LOCAL lock_timeout = '2s'makes a transaction give up instead of queuing without limit. Addidle_in_transaction_session_timeoutto kill sessions that opened a transaction and went quiet.
Finding who is blocking
SELECT pid, pg_blocking_pids(pid) AS blocked_by, wait_event_type, state, query
FROM pg_stat_activity
WHERE cardinality(pg_blocking_pids(pid)) > 0;
pg_locks shows each lock and whether it is granted. A row with granted = false is a waiter.
Before and after
# Before: lock order follows the direction of the transfer
lock(src); lock(dst)
# After: lock order is always by id
for acct_id in sorted([src, dst]):
lock(acct_id)
What goes wrong
- Locking rows in a loop in whatever order a query returned them.
- Running a migration during peak traffic without
lock_timeout. - Treating a deadlock error as a database fault instead of an ordering bug.
Examples
Reading a deadlock log
ERROR: deadlock detected
DETAIL: Process 5121 waits for ShareLock on transaction 9042; blocked by process 5130.
Process 5130 waits for ShareLock on transaction 9041; blocked by process 5121.
Process 5121: UPDATE accounts SET balance = balance - 50 WHERE id = 2
Process 5130: UPDATE accounts SET balance = balance + 50 WHERE id = 1
Each process holds one account and wants the other. Both updates touch accounts 1 and 2 in opposite order. Sorting the ids before updating removes the cycle.
The migration that froze the site
An ALTER TABLE orders ADD COLUMN note text waited behind a report query that had been open for 20 minutes. Every new request on orders then queued behind the ALTER. Running it with SET lock_timeout = '3s' and retrying later would have caused a failed migration, not an outage.
Key points
- A row lock is held until commit or rollback, and other writers on that row wait rather than fail.
- A deadlock is a cycle of waits; PostgreSQL aborts one transaction with SQLSTATE 40P01 and logs the queries involved.
- Taking locks in one agreed order, such as ascending id, makes the cycle impossible.
- lock_timeout makes a statement give up after a set time instead of queuing behind a long transaction.
- pg_blocking_pids and pg_locks show which session holds the lock a stuck query is waiting for.
Common mistakes
- Locking rows in the order a query happens to return them.
- Waiting for a lock with no timeout in a request handler.
- Running ALTER TABLE during traffic with no lock_timeout.
- Blaming the database for deadlocks that an ordering change would remove.
Check yourself · 2 of 3
Transfers lock the source account then the destination, and deadlocks appear when two opposite transfers overlap. Which change removes them?
Check yourself · 3 of 3
A deploy runs ALTER TABLE on a busy table and the site stalls. Which setting would have made the ALTER give up instead of stalling everything?
Practice items, not counted towards your mastery.
Start here
- Transaction Isolation (PostgreSQL documentation) (opens in a new tab)DocsFree
What read committed, repeatable read and serializable allow, and why serialization failures must be retried.
- PostgreSQL: Explicit locking (opens in a new tab)DocsFree
Row and table lock modes, FOR UPDATE, and the section on deadlocks and lock ordering.
- Jepsen: Consistency models (opens in a new tab)ArticleFree
A map of isolation and consistency models and which anomalies each one allows.
More for this topic
- PostgreSQL: pg_locks view (opens in a new tab)DocsFree
The columns that show who holds and who waits for a lock.
- PostgreSQL client settings (statement_timeout) (opens in a new tab)DocsFree
Reference for lock_timeout, statement_timeout and idle_in_transaction_session_timeout.