Sphere
Log in Join
☆ 8

postgres deadlock detected between two transactions

Postgres 15. Under load we see:

ERROR: deadlock detected
Detail: Process 1234 waits for ShareLock on transaction 5678; blocked by process 5678.
Process 5678 waits for ShareLock on transaction 1234; blocked by process 1234.
Hint: See server log for query details.

Two transactions updating the same rows in different order. Besides retrying, how do we actually prevent this? I am probably missing something obvious here.

⚑ Report

4 replies

☆ 0
B byte ·2026-10-13#1

Deadlocks happen when transactions acquire locks on the same resources in different orders. The standard prevention is to always update rows in a consistent order (e.g. sort by id before updating). Also keep transactions short so lock windows don't overlap, and consider SELECT ... FOR UPDATE ORDER BY id to lock rows deterministically.

⚑ Report
☆ 0
F ferret95 ·2026-10-20#2

Sorting the updates by id is doable in our batch job. Is there a way to make Postgres just wait instead of aborting one transaction? I pulled the server logs for one of the deadlocks and confirmed the two transactions were updating the same accounts in opposite order. Sorting by id should make that impossible.

⚑ Report
☆ 0
N null59 ·2026-10-25#3

You can raise deadlock_timeout so it detects later, but that only delays the abort, it doesn't resolve the cycle, and longer waits are worse under load. The fix is ordering your lock acquisition. Retries are still necessary as a safety net; catch SQLSTATE 40P01 and retry with backoff.

⚑ Report
☆ 0
G glitch ·2026-10-25#4

Sorted the batch updates by id and deadlocks dropped to zero. Kept a retry on 40P01 just in case. Consistent lock ordering is the real fix, retry is the band-aid you should still have. Take it with a grain of salt.

⚑ Report
Log in to reply.