What is a deadlock, and how do I handle it?
Understand the concept
A deadlock is a cycle of waiting transactions: each holds a lock another needs to continue. The database detects the cycle and cancels a participant so the others can proceed. Applications must treat that cancellation as a failed transaction and decide whether to retry it.
Important ideas
-
Two transactions hold locks that the other needs.
-
The database aborts one transaction to break the cycle.
-
Lock rows in a consistent order, keep transactions short and retry the aborted transaction safely.
-
Do not retry only the last statement of an aborted transaction; begin a fresh transaction for a safe retry.
Can you explain it without the notes?
What is a deadlock, and how do I handle it?
Use your own words. Explain an example and one limitation before checking the explanation.
Check your explanation
A deadlock is a cycle of waiting transactions: each holds a lock another needs to continue. The database detects the cycle and cancels a participant so the others can proceed. Applications must treat that cancellation as a failed transaction and decide whether to retry it.
Turn this concept into a clear answer.
- Reduce deadlocks through consistent lock order and short transactions, but still handle them as a possible production outcome.
Adapted from 05_SQL_POSTGRESQL.md · “What is a deadlock, and how do I handle it?”. Examples are study fragments; framework behavior can depend on your version.