Deadlock
In one line
A deadlock is when two transactions wait for each other's locks — neither can proceed, one must be rolled back.
In simple words
A deadlock happens when:
- Transaction A locks resource X, then tries to lock resource Y
- Transaction B locks resource Y, then tries to lock resource X
- A waits for B to release Y, B waits for A to release X
- Neither can proceed — deadlock!
The database detects deadlocks and resolves them by aborting one transaction (the "victim") with a deadlock error. The application must retry the aborted transaction.
Prevention strategies:
- Consistent lock ordering — always lock resources in the same order
- Short transactions — reduce the window for deadlocks
- Lower isolation — fewer locks = fewer deadlock opportunities
- Lock timeouts — give up waiting after a period
Deadlocks are normal in concurrent systems — handle them with retry logic.
Example
-- Deadlock scenario:
-- Transaction A:
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 1; -- locks account 1
UPDATE accounts SET balance = balance + 100 WHERE id = 2; -- waits for account 2 lock
-- Transaction B (concurrent):
BEGIN;
UPDATE accounts SET balance = balance - 50 WHERE id = 2; -- locks account 2
UPDATE accounts SET balance = balance + 50 WHERE id = 1; -- waits for account 1 lock
-- DEADLOCK! A has 1, wants 2. B has 2, wants 1.
-- Fix: always lock in the same order
-- Transaction B (fixed):
BEGIN;
UPDATE accounts SET balance = balance + 50 WHERE id = 1; -- lock 1 first
UPDATE accounts SET balance = balance - 50 WHERE id = 2; -- then lock 2Deadlock: A locks 1→wants 2, B locks 2→wants 1. Fix: always lock in the same order (1 then 2) to prevent circular dependencies.
Common confusions
Confused with: race condition
The difference: A race condition is about incorrect results from concurrent execution order. A deadlock is about transactions being stuck waiting for each other forever. Race conditions produce wrong answers; deadlocks produce no answer (transactions hang). Deadlocks are detected and resolved; race conditions are subtle bugs.
Related terms
Related Resources
Related Lessons
- Transactions
Deadlocks.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.