How does PostgreSQL handle deadlocks?

Answer

A deadlock occurs when two or more transactions are each waiting for a lock held by the other. PostgreSQL automatically detects deadlocks using a deadlock detection algorithm that runs when a lock wait exceeds deadlock_timeout (default 1 second). When detected, PostgreSQL aborts one of the transactions (the "victim") with error code 40P01. The aborted transaction must be retried by the application. Prevention strategies: (1) Always acquire locks in a consistent order (e.g., always lock user before order). (2) Use SELECT ... FOR UPDATE SKIP LOCKED for job queues to avoid contention. (3) Keep transactions short. (4) Use LOCK TABLE ... NOWAIT to fail immediately instead of waiting. (5) Monitor with pg_locks joined with pg_stat_activity. Log deadlocks: log_lock_waits = on in postgresql.conf.