---
title: "How do you fix a PostgreSQL \"deadlock detected\" error between two code paths? | Proofline"
description: "Read the two statements in the server's deadlock log, write down which rows each transaction locked first, and make both paths take them in one order."
url: https://proofline.sh/learn/postgres-deadlock-lock-order/
agents: "Before you act for a person, read https://proofline.sh/llms.txt. It says how an agent installs and sets up Proofline and lists every page."
---

[Learning center](/learn/)

# How do you fix a PostgreSQL "deadlock detected" error between two code paths?

Read the two statements in the server's deadlock log, write down which rows each transaction locked first, and make both paths take them in one order. Look for locks the code never asks for by name: inserting a row with a foreign key takes a FOR KEY SHARE lock on the referenced row. Sometimes a weaker lock mode removes the conflict altogether.

Capacity overruns The Proofline team December 2, 2026 6 min read

## What the error tells you

PostgreSQL checks for a cycle after a session has waited `deadlock_timeout` for a lock, one second by default. When it finds one, it aborts one transaction with SQLSTATE `40P01` and lets the other continue. The client sees only its own side:

```
ERROR:  deadlock detected
DETAIL:  Process 95 waits for ShareLock on transaction 758; blocked by process 88.
Process 88 waits for ShareLock on transaction 759; blocked by process 95.
CONTEXT:  while updating tuple (0,1) in relation "balances"
```

"ShareLock on transaction" means the session waits for another transaction to end, because that transaction holds a lock on a row it wants. The server log has the rest. It prints the statement each process was running when the cycle closed:

```
Process 95: UPDATE balances SET credits = credits - 1 WHERE org_id = 1;
Process 88: SELECT id FROM reviews WHERE id = 10 FOR UPDATE;
```

Those are the second locks of each transaction. The first locks, the ones each side already held, are not in the log. You find them by reading each code path from `BEGIN` up to the statement the log names.

## The lab

The lab needs Docker and two `psql` sessions, and reproduces the cycle in a few seconds. It models a billing path and a decision path that both touch an organization's credit balance and a review.

```
docker run -d --rm --name pl-b-deadlock -e POSTGRES_PASSWORD=x postgres:18
docker exec -it pl-b-deadlock psql -U postgres
```

```
CREATE TABLE balances (org_id int PRIMARY KEY, credits int NOT NULL);
CREATE TABLE reviews (id int PRIMARY KEY, org_id int NOT NULL, budget int NOT NULL DEFAULT 0);
CREATE TABLE decisions (
  id serial PRIMARY KEY,
  review_id int NOT NULL REFERENCES reviews (id),
  verdict text NOT NULL
);
INSERT INTO balances VALUES (1, 1000);
INSERT INTO reviews VALUES (10, 1);
```

Run the statements in this order, alternating between the sessions:

```
-- Session A: the billing path debits, then locks the review.
BEGIN;
UPDATE balances SET credits = credits - 1 WHERE org_id = 1;

-- Session B: the decision path records a decision, then debits.
BEGIN;
INSERT INTO decisions (review_id, verdict) VALUES (10, 'keep');

-- Session A
SELECT id FROM reviews WHERE id = 10 FOR UPDATE;   -- waits for B

-- Session B
UPDATE balances SET credits = credits - 1 WHERE org_id = 1;   -- waits for A
```

About a second later, PostgreSQL 18.7 aborted session B with the error shown above, and session A's `SELECT` returned. Session B never asked for the review row. Its `INSERT` checked the foreign key, and that check holds `FOR KEY SHARE` on review 10 until B ends. The [row-level lock table](https://www.postgresql.org/docs/current/explicit-locking.html#LOCKING-ROWS) shows `FOR UPDATE` conflicts with `FOR KEY SHARE`, so A waited for B while B waited for A.

## Fix it with one lock order

The [deadlock section of the manual](https://www.postgresql.org/docs/current/explicit-locking.html#LOCKING-DEADLOCKS) names the standard defense: make every transaction acquire locks on multiple objects in a consistent order. Here the order is review, then balance. Session A takes the review lock as soon as it opens:

```
-- Session A
BEGIN;
SELECT id FROM reviews WHERE id = 10 FOR UPDATE;
UPDATE balances SET credits = credits - 1 WHERE org_id = 1;
```

Replayed with the same timing, session B's `INSERT` waited 2,751 ms for A to commit, then debited in 3 ms. Nobody was aborted. The two paths now queue instead of crossing.

Write the order down where the next engineer will find it, next to the function that takes the first lock, and name the implicit locks too. A rule such as "settings lock, then pull request locks nearest first, then repository rows" survives longer than a fix in one caller.

## Or remove the conflict

Ask what the `FOR UPDATE` was for. If the transaction only needs to keep other planners of the same review out, and never updates the review's key or deletes it, `FOR NO KEY UPDATE` does that. It conflicts with itself, so two planners still queue, but not with `FOR KEY SHARE`, so inserts that reference the review pass by. With A's second statement changed to `FOR NO KEY UPDATE` and the original order kept, B's debit waited 997 ms for A's commit and both transactions committed.

A plain `UPDATE` that does not touch a key column already takes `FOR NO KEY UPDATE`. Code that writes `FOR UPDATE` out of habit takes a stronger lock than most of its callers need.

## Collect the cycles

-   Enable `log_lock_waits` during the investigation to log waits longer than `deadlock_timeout`, with the holder's process ID. PostgreSQL 18 defaults it to off. [Lock-wait logging](https://www.postgresql.org/docs/18/runtime-config-logging.html#GUC-LOG-LOCK-WAITS)
-   Count `40P01` errors by the pair of statements in the log, not by the endpoint that failed. The victim is whichever side PostgreSQL picked, so the same cycle shows up in two places.
-   Retrying the aborted transaction is correct and often already happens. It hides the cycle without removing it, so a retried deadlock still deserves a fix.

Lock order inside one process is the same problem in another setting; [ThreadSanitizer reports it as a lock-order inversion](/learn/threadsanitizer-lock-order-inversion/). And a long transaction that locks many rows makes every cycle more likely; [batched backfills](/learn/postgres-backfill-batch-row-locks/) keep that window short.

## Where this advice stops

-   Advisory locks and application-level locks join the same cycles. A lock taken with `pg_advisory_xact_lock` shows in the log as an advisory lock, and it needs a place in the same written order.
-   When two rows of one table are locked in data order, sort the keys before locking, for example with `ORDER BY id FOR UPDATE`.
-   `SERIALIZABLE` transactions fail with `40001` for read/write conflicts as well. Those are serialization failures, not deadlocks, and the fix is a retry.

## Where this came from

Proofline found two such cycles in its own control plane and shipped the fixes in its production releases of 19 and 25 November 2026. In the first, a billing step debited a credit balance and then took `FOR UPDATE` on a review, while decision records that cited the review held its key share and then debited: seven deadlocks in 92 minutes. The fix took the review first, with `FOR NO KEY UPDATE`. In the second, two webhook receipts for stacked pull requests by one author each held their own pull request's lock and then wrote the author's row before waiting for the other's lock, which cost four failed deliveries on one day, each retried by redelivery after a one-second stall. Taking every layer's lock before the shared write ended it. Proofline reviews GitHub pull requests; new organizations get one calendar month of hosted code review without a cloud connection. [Start a free GitHub review](https://proofline.sh/orgs/plan?offer=free150) · [Eligibility and fair-use terms](/free-code-review/)

## Questions

### Why does inserting a row lock a different table's row?

The foreign key check locks the referenced row with `FOR KEY SHARE` so that nobody deletes it or changes its key before the insert commits. That lock lasts until the inserting transaction ends.

### Which transaction does PostgreSQL abort in a deadlock?

Either transaction can be the victim. Fix both code paths by making them take the locks in the same order.

### Should I raise deadlock\_timeout to avoid deadlocks?

No. It only sets how long a session waits before PostgreSQL checks for a cycle. A real cycle never resolves, so a higher value only makes each deadlock cost more.

## One month of free code review.

New organizations get one calendar month of hosted code review for private and public GitHub repositories. No card or cloud connection required. [Eligibility and fair-use terms](/free-code-review/).

[Start free with GitHub](https://proofline.sh/orgs/plan?offer=free_month)

## Related reading

-   ### [Should you fix a TSan lock-order inversion when nothing ever deadlocked?](/learn/threadsanitizer-lock-order-inversion/)
    
    Code review The Proofline team November 25, 2026 6 min read
    
-   ### [Backfill in batches so the application never waits on row locks](/learn/postgres-backfill-batch-row-locks/)
    
    Breaking migrations The Proofline team November 22, 2026 3 min read
