Sub topic 8
Avoiding deadlocks in application code
This chapter assumes you can read the deadlock error from the previous chapter and know that row locks last until the end of the transaction. It also assumes you know the row lock modes FOR UPDATE, FOR NO KEY UPDATE, FOR SHARE and FOR KEY SHARE. Here you turn that knowledge into habits you can apply in application code.
PostgreSQL detects deadlocks and aborts one transaction, so a deadlock is never fatal to the database. For the application it still means a failed request, wasted work and a retry. The best fix is to make deadlocks unlikely and the remaining ones harmless.
What you are preventing
A deadlock needs a cycle of waits. Transaction 1 holds lock X and wants Y, while transaction 2 holds Y and wants X. Every technique below removes one ingredient of that cycle:
- Acquire locks in the same order everywhere, so a cycle cannot form.
- Hold locks for less time, so the window for a cycle is small.
- Take the strongest lock you need at the start, so you never wait while holding a weaker one.
- Retry when a deadlock happens anyway.
Rule 1: Lock rows in a consistent order
The deadlock example in the previous chapter updated accounts 1 and 2 in opposite order. If every transaction locks the rows it needs in ascending id order, the second transaction waits at the first row. It never holds a lock the first transaction wants.
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;The ORDER BY id is what matters here. Without it, PostgreSQL locks rows in whatever order the plan produces, and that order can differ between two sessions. With it, the locking step sits above the sort, so rows are locked in sorted order.
The order itself does not matter. You only need every code path that touches these rows to use the same order. A common convention is to sort by primary key. Across tables, pick a fixed table order too, for example always accounts before transfers.
The diagram shows why ordered locking turns a deadlock into a simple wait.
Sorting in application code
When a request names the rows (a transfer between two accounts, say), the application should sort the ids before it sends any SQL. This example uses psycopg 3.
import random
import time
import psycopg
from psycopg import errors
def transfer(conninfo, src, dst, amount, max_attempts=4):
if src == dst:
raise ValueError("source and destination must differ")
ids = sorted([src, dst]) # fixed lock order
for attempt in range(1, max_attempts + 1):
try:
# The with-block commits on success and rolls back on any exception.
with psycopg.connect(conninfo) as conn:
with conn.cursor() as cur:
cur.execute(
"SELECT id FROM accounts "
"WHERE id = ANY(%s) ORDER BY id FOR UPDATE",
(ids,),
)
if len(cur.fetchall()) != 2:
raise LookupError("account not found")
cur.execute(
"UPDATE accounts SET balance = balance - %s WHERE id = %s",
(amount, src),
)
cur.execute(
"UPDATE accounts SET balance = balance + %s WHERE id = %s",
(amount, dst),
)
return
except (errors.DeadlockDetected, errors.SerializationFailure):
if attempt == max_attempts:
raise
time.sleep(random.uniform(0, 0.05 * 2 ** attempt))The statement order inside the transaction (debit, then credit) no longer matters. All the locks were taken by the first SELECT, in sorted order. The retry handling at the bottom is covered under Rule 5.
Rule 2: Keep transactions short
A lock is held until COMMIT or ROLLBACK, so the longer a transaction runs, the more chances another transaction has to collide with it. Typical mistakes:
- Calling an HTTP API, sending an email or waiting for user input between
BEGINandCOMMIT. - Starting a transaction at the beginning of a web request and committing at the end, even if the database work is a small part of it.
- Looping over thousands of rows, doing slow work per row, in one transaction.
- Leaving a connection
idle in transactionafter an error handler forgot to roll back.
Do the slow work before BEGIN, then open the transaction, take the locks, write and commit. For large batches, commit in chunks of a few hundred or thousand rows. Each chunk should use the same ordering rule.
Rule 3: Take the strongest lock you need first
A lock upgrade is a transaction that first takes a weak lock and later needs a stronger one on the same row. Two transactions doing this at once can deadlock without touching any second row.
-- Session 1
BEGIN;
SELECT balance FROM accounts WHERE id = 1 FOR SHARE;
-- Session 2
BEGIN;
SELECT balance FROM accounts WHERE id = 1 FOR SHARE;
-- Session 1 (waits: session 2 holds a share lock)
UPDATE accounts SET balance = balance - 10 WHERE id = 1;
-- Session 2 (waits: session 1 holds a share lock, so a cycle forms)
UPDATE accounts SET balance = balance - 10 WHERE id = 1;
-- ERROR: deadlock detectedBoth sessions can hold FOR SHARE together, but neither can get the exclusive lock the UPDATE needs while the other still holds its share lock. The fix is to ask for the real lock at the start:
BEGIN;
SELECT balance FROM accounts WHERE id = 1 FOR NO KEY UPDATE;
UPDATE accounts SET balance = balance - 10 WHERE id = 1;
COMMIT;Now the second session waits at its SELECT, holding nothing, and proceeds after the first commits.
Use FOR NO KEY UPDATE when you will change non-key columns. It does not block other transactions that insert child rows referencing this row, because those take only FOR KEY SHARE on the parent. Use FOR UPDATE when you will delete the row or change a unique or primary key column.
The same pattern appears as read, decide, write code: SELECT a value, compute in the application, then UPDATE. If two requests can do this on one row, lock at the SELECT, or do the change in one atomic statement such as UPDATE ... SET balance = balance - 10.
Rule 4: Make multi-row statements predictable
A single UPDATE or DELETE that touches many rows locks them one at a time, in the order the executor reaches them. That order is not guaranteed. Two bulk updates that overlap on several rows can therefore lock them in different orders and deadlock, even though each is one statement.
Lock first in a defined order, then update the locked rows:
WITH locked AS MATERIALIZED (
SELECT id
FROM accounts
WHERE id = ANY ('{3,1,2}'::int[])
ORDER BY id
FOR UPDATE
)
UPDATE accounts AS a
SET balance = balance + 1
FROM locked AS l
WHERE a.id = l.id;MATERIALIZED makes the locking step run as its own unit, so the sorted order is the order of acquisition.
Bulk inserts follow the same rule. Two transactions inserting overlapping sets of unique keys in different orders can each wait on the other's uncommitted row. Sort the batch by the unique key before inserting. If duplicates are expected, INSERT ... ON CONFLICT DO NOTHING removes one source of waiting, but ordering still matters when you use ON CONFLICT DO UPDATE.
Rule 5: Retry, because you cannot remove every deadlock
Foreign keys, triggers, indexes and other code paths take locks you did not write. Even a careful application sees an occasional deadlock. Treat SQLSTATE 40P01 (deadlock_detected) as a retryable error, like 40001 (serialization_failure).
Follow these points when you write the retry:
- Retry the whole transaction, from
BEGIN. After the error the transaction is aborted and every earlier statement was rolled back. - Re-read any data the transaction used. Another session committed while you waited, so earlier reads are stale.
- Limit attempts (three or four is typical) and add random jitter to the sleep. Without jitter, the two transactions can collide again in lockstep.
- Make the transaction safe to run twice. Do not send emails or call payment APIs inside it. Do them after the commit, or use an idempotency key.
- Log each deadlock. A steady stream means an ordering bug, not bad luck.
Summary of techniques
| Technique | What it removes | Cost |
|---|---|---|
| Sort ids and `ORDER BY ... FOR UPDATE` | Opposite-order lock cycles | One extra locking query |
| Short transactions | The time window for collisions | Restructuring code |
| Strongest lock first | Lock-upgrade cycles | Slightly more blocking up front |
| Lock then bulk update | Cycles inside multi-row statements | Extra query or CTE |
| Retry with jitter | Residual deadlocks | Needs idempotent transactions |
Checking your fix
Reproduce the original deadlock with two psql sessions, apply the ordering rule to both sessions, and run the same interleaving again. The second session should wait and then finish without an error. A single test run does not prove the fix, because deadlocks depend on timing. If you suspect a code path, run it from many concurrent clients (a script with a few dozen threads is enough) and count 40P01 errors in the server log.
Exercise
An order-processing service runs two kinds of transactions. Kind A updates a customer row and then an inventory row. Kind B updates the same inventory row and then the same customer row. Under load the service logs occasional 40P01 errors. Describe the cause, give two changes that fix it, and say what the application should do about the errors that still occur.
Show answer
The two kinds lock the same two rows in opposite order, so A can hold the customer while waiting for the inventory, and B can hold the inventory while waiting for the customer, which is a cycle. Fix 1: make both kinds lock in the same order, for example customer first, then inventory, ideally with one SELECT ... ORDER BY ... FOR UPDATE (or a fixed table order) at the start of each transaction. Fix 2: shorten the transactions by moving slow work outside them, which narrows the window for collisions. For deadlocks that still occur, catch SQLSTATE 40P01, retry the whole transaction a limited number of times with random jitter, and make sure the transaction is safe to run again.
Exercise
Two sessions each run SELECT ... WHERE id = 1 FOR SHARE and then UPDATE accounts SET balance = balance - 10 WHERE id = 1. Why does this deadlock, and what single change prevents it?
Show answer
Both sessions hold a share lock on row 1. Each UPDATE needs a stronger lock that conflicts with the other session's share lock, so each waits for the other. Take the intended lock at the start by using FOR NO KEY UPDATE (or FOR UPDATE) in the SELECT. The second session then waits at its SELECT and holds nothing, so no cycle forms.
Exercise
Why is UPDATE accounts SET balance = balance + 1 WHERE id = ANY(...) not guaranteed to be deadlock-free when two sessions run it with overlapping id lists? How do you fix it?
Show answer
A multi-row UPDATE locks rows one at a time in the order the executor visits them, and that order is not guaranteed to be the same for both sessions. They can lock the shared rows in opposite order and form a cycle. Lock the rows first in a defined order with SELECT id ... ORDER BY id FOR UPDATE (for example in a MATERIALIZED CTE) and update the locked rows, or sort the ids and lock them in a separate first step.