Sub topic 6
How a deadlock happens
This chapter assumes you know basic SQL, transactions (BEGIN, COMMIT, ROLLBACK), and how to run two psql sessions side by side. It also assumes you have read the earlier chapters on lock lifetime and row-level locks. Here you will see how two transactions can end up waiting on each other, and how to recognize the pattern.
The core idea: a cycle of waits
A lock wait is normal. Session B waits for session A to commit, then continues. A deadlock is different because the waiting never ends on its own. It happens when a group of transactions each hold a lock that another one in the group needs, so the waits form a loop.
The smallest case has two transactions:
- Transaction 1 holds a lock on resource X and requests resource Y.
- Transaction 2 holds a lock on resource Y and requests resource X.
Neither can proceed. Locks are held until the end of the transaction, and neither transaction can end while it is blocked. Without outside help, both would wait forever.
Four conditions must all hold for a deadlock:
- Mutual exclusion: the locks conflict, so only one transaction can hold each at a time.
- Hold and wait: a transaction keeps the locks it already has while it asks for more.
- No preemption: the server does not take a lock away from a transaction that holds it.
- Circular wait: the chain of "waits for" relationships closes into a loop.
PostgreSQL cannot remove the first three without breaking transaction semantics. Prevention in application code, covered in a later chapter, works by breaking the circular wait. Detection and resolution, covered in the next chapter, is how the server recovers when prevention fails.
Reproducing the classic deadlock
Use the accounts table from earlier chapters. Run these statements in two sessions, in the order shown.
CREATE TABLE accounts (
id int PRIMARY KEY,
balance numeric NOT NULL
);
INSERT INTO accounts VALUES (1, 100), (2, 100);Now run the two transfers in opposite directions. Each transfer subtracts from one account and then adds to the other.
-- 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, so a cycle forms)
UPDATE accounts SET balance = balance + 10 WHERE id = 1;
-- After deadlock_timeout (default 1s), one session fails with:
-- ERROR: deadlock detected (SQLSTATE 40P01)Step by step:
- Session 1 updates row 1 and holds its row lock.
- Session 2 updates row 2 and holds its row lock. So far there is no conflict.
- Session 1 tries to update row 2. That row is locked by session 2, so session 1 waits.
- Session 2 tries to update row 1. That row is locked by session 1, so session 2 waits.
Session 1 waits for session 2, and session 2 waits for session 1. That is the cycle.
Nothing is wrong with either transaction in isolation. Each is a reasonable transfer. The problem is that they touch the same rows in different orders and overlap in time.
What the error looks like
After deadlock_timeout (1 second by default), PostgreSQL runs its deadlock check and aborts one of the sessions. The victim sees:
ERROR: deadlock detected
DETAIL: Process 12345 waits for ShareLock on transaction 801; blocked by process 12346.
Process 12346 waits for ShareLock on transaction 800; blocked by process 12345.
HINT: See server log for query details.
CONTEXT: while updating tuple (0,1) in relation "accounts"The SQLSTATE is 40P01. The other session is not aborted. Its wait ends as soon as the victim's transaction rolls back and releases its locks, and its UPDATE then completes.
Note the lock type in the message: ShareLock on transaction 801. A session waiting for a row lock does not queue on the row itself. It waits for the transaction ID of the transaction that holds the row. That is why the report names transactions, not rows.
The victim's transaction is now in an aborted state. Until the client issues ROLLBACK, every further statement fails with current transaction is aborted. The application must roll back and, in most cases, retry the whole transaction.
Why the wait is not always visible as a cycle
The two-session example is the textbook case, but real deadlocks have several shapes.
More than two participants
A cycle can have any length. Session 1 waits for session 2, session 2 waits for session 3, and session 3 waits for session 1. These are harder to spot because no two sessions look directly at each other. Reading the DETAIL output from first to last line follows the chain around the loop.
Deadlocks that mix lock types
The resources in a cycle do not have to be rows of the same table. A cycle can combine:
- a row lock in one table and a row lock in another,
- a row lock and a table-level lock,
- a lock taken by
SELECT ... FOR UPDATEand one taken byUPDATE.
Any combination of conflicting locks can close the loop.
Deadlocks from lock upgrades
A transaction that first takes a weak lock and later needs a stronger one on the same resource can deadlock with another transaction doing the same thing. Two sessions each run SELECT ... FOR SHARE on a row, which does not conflict. Then each tries to UPDATE that row. Each update must wait for the other session's share lock to go away, and neither will release it before commit.
-- Session 1
BEGIN;
SELECT * FROM accounts WHERE id = 1 FOR SHARE;
-- Session 2
BEGIN;
SELECT * FROM accounts WHERE id = 1 FOR SHARE;
-- Session 1 (waits for session 2's share lock)
UPDATE accounts SET balance = balance + 1 WHERE id = 1;
-- Session 2 (waits for session 1's share lock, so a cycle forms)
UPDATE accounts SET balance = balance + 1 WHERE id = 1;
-- ERROR: deadlock detected (SQLSTATE 40P01)Here both sessions work on a single row, which shows that a deadlock does not require two different rows. It requires two transactions that each hold something the other wants. The fix is to take the strongest lock you will need at the start, for example SELECT ... FOR UPDATE instead of FOR SHARE, so the second session waits at the first statement and no cycle forms.
Deadlocks hidden inside one statement
A single multi-row statement can deadlock against another one. Suppose two sessions run these at the same time:
-- Session 1
UPDATE accounts SET balance = balance + 1 WHERE id IN (1, 2);
-- Session 2
UPDATE accounts SET balance = balance + 1 WHERE id IN (2, 1);The IN list order does not control which row is locked first. PostgreSQL locks rows in the order it visits them, which depends on the plan, such as a sequential scan or an index scan. If two statements visit overlapping rows in different orders, for example because they use different plans or because rows moved between visits, they can deadlock even though each is one statement. You cannot rely on the order you wrote the values.
Deadlocks caused by foreign keys
Inserting into a child table takes a FOR KEY SHARE lock on the referenced parent row. Updating or deleting that parent row can conflict with it. A workflow that inserts child rows in one transaction while another transaction updates the parent can therefore deadlock without any explicit locking statement. Because FOR KEY SHARE conflicts only with the strongest row lock modes, an UPDATE that does not change key columns takes the weaker FOR NO KEY UPDATE lock and does not conflict with it. Updates that change a key column, and deletes, do conflict.
What is not a deadlock
Several situations look similar but are not deadlocks.
| Situation | Why it is not a deadlock | What you see |
|---|---|---|
| One long transaction holds a lock and others queue behind it | There is no cycle. The chain ends at a session that is running or idle. | Waits that last until the holder commits, rolls back, or times out |
| A session is `idle in transaction` holding locks | The holder is not waiting for anything. | Other sessions wait indefinitely |
| A session waits for a lock that another waiting session also queues for | The queue is ordered. There is still no loop. | Blocking chain, not a cycle |
| Two sessions wait on application-level state, such as a message or a client lock | PostgreSQL cannot see waits outside its own locks. | No error from PostgreSQL |
The last row matters. PostgreSQL detects only cycles among its own locks. If your application holds a database lock in one process while waiting on another process that is waiting for the database, the server has no way to see the loop. These waits last until a timeout fires, and a later chapter covers timeouts.
Predicting deadlocks in your own code
When you review a transaction, ask these questions:
- Which rows or tables does it lock, and in what order?
- Does another code path lock the same objects in a different order?
- Does it take a weak lock and later need a stronger one?
- Does it keep the transaction open while doing slow work, such as calling an external service? A longer lock hold makes overlap more likely.
A deadlock needs overlap in time, so it tends to appear under load and rarely in a single-user test. A bug that never shows up in development can appear often in production. If you see 40P01 errors, treat them as evidence of an ordering problem in the code, not as random noise.
Summary of the mechanism
- A deadlock is a cycle of waits among transactions, and no transaction in the cycle can finish until another does.
- Locks are held until commit or rollback, so a transaction that is waiting keeps everything it already acquired.
- Typical causes are opposite lock order, lock upgrades, multi-row statements that visit rows in different orders, and foreign key locks.
- PostgreSQL reports the error
deadlock detectedwith SQLSTATE40P01and aborts only one of the transactions. - The aborted transaction must be rolled back and usually retried.
Exercise
Two sessions both run SELECT * FROM accounts WHERE id = 1 FOR SHARE; and both succeed. Each then runs UPDATE accounts SET balance = balance + 1 WHERE id = 1;. Why does this end in a deadlock, even though only one row is involved? What single change to the first statement would avoid it?
Show answer
Both share locks are granted because FOR SHARE locks do not conflict with each other. The UPDATE needs a lock that conflicts with FOR SHARE, so each session waits for the other to release its share lock. Neither releases it before commit, so the waits form a cycle. Changing the first statement to SELECT ... FOR UPDATE makes the second session wait at the SELECT, before it holds anything, so no cycle forms.
Exercise
A transaction receives ERROR: deadlock detected (SQLSTATE 40P01). The application catches the error and runs the next statement of the same transaction. What happens, and what should the application do instead?
Show answer
The next statement fails with "current transaction is aborted, commands ignored until end of transaction block", because the transaction is already in an aborted state. The application should issue ROLLBACK and then, if the work is safe to repeat, retry the whole transaction from BEGIN.