Sub topic 6
How a Deadlock Happens
Assume you know basic SQL, transactions, primary keys, foreign keys, and how to use two concurrent psql sessions. You should also know that BEGIN starts a transaction and that locks normally remain until COMMIT or ROLLBACK.
A deadlock is a cycle of transactions waiting for one another. Each transaction holds a lock that another transaction needs, so none of them can continue. PostgreSQL detects the cycle and aborts one transaction.
The two-session pattern
Suppose an application transfers money between accounts. Each transfer updates two account rows. The following setup creates two accounts:
CREATE TABLE accounts (
id integer PRIMARY KEY,
balance numeric NOT NULL
);
INSERT INTO accounts (id, balance)
VALUES (1, 100), (2, 100);Now run these statements in two database sessions.
Session 1 locks account 1 first:
BEGIN;
UPDATE accounts
SET balance = balance - 10
WHERE id = 1;The UPDATE takes a row-level lock on account 1. The transaction keeps that lock because it is still open.
Session 2 locks account 2 first:
BEGIN;
UPDATE accounts
SET balance = balance - 10
WHERE id = 2;Session 2 now holds the row-level lock on account 2.
Next, ask Session 1 to update account 2:
UPDATE accounts
SET balance = balance + 10
WHERE id = 2;This statement waits. Session 2 owns the lock on account 2.
Then ask Session 2 to update account 1:
UPDATE accounts
SET balance = balance + 10
WHERE id = 1;This statement also waits. Session 1 owns the lock on account 1. The wait relationships now form a cycle:
Neither transaction can release its first lock because each is waiting for its second statement to finish. Waiting longer cannot solve this situation.
What PostgreSQL does
PostgreSQL periodically checks whether a lock wait has created a cycle. The deadlock_timeout setting controls how long a process waits before performing a deadlock check. Its default is commonly one second.
When PostgreSQL detects the cycle, it chooses one transaction as the victim and cancels the statement with an error similar to this:
ERROR: deadlock detected
DETAIL: Process ... waits for ShareLock on transaction ...;
blocked by process ...
HINT: See server log for query details.
SQLSTATE: 40P01The failed transaction is then in an aborted state. The application must issue ROLLBACK before it can run more commands in that transaction. The other transaction can continue after the deadlock victim releases its locks.
The choice of victim is an implementation decision. Do not assume that the transaction started later, or the transaction with fewer changes, will always be selected.
Why lock order matters
The deadlock occurred because both transactions needed the same rows but acquired them in opposite orders:
- Session 1: account 1, then account 2
- Session 2: account 2, then account 1
A consistent order prevents this cycle. For example, every transfer can lock account rows in ascending id order before changing either balance:
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;With this design, a concurrent transfer waits for the first transaction to finish. It does not hold a higher-numbered row while waiting for a lower-numbered row, so the cycle cannot form.
Keep the transaction short as well. Do not perform network calls, user interaction, or slow calculations while holding locks.
Exercise
Session 1 holds row A and waits for row B. Session 2 holds row B and waits for row A. What has PostgreSQL detected, and what should the application do after SQLSTATE 40P01?
Show answer
PostgreSQL has detected a deadlock. It aborts one transaction. The application should roll back the failed transaction and retry the complete transaction when the operation is safe to retry.