Postgres "Deadlock Detected": Kill the Root Cause

Symptom

ERROR 40P01 deadlock detected; one transaction aborts.

Root cause

Two transactions each hold a lock the other needs.

Fix, in order

1. Read the DETAIL lines — they name both statementstail -100 /var/log/postgresql/*.log | grep -A4 deadlock
2. Touch rows in a consistent order everywhereUPDATE ... WHERE id IN (SELECT id FROM t ORDER BY id FOR UPDATE)
3. Keep transactions shortBEGIN late, COMMIT early; no user waits inside a txn

Prevent it coming back

Lock ordering conventions + statement timeouts (lock_timeout 5s).

Run it on clean infra

Spinning up a fresh box to reproduce or escape this error?

Managed cloud hosting

Related

Cloud & DevOps tool comparisons · Hardware build guides

NinjaOps publishes free engineering guides. Some outbound links are affiliate links: they cost you nothing and support the site.

Last reviewed 2026-10-02 · NinjaOps SEO grid · DevOps blog