Skip to content

Deadlock detected: transaction aborted

Quick summary

Your transaction was chosen as the deadlock victim — another transaction holds a lock you need and vice versa.

Why this happens

  • Two transactions acquire locks on the same resources in different orders

  • Long-running transactions hold locks for extended periods, increasing deadlock probability

  • Bulk operations without proper ordering lock many rows and conflict with concurrent transactions

Minimal example

✗ Broken code
// Transaction A: locks row 1 then row 2
await db.query('UPDATE accounts SET bal = bal - 100 WHERE id = 1');
await db.query('UPDATE accounts SET bal = bal + 100 WHERE id = 2');
// Transaction B (concurrent): locks row 2 then row 1 = deadlock!
✓ Fixed code
// Both transactions: always lock in ascending id order
await db.query('UPDATE accounts SET bal = bal - 100 WHERE id = 1');
await db.query('UPDATE accounts SET bal = bal + 100 WHERE id = 2');
// Transaction B also locks id=1 first, then id=2 — no deadlock

Acquiring locks in a consistent order (ascending id) prevents the circular wait condition that causes deadlocks.

How to diagnose

  • Check the database error log for deadlock details and the involved transactions

  • Review the SQL statements in both transactions to identify the lock ordering conflict

  • Use database monitoring tools to trace lock acquisition and identify the deadlock cycle

How to fix

  • Acquire locks in a consistent order across all transactions to prevent circular waits

  • Keep transactions short and commit quickly to reduce the window for deadlocks

  • Add retry logic to re-run the transaction when a deadlock error is caught

How to prevent

  • Always access tables and rows in a consistent order across all transactions

  • Use appropriate isolation levels and keep transactions as short as possible

Related Resources

Related Glossary

Related Lessons

← Back to language