Sub topic 7
How PostgreSQL Detects and Resolves Deadlocks
This chapter assumes you know basic SQL, transactions, BEGIN, COMMIT, and ROLLBACK. You should also be able to connect to the same PostgreSQL database through two concurrent client sessions.
A deadlock is a cycle in which each transaction waits for a lock held by another transaction in the cycle. Neither transaction can continue. PostgreSQL detects the cycle and aborts one transaction so that the other can proceed.
How a deadlock forms
Suppose two transactions update the same two rows, but in opposite orders:
-- Run once before opening the two sessions
CREATE TABLE accounts (
id integer PRIMARY KEY,
balance numeric NOT NULL
);
INSERT INTO accounts (id, balance)
VALUES (1, 100), (2, 100);Run the following commands in Session 1 and Session 2 in the shown order:
-- Session 1
BEGIN;
UPDATE accounts
SET balance = balance - 10
WHERE id = 1;
-- Session 2
BEGIN;
UPDATE accounts
SET balance = balance - 10
WHERE id = 2;
-- Session 1 waits for Session 2
UPDATE accounts
SET balance = balance + 10
WHERE id = 2;
-- Session 2 waits for Session 1
UPDATE accounts
SET balance = balance + 10
WHERE id = 1;The first update in each session obtains a row-level lock. Session 1 then requests the row locked by Session 2. Session 2 requests the row locked by Session 1. This creates a cycle:
How PostgreSQL detects the cycle
When a transaction cannot obtain a lock, PostgreSQL normally makes it wait. After the deadlock_timeout interval, the server checks whether the waits form a cycle. The default value is commonly one second, but it can be changed in the server configuration or for a session.
The detector examines the lock-wait graph. Each waiting transaction points to the transaction holding the requested lock. A cycle means that progress is impossible without intervention.
| Situation | PostgreSQL action |
|---|---|
| A transaction waits, but no cycle exists | Continue waiting |
| A cycle exists | Abort one transaction |
| A transaction exceeds `lock_timeout` | Cancel the waiting statement |
deadlock_timeout controls when PostgreSQL checks for a deadlock. It does not cancel a transaction merely because it has waited that long. lock_timeout is different: it limits how long a statement may wait for a lock.
How PostgreSQL resolves a deadlock
After detecting a cycle, PostgreSQL chooses one transaction as the victim and cancels it. The victim receives an error such as:
ERROR: deadlock detected
DETAIL: Process ... waits for ...
HINT: See server log for query details.
SQLSTATE: 40P01The failed transaction is in an aborted state. The application must issue ROLLBACK or close the transaction before it can execute more commands in that session. The other transaction can then acquire the released locks and continue.
PostgreSQL may write additional details to the server log, depending on settings such as log_lock_waits. The log can show the processes, lock types, relations, and queries involved.
Handling deadlock errors
Applications should treat SQLSTATE 40P01 as a retryable transaction failure when the operation is safe to repeat. Retry the complete transaction, not only the statement that failed. Use a limit and a backoff delay so many clients do not immediately collide again.
A retry is safe only when the transaction is idempotent or protected from duplicate external effects. For example, an email or payment should not be repeated merely because its database transaction is retried.
The best prevention is consistent lock ordering. If every transfer locks account rows by ascending id, concurrent transactions wait in a queue instead of forming a cycle.
BEGIN;
SELECT id
FROM accounts
WHERE id IN (1, 2)
ORDER BY id
FOR UPDATE;
UPDATE accounts
SET balance = balance - 10
WHERE id = 1;
UPDATE accounts
SET balance = balance + 10
WHERE id = 2;
COMMIT;Keep transactions short and avoid waiting for network calls or user input while holding locks.
Exercise
Session 1 holds a lock on row 1, and Session 2 holds a lock on row 2. Each session then requests the other row. What does PostgreSQL do?
Show answer
After a deadlock check, PostgreSQL aborts one transaction with SQLSTATE 40P01. The other transaction can proceed, and the application should roll back and retry the complete failed transaction when appropriate.