SQLSTATE 40P01 is deadlock_detected. Two or more transactions form a cycle: each holds a lock another needs. PostgreSQL aborts one participant so others can proceed. This is not simply a slow query or any lock wait, and the victim transaction is not necessarily the code that created the underlying ordering problem.
Concurrent workflows update the same rows or tables in different orders, such as one touching record A then B while another touches B then A.
Triggers, foreign-key checks, explicit locks, or lock upgrades acquire additional locks that the application's visible SQL does not make obvious.
Transactions hold locks during network calls, user interaction, or oversized batches, increasing overlap with other operations.
How to fix it
Collect the server deadlock DETAIL, involved statements, transaction boundaries, and application request identifiers. Reconstruct the full sequence on every side of the cycle rather than blaming only the statement that received the error.
For an ongoing reproduction, inspect pg_stat_activity, pg_locks, and pg_blocking_pids(pid) with suitable monitoring privileges. After PostgreSQL resolves the deadlock, that live cycle may already be gone, so preserve the original log evidence.
Make competing code paths acquire shared resources in a consistent, deterministic order, including rows reached through triggers. Avoid unnecessary lock upgrades and test multi-row operations concurrently rather than relying on a single-session test.
Keep transactions focused on database work. Move unrelated remote calls outside the lock-holding window and reduce batch sizes when doing so preserves the required atomicity. Raising deadlock_timeout changes detection timing; it does not remove the cycle.
On 40P01, roll back and retry the complete transaction with fresh reads, a bounded retry budget, and randomized backoff. Make external side effects idempotent or defer them until commit. Never retry only the last statement inside the failed transaction, and do not kill unrelated sessions as a routine workaround.