Practical technical guides / Core IT: databases (PostgreSQL row locks and deadlocks)

Two Batch Updates Deadlock on the Same Rows: PostgreSQL Lock Order, deadlock_timeout and Sorting Before You Lock

On PostgreSQL 18.4 two transactions updating rows in opposite orders deadlocked; one was aborted one deadlock_timeout later. Lock rows in id order and retry the transaction.

By Sandeep Belgavi · Published 2026-11-09

Two transactions lock rows in opposite orders
Original explanatory diagram; synthetic values where shown.

On PostgreSQL 18.4 two transactions updating rows in opposite orders deadlocked; one was aborted one deadlock_timeout later. Lock rows in id order and retry the transaction.

A nightly job that fails one run in twenty

Belgavi's Book Store adjusts stock counts on order lines in two places. The nightly reconciliation job walks the day's orders and updates each line. The returns service updates the lines of a returned order as soon as a return is approved. Both run inside a transaction per order, and both touch the same order_lines rows when a return lands on an order from that day.

Most nights nothing happens. Some nights the job fails with:

ERROR:  deadlock detected
DETAIL:  Process N waits for ShareLock on transaction N; blocked by process N.
Process N waits for ShareLock on transaction N; blocked by process N.
HINT:  See server log for query details.
CONTEXT:  while updating tuple (0,2) in relation "order_lines"

That is SQLSTATE 40P01. This guide reproduces it on PostgreSQL 18.4, explains how PostgreSQL detects and resolves it, and fixes it by locking rows in one global order. The companion probe and the interactive lab use the same scenarios. The probe's outputs here are measured; the lab's larger scenarios come from a rule model and are labelled that way.

How two transactions deadlock on rows

Updating a row takes a row-level lock that lasts until the transaction ends. A second transaction that wants to update the same row waits for the first to commit or roll back. In the error above, it waits on the first transaction's ID, which is why the detail says ShareLock on transaction.

Two transactions deadlock when each holds a row the other wants:

T1: BEGIN; UPDATE order_lines SET qty = qty + 1 WHERE id = 1;   -- locks row 1
T2: BEGIN; UPDATE order_lines SET qty = qty + 1 WHERE id = 2;   -- locks row 2
T1:        UPDATE order_lines SET qty = qty + 1 WHERE id = 2;   -- waits for T2
T2:        UPDATE order_lines SET qty = qty + 1 WHERE id = 1;   -- waits for T1: a cycle

Neither can proceed. Something has to give, and PostgreSQL decides what.

How PostgreSQL finds the cycle

Checking for deadlocks is relatively expensive, so PostgreSQL does not do it on every wait. A backend that has waited for a lock for deadlock_timeout (default 1 second) runs a deadlock check. If it finds a cycle of waits that includes itself, it aborts its own transaction with 40P01 and releases its locks, and the other transaction continues. If there is no cycle yet, it keeps waiting; a backend that closes a cycle later finds it when its own timer fires.

The documentation is explicit that "exactly which transaction will be aborted is difficult to predict and should not be relied upon". In the runs below it was the one that started waiting first, because its timer fired first, but code must not depend on that.

The probe runs the schedule above with two sessions on PostgreSQL 18.4. T1 updates row 1, T2 updates row 2 about 0.15 seconds later, and each then asks for the other row after 0.3 seconds:

CaseT1T2Time from T1 starting to wait until its abort
deadlock_timeout 1 saborted, 40P01committedabout 1.0 s
deadlock_timeout 200 msaborted, 40P01committedabout 0.2 s
both lock rows in id order firstcommittedcommitted (waited for T1)no deadlock

A shorter deadlock_timeout reports deadlocks sooner but runs the expensive check on every lock wait that lasts that long, including ordinary waits. The documentation suggests the setting should ideally exceed typical transaction time and calls one second "probably about the smallest value you would want in practice". Only superusers and roles granted the privilege can change it. Treat it as a reporting delay, not a fix.

The fix: one global lock order

Deadlocks between row locks need a cycle, and a cycle needs two transactions to take locks in different orders. If every transaction that touches several order lines takes their locks in ascending id order, a transaction can only wait for one holding a lower id, and no cycle can form. The PostgreSQL documentation gives the same advice: acquire locks on multiple objects in a consistent order.

The direct way is to lock first, in order, then do the work:

BEGIN;
SELECT id FROM order_lines WHERE id = ANY($1) ORDER BY id FOR UPDATE;   -- lock every row, lowest id first
UPDATE order_lines SET qty = qty + 1 WHERE id = 2;
UPDATE order_lines SET qty = qty + 1 WHERE id = 1;
COMMIT;

The order of the updates afterwards no longer matters, because every row is already locked. In the probe, T1 passed its ids as [2, 1] and T2 as [1, 2]; both sorted through ORDER BY id, T2 waited about 0.15 seconds for T1 to commit, and both committed.

SELECT ... ORDER BY ... FOR UPDATE sorts first and then locks rows in that order. The documentation notes one subtlety: at READ COMMITTED, a row whose ordering column changes while you wait can come back out of order. Order by an immutable key such as the primary key and this does not matter.

One statement can deadlock too

A single UPDATE that touches many rows locks them one by one, in whatever order its plan visits them. Two statements with different plans can visit the same rows in opposite orders. The probe shows this with a table inserted in descending id order and a trigger that sleeps 150 ms per row, so the locks are spread out in time:

  • T1: UPDATE order_lines SET ... WHERE id = ANY('{1,2,3,4,5,6}') with an index scan, which visits ids in ascending order.
  • T2: UPDATE order_lines SET ... WHERE batch = 'nightly' with a sequential scan, which visits rows in physical order: 6, 5, 4, 3, 2, 1.

T1 was aborted with 40P01 and T2 committed. With only six rows the planner chose a sequential scan for T1 too, so the probe forced the index scan with enable_seqscan = off to show what happens when plans differ, as they do on real tables of different sizes and statistics. Rewriting both as "lock in id order, then update" removed the deadlock:

WITH l AS (SELECT id FROM order_lines WHERE batch = 'nightly' ORDER BY id FOR UPDATE)
UPDATE order_lines o SET qty = qty + 1 FROM l WHERE o.id = l.id;

Do not rely on WHERE id IN (...) or on the order of values in a list. Neither promises the order in which rows are locked.

Retry the whole transaction

A transaction aborted with 40P01 is rolled back; nothing it did is kept. The right response is to retry the whole transaction from the start, re-reading anything it read, usually after a short random delay. Retrying only the failed statement inside the same transaction is impossible: the transaction is already aborted.

for attempt in range(3):
    try:
        with conn.transaction():
            lock_in_order(conn, ids)
            apply_updates(conn, ids)
        break
    except psycopg.errors.DeadlockDetected:
        time.sleep(random.uniform(0.05, 0.2) * (attempt + 1))
else:
    raise

Retries are a safety net, not the fix. In the lab's four-batch scenario (a model result), four transactions with unsorted keys and retries enabled all committed eventually, after four deadlock aborts and about 12 seconds of total waiting; with sorted keys, there were no aborts and about 1.3 seconds of waiting. Each abort also throws away work and holds other transactions back for deadlock_timeout.

Failure modes

  • Sorting in the application but not everywhere. One code path that locks in a different order is enough. Put the ordered lock in a shared function and use it from every writer.
  • Mixed lock targets. Sorting order lines does not help if one path locks the order header first and another locks lines first. Define an order across tables as well: header, then lines by id.
  • Long transactions. A transaction that calls a slow service while holding row locks turns short waits into long ones and makes cycles more likely. Lock late and commit early.
  • Foreign keys and triggers. Updates can take locks on other tables through foreign-key checks and triggers, which the application never names. Include those tables in the lock order.
  • Logging only the error. The client sees 40P01 and process numbers; the server log has the queries. Set log_lock_waits = on to log waits longer than deadlock_timeout as well.

When not to bother

If two code paths never touch the same rows concurrently, there is nothing to order. If a deadlock happens once a month in a job that retries cleanly, an alert and the retry may be enough. Ordered locking matters when the same rows are updated from several places at once and when every abort is expensive.

Verification

The companion probe needs a disposable PostgreSQL server; it drops and recreates a table called order_lines. Run it, then compare the outcome of each case with the recording: the two opposite-order cases abort T1 with 40P01 about one deadlock_timeout after it began to wait, and the ordered cases commit both sessions. In application code, add a test that runs two writers with opposite key orders against a real database and asserts that both commit.

Interactive experiment

Row lock order: two batch updates, a deadlock and deadlock_timeout. Synthetic browser-local fixtures, adjustable inputs, decision traces and JSON export.

Primary references and authorship

Original explanation and synthetic examples by Sandeep Belgavi. Companion code: Sandeep-BA/agent-decision-lab/examples/python/pg_deadlock_lock_order. Views are my own and do not represent any employer, past or present.