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.
Previous
What is table bloat in PostgreSQL and how do you fix it?
Next
What are advisory locks vs regular locks in PostgreSQL?
More PostgreSQL Questions
View all →- Advanced What is the query planner in PostgreSQL and how does it work?
- Advanced What causes poor query plans and how do you fix them?
- Advanced What is logical replication in PostgreSQL?
- Advanced How do you implement row-level security (RLS) in PostgreSQL?
- Advanced What is table bloat in PostgreSQL and how do you fix it?