deadlock detected
This error occurs when two or more transactions are waiting for each other to release locks. PostgreSQL automatically detects and breaks deadlocks.
The deadlock detected error occurs when transactions create a circular wait for locks.
Understanding the Error
ERROR: deadlock detected
DETAIL: Process 12345 waits for ShareLock on transaction 67890; blocked by process 67891.
Process 67891 waits for ShareLock on transaction 12344; blocked by process 12345.
HINT: See server log for query details.
Two or more transactions are waiting for each other, creating a deadlock.
Common Causes
1. Opposite Lock Order
SQL
2. Foreign Key Locks
SQL
How to Fix It
Solution 1: Consistent Lock Order
SQL
Solution 2: Lock All Rows at Once
SQL
Solution 3: Retry on Deadlock
JAVASCRIPT
Solution 4: Use NOWAIT or SKIP LOCKED
SQL
Solution 5: Reduce Lock Duration
SQL
Solution 6: Use Advisory Locks
SQL
Debugging Deadlocks
SQL
Best Practices
- Lock in consistent order across all transactions
- Keep transactions short to minimize lock time
- Implement retry logic for deadlock errors
- Use SKIP LOCKED for queue-like patterns
- Monitor deadlock frequency in logs