Understanding, Detecting & Preventing Deadlocks
Detect deadlock cycles and prevent them with consistent lock ordering.
In plain words
Two transactions each wait for something the other is holding, forever. The database spots it and cancels one so the other can finish.
Think of it like…
Two cars meet on a narrow bridge from opposite ends; each needs the other to back up. Someone has to reverse (the database aborts one transaction) before either can cross.
Where you’ve seen it
Two transfers run at once: T1 moves money from account 1 to 2, T2 from account 2 to 1. T1 locks account 1, T2 locks account 2, then each tries to lock the other. Updating accounts in ascending id order in every transfer makes the cycle impossible.
Words you’ll hear
- Lock wait
- A transaction blocked until another releases a lock; normal and temporary.
- Deadlock cycle
- T1 waits for T2 while T2 waits for T1; it can never resolve itself.
- Deadlock detection
- The database periodically checks waiting transactions for cycles and aborts a victim.
- Lock ordering
- Always acquiring locks in the same global order, which prevents cycles.
Visual diagram
Theory & example queries
How deadlocks form and get resolved
A deadlock needs at least two transactions acquiring the same locks in different orders. Each succeeds with its first lock, then blocks on a lock the other already holds. Unlike a normal lock wait, nothing will ever release, because each is waiting on the other.
Databases detect this automatically. PostgreSQL checks for cycles after a transaction has waited for deadlock_timeout (1 second by default), then aborts one participant with "deadlock detected". InnoDB detects them immediately. The error is your signal to roll back and retry the whole transaction.
| id | owner | balance |
|---|---|---|
| 1 | Maya | 1000 |
| 2 | Ravi | 500 |
BEGIN;UPDATE accountsSET balance = balance - 100WHERE id = 1;PostgreSQL is the lesson baseline unless noted otherwise.
Open a transaction so changes can be checked and committed or rolled back together.
BEGIN;UPDATE accountsSET balance = balance - 100WHERE id = 2;PostgreSQL is the lesson baseline unless noted otherwise.
Open a transaction so changes can be checked and committed or rolled back together.
UPDATE accounts …WHERE id = 2;PostgreSQL is the lesson baseline unless noted otherwise.
Identify the table or database object the statement will modify.
UPDATE accounts …WHERE id = 1;PostgreSQL is the lesson baseline unless noted otherwise.
Identify the table or database object the statement will modify.
Expected output
Note: Representative PostgreSQL result; lock-wait wording and which session is rolled back are engine- and timing-dependent.
Session 1:
Session 2:
Session 1:
(waits) Session 2:
→ deadlock detected.
Key takeaway: Different lock orders plus concurrency create cycles; the database breaks them by aborting one.
Preventing and handling them
Acquire locks in a consistent order everywhere: for transfers, lock or update the lower account id first, regardless of direction. When a transaction will touch several rows, lock them all up front with SELECT … WHERE id IN (…) ORDER BY id FOR UPDATE. Keep transactions short, never wait for user input inside one, and index foreign key columns so checks don't lock or scan more rows than necessary.
Even with good design, rare deadlocks can still happen under load, so treat them like serialization failures: catch the error and retry the transaction a few times with a short backoff. Investigate with PostgreSQL's server log (which records the statements involved) or MySQL's SHOW ENGINE INNODB STATUS (LATEST DETECTED DEADLOCK).
| id | owner | balance |
|---|---|---|
| 1 | Maya | 1000 |
| 2 | Ravi | 500 |
SELECT idFROM accountsWHERE id IN ($from, $to)ORDER BY id FORUPDATE;PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Expected output2 sample rows
| id |
|---|
| 1 |
| 2 |
Note: Illustrative result for $from = 2 and $to = 1; the selected rows are locked in ascending ID order.
then perform both UPDATEs. Every transfer locks the lower id first, so two transfers can't lock in opposite orders.
Key takeaway: Consistent ordering prevents most deadlocks; retries handle the rest.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Find the transactions involved
Read the deadlock report in the PostgreSQL log or SHOW ENGINE INNODB STATUS to see which statements and rows were in the cycle.
ERROR: deadlock detected
When to use it & trade-offs
What it is
A deadlock happens when two (or more) transactions each hold a lock the other needs, so neither can continue. The database detects the cycle, aborts one transaction with an error (PostgreSQL SQLSTATE 40P01, MySQL error 1213), and lets the other finish. The aborted transaction must be retried.
Why it matters: Deadlocks show up under real concurrency, typically as intermittent errors in production that never happen in testing. You can't eliminate the possibility entirely, but consistent lock ordering and short transactions make them rare, and retry logic makes them harmless. It's a standard question for backend and database roles.
When to reach for it
- Money transfers and other two-row updates
- Batch jobs that update many rows while users write too
- Diagnosing intermittent "deadlock detected" errors
When to avoid or be careful
- Updating related rows in whatever order the request happens to list them
- Long transactions that mix reads, external calls and writes
- Ignoring deadlock errors instead of retrying
Deadlock prevention techniques
Strengths: Removes the cycle that causes most deadlocks.
Watch out: Every code path has to follow the same rule.
Strengths: Fewer and shorter lock overlaps.
Watch out: May lock rows slightly earlier than strictly needed.
Strengths: Makes the rare remaining deadlocks invisible to users.
Watch out: Doesn't fix frequent deadlocks; hides design problems if overused.
Interview signals & numbers to know
When this topic comes up
- "deadlock detected" in logs
- Intermittent failures under load
- “What is a deadlock and how do you prevent it?”
- Transfers between accounts
- Concurrent batch updates
Benchmarks & rules of thumb
- 40P01
- PostgreSQL deadlock SQLSTATE
- 1213
- MySQL deadlock error code
- 1 s
- PostgreSQL default deadlock_timeout
Common mistakes & follow-ups
Common interview mistakes
- Confusing a long lock wait with a deadlock; waits resolve, deadlocks don't.
- Locking the source account first in a transfer, so opposite-direction transfers deadlock.
- Treating a deadlock error as fatal instead of retrying the transaction.
Likely interviewer follow-ups
- How would you prevent deadlocks between concurrent money transfers?
- What's the difference between a lock wait and a deadlock?
- How do you find out which queries were involved in a deadlock?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Understanding, Detecting & Preventing Deadlocks with hands-on SQL practice and interview Q&A.