Deadlocks
Waiting for each other
Section titled “Waiting for each other”T1 moves 10 from account A to account B. T2 moves 20 from B to A. Each takes from its own source account first.
T1 locks A. T2 locks B. Now T1 wants B and T2 wants A. T1 waits for T2, who waits for T1. Neither can proceed, and neither will ever release a lock, because both hold their locks until they end. That is a deadlock: a cycle of transactions, each waiting for a lock that the next one holds.
Mental model. A deadlock is two people in a corridor each holding a door the other needs. Waiting longer does not help. Someone has to back out.
The database finds it and breaks it
Section titled “The database finds it and breaks it”Deadlock
Accounts A and B hold 100 each. T1 moves 10 from A to B. T2 moves 20 from B to A. Each updates the account it takes from first.
What to watch Look at who waits for whom, and how the database gets out.
A read waits if another transaction has written the row and not committed, then lets go of its lock at once. Writes lock the row until the end.
- T1
UPDATE A = A − 10T1 writes 90 to A. It is not committed yet. - T2
UPDATE B = B − 20T2 writes 80 to B. It is not committed yet. - T1
UPDATE B = B + 10Has to waitT1 has to wait for T2, because of a lock on B. - T2
UPDATE A = A + 20AbortedDeadlock: T2 waits for T1, T1 waits for T2. The database aborts T2, whose request closed the cycle, and releases its locks. - T1
UPDATE B = B + 10ResumedT1 writes 110 to B. It is not committed yet. - T1
COMMITT1 commits. - T2
COMMITNot runT2 was aborted, so this statement does not run.
State after this step
| Row | Committed | Not committed | Locks held |
|---|---|---|---|
A | 90 | none | none |
B | 110 | none | none |
| Transaction | Status | Values read so far |
|---|---|---|
| T1 Moves 10 from A to B | Committed | none |
| T2 Moves 20 from B to A | Aborted | none |
Outcome
No anomaly happened in this run.
- T2 was aborted by the database (deadlock). An application would retry it.
- Waited for another transaction to finish: T1.
- Committed values at the end: A = 90, B = 110.
| Isolation level | Locks | MVCC (row versions) |
|---|---|---|
| Read uncommitted | No anomalyT2 aborted: deadlockWaiting: T1 | No anomalyT2 aborted: deadlockWaiting: T1 |
| Read committed | No anomalyT2 aborted: deadlockWaiting: T1 (shown above) | No anomalyT2 aborted: deadlockWaiting: T1 |
| Repeatable read | No anomalyT2 aborted: deadlockWaiting: T1 | No anomalyT2 aborted: deadlockWaiting: T1 |
| Serializable | No anomalyT2 aborted: deadlockWaiting: T1 | No anomalyT2 aborted: deadlockWaiting: T1 |
Model notes
Assumptions
- The levels have the names of the SQL standard, but real databases differ. In PostgreSQL, read uncommitted behaves as read committed, and repeatable read is snapshot isolation: no phantom reads, but write skew is possible. In MySQL’s InnoDB, read uncommitted can read uncommitted data, and locking reads lock index ranges to stop phantoms. This lab shows a textbook model, not any one product.
- Locks follows the locking definitions in Berenson et al., A Critique of ANSI SQL Isolation Levels (1995): write locks are held until the end at every level; read locks are absent at read uncommitted, released at once at read committed, held on rows until the end at repeatable read (a search is locked only while it runs), and held on rows and searches until the end at serializable.
- MVCC follows PostgreSQL’s documentation: a read never waits and sees a committed version of a row, from a snapshot taken at the first statement at repeatable read and serializable, and two writers of the same row wait for each other. At repeatable read and serializable, the writer that waited is aborted if the first one commits.
- Serializable with MVCC aborts a transaction at commit when committing it would make the dependencies between the committed transactions form a cycle. PostgreSQL’s serializable level uses a related method, and its documentation warns that it can raise errors that would not occur in a true serial execution.
- A deadlock is resolved by aborting the transaction whose request closed the cycle. Databases choose differently (PostgreSQL’s documentation says which one is aborted is difficult to predict), and the application has to retry the transaction that was aborted. With locks, two transactions that each hold a read lock on a row and then both want to write it deadlock, which is what happens at repeatable read and serializable in the lost-update and write-skew schedules.
Simplifications
- Each lab runs one fixed interleaving. A level that avoids an anomaly in this schedule can still allow it in another, and a transaction that has to wait changes the timing of the statements behind it.
- A statement is one atomic step. There are no timeouts, no indexes and no gap or next-key locks, a statement waits until every transaction it waits for has finished, and an aborted transaction is not retried. Durability, the log and crashes are not modelled.
- A search matches rows by the start of their name and, if one is given, an exact value. A lock on a search, and a conflict with it, looks at both the old and the new value of a row that is written.
Parameter values are illustrative. They are not benchmarks of any real product.
Step through it. T1 writes A, and T2 writes B. At step 3, T1 has to wait for T2. At step 4 the cycle forms: T2 waits for T1 and T1 waits for T2. The database detects the cycle and aborts T2, whose request closed it, and releases T2’s locks. T1 then gets B and commits. A ends at 90 and B at 110, which is T1’s transfer alone.
Both databases whose documentation this course read do the same thing in outline. PostgreSQL detects deadlocks and resolves them by aborting one of the transactions involved, so the others can complete. InnoDB, with deadlock detection on (its default), rolls back one transaction, the victim.
Which transaction is the victim is the database’s choice. In the lab it is the one whose request closed the cycle. PostgreSQL’s documentation says that which one it aborts is difficult to predict and should not be relied upon. InnoDB can also be configured with deadlock detection off, and then it relies on a lock wait timeout to roll transactions back.
The application has to retry
Section titled “The application has to retry”The aborted transaction is not finished: it did nothing, and its caller got an error. InnoDB’s documentation says that even if your application logic is correct, you must still handle the case where a transaction has to be retried.
In the lab, T2’s transfer of 20 from B to A did not happen. Rerun it now on A = 90 and B = 110: A becomes 110, and B becomes 90. Retrying was the right answer, and it is only safe because the aborted transaction left nothing behind. That is atomicity, from the first lesson, doing its job.
Take the rows in the same order
Section titled “Take the rows in the same order”The deadlock needed the two transfers to take their rows in opposite orders. If both take A first, one of them gets A, and the other waits for it before it holds anything.
Same locks, same order
The same two transfers, but both update A first and then B.
What to watch Does anyone wait, and does anyone have to be aborted?
A read waits if another transaction has written the row and not committed, then lets go of its lock at once. Writes lock the row until the end.
- T1
UPDATE A = A − 10T1 writes 90 to A. It is not committed yet. - T2
UPDATE A = A + 20Has to waitT2 has to wait for T1, because of a lock on A. - T1
UPDATE B = B + 10T1 writes 110 to B. It is not committed yet. - T2
UPDATE B = B − 20QueuedT2 is still waiting for T1, so this statement waits behind it. - T1
COMMITT1 commits. - T2
UPDATE A = A + 20ResumedT2 writes 110 to A. It is not committed yet. - T2
UPDATE B = B − 20ResumedT2 writes 90 to B. It is not committed yet. - T2
COMMITT2 commits.
State after this step
| Row | Committed | Not committed | Locks held |
|---|---|---|---|
A | 110 | none | none |
B | 90 | none | none |
| Transaction | Status | Values read so far |
|---|---|---|
| T1 Moves 10 from A to B | Committed | none |
| T2 Moves 20 from B to A, A first | Committed | none |
Outcome
No anomaly happened in this run.
- The result is the same as running T1, T2 one at a time, in that order.
- Waited for another transaction to finish: T2.
- Committed values at the end: A = 110, B = 90.
| Isolation level | Locks | MVCC (row versions) |
|---|---|---|
| Read uncommitted | No anomalyWaiting: T2 | No anomalyWaiting: T2 |
| Read committed | No anomalyWaiting: T2 (shown above) | No anomalyWaiting: T2 |
| Repeatable read | No anomalyWaiting: T2 | No anomalyT2 aborted: serialization failure, concurrent updateWaiting: T2 |
| Serializable | No anomalyWaiting: T2 | No anomalyT2 aborted: serialization failure, concurrent updateWaiting: T2 |
Model notes
Assumptions
- The levels have the names of the SQL standard, but real databases differ. In PostgreSQL, read uncommitted behaves as read committed, and repeatable read is snapshot isolation: no phantom reads, but write skew is possible. In MySQL’s InnoDB, read uncommitted can read uncommitted data, and locking reads lock index ranges to stop phantoms. This lab shows a textbook model, not any one product.
- Locks follows the locking definitions in Berenson et al., A Critique of ANSI SQL Isolation Levels (1995): write locks are held until the end at every level; read locks are absent at read uncommitted, released at once at read committed, held on rows until the end at repeatable read (a search is locked only while it runs), and held on rows and searches until the end at serializable.
- MVCC follows PostgreSQL’s documentation: a read never waits and sees a committed version of a row, from a snapshot taken at the first statement at repeatable read and serializable, and two writers of the same row wait for each other. At repeatable read and serializable, the writer that waited is aborted if the first one commits.
- Serializable with MVCC aborts a transaction at commit when committing it would make the dependencies between the committed transactions form a cycle. PostgreSQL’s serializable level uses a related method, and its documentation warns that it can raise errors that would not occur in a true serial execution.
- A deadlock is resolved by aborting the transaction whose request closed the cycle. Databases choose differently (PostgreSQL’s documentation says which one is aborted is difficult to predict), and the application has to retry the transaction that was aborted. With locks, two transactions that each hold a read lock on a row and then both want to write it deadlock, which is what happens at repeatable read and serializable in the lost-update and write-skew schedules.
Simplifications
- Each lab runs one fixed interleaving. A level that avoids an anomaly in this schedule can still allow it in another, and a transaction that has to wait changes the timing of the statements behind it.
- A statement is one atomic step. There are no timeouts, no indexes and no gap or next-key locks, a statement waits until every transaction it waits for has finished, and an aborted transaction is not retried. Durability, the log and crashes are not modelled.
- A search matches rows by the start of their name and, if one is given, an exact value. A lock on a search, and a conflict with it, looks at both the old and the new value of a row that is written.
Parameter values are illustrative. They are not benchmarks of any real product.
T1 writes A. T2 wants A and has to wait. T1 writes B and commits, and then T2 writes A and B and commits. Nobody is aborted, and A ends at 110 and B at 90. PostgreSQL’s documentation calls this the best defence against deadlocks: make sure that all applications acquire locks on multiple objects in a consistent order. InnoDB’s advice is the same, to use the same order of operations in every transaction.
Two limits are worth knowing:
- Ordering prevents the cycle, not the waiting. T2 still waited. The price of the order is that transactions queue.
- It has to be everywhere. One piece of code that takes the rows the other way round can bring the deadlock back.
There is one more catch, which shows how the pieces of this module fit. Run the same ordered schedule with row versions at repeatable read: there is no deadlock, but T2 is still aborted with a serialization failure when T1 commits, because T1 changed A after T2’s snapshot. The database stopped one problem and the isolation level raised another, which the application also has to retry.
Three in a ring
Section titled “Three in a ring”A deadlock does not need exactly two transactions.
Deadlock between three
Three transactions each add 1 to two of the rows A, B and C, in a ring: T1 takes A then B, T2 takes B then C, T3 takes C then A.
What to watch Follow the chain of waiting around the ring.
A read waits if another transaction has written the row and not committed, then lets go of its lock at once. Writes lock the row until the end.
- T1
UPDATE A = A + 1T1 writes 1 to A. It is not committed yet. - T2
UPDATE B = B + 1T2 writes 1 to B. It is not committed yet. - T3
UPDATE C = C + 1T3 writes 1 to C. It is not committed yet. - T1
UPDATE B = B + 1Has to waitT1 has to wait for T2, because of a lock on B. - T2
UPDATE C = C + 1Has to waitT2 has to wait for T3, because of a lock on C. - T3
UPDATE A = A + 1AbortedDeadlock: T3 waits for T1, T1 waits for T2, T2 waits for T3. The database aborts T3, whose request closed the cycle, and releases its locks. - T2
UPDATE C = C + 1ResumedT2 writes 1 to C. It is not committed yet. - T1
COMMITQueuedT1 is still waiting for T2, so this statement waits behind it. - T2
COMMITT2 commits. - T1
UPDATE B = B + 1ResumedT1 writes 2 to B. It is not committed yet. - T1
COMMITResumedT1 commits. - T3
COMMITNot runT3 was aborted, so this statement does not run.
State after this step
| Row | Committed | Not committed | Locks held |
|---|---|---|---|
A | 1 | none | none |
B | 2 | none | none |
C | 1 | none | none |
| Transaction | Status | Values read so far |
|---|---|---|
| T1 Updates A, then B | Committed | none |
| T2 Updates B, then C | Committed | none |
| T3 Updates C, then A | Aborted | none |
Outcome
No anomaly happened in this run.
- The result is the same as running T2, T1 one at a time, in that order.
- T3 was aborted by the database (deadlock). An application would retry it.
- Waited for another transaction to finish: T1, T2.
- Committed values at the end: A = 1, B = 2, C = 1.
| Isolation level | Locks | MVCC (row versions) |
|---|---|---|
| Read uncommitted | No anomalyT3 aborted: deadlockWaiting: T1, T2 | No anomalyT3 aborted: deadlockWaiting: T1, T2 |
| Read committed | No anomalyT3 aborted: deadlockWaiting: T1, T2 (shown above) | No anomalyT3 aborted: deadlockWaiting: T1, T2 |
| Repeatable read | No anomalyT3 aborted: deadlockWaiting: T1, T2 | No anomalyT3 aborted: deadlockT1 aborted: serialization failure, concurrent updateWaiting: T1, T2 |
| Serializable | No anomalyT3 aborted: deadlockWaiting: T1, T2 | No anomalyT3 aborted: deadlockT1 aborted: serialization failure, concurrent updateWaiting: T1, T2 |
Model notes
Assumptions
- The levels have the names of the SQL standard, but real databases differ. In PostgreSQL, read uncommitted behaves as read committed, and repeatable read is snapshot isolation: no phantom reads, but write skew is possible. In MySQL’s InnoDB, read uncommitted can read uncommitted data, and locking reads lock index ranges to stop phantoms. This lab shows a textbook model, not any one product.
- Locks follows the locking definitions in Berenson et al., A Critique of ANSI SQL Isolation Levels (1995): write locks are held until the end at every level; read locks are absent at read uncommitted, released at once at read committed, held on rows until the end at repeatable read (a search is locked only while it runs), and held on rows and searches until the end at serializable.
- MVCC follows PostgreSQL’s documentation: a read never waits and sees a committed version of a row, from a snapshot taken at the first statement at repeatable read and serializable, and two writers of the same row wait for each other. At repeatable read and serializable, the writer that waited is aborted if the first one commits.
- Serializable with MVCC aborts a transaction at commit when committing it would make the dependencies between the committed transactions form a cycle. PostgreSQL’s serializable level uses a related method, and its documentation warns that it can raise errors that would not occur in a true serial execution.
- A deadlock is resolved by aborting the transaction whose request closed the cycle. Databases choose differently (PostgreSQL’s documentation says which one is aborted is difficult to predict), and the application has to retry the transaction that was aborted. With locks, two transactions that each hold a read lock on a row and then both want to write it deadlock, which is what happens at repeatable read and serializable in the lost-update and write-skew schedules.
Simplifications
- Each lab runs one fixed interleaving. A level that avoids an anomaly in this schedule can still allow it in another, and a transaction that has to wait changes the timing of the statements behind it.
- A statement is one atomic step. There are no timeouts, no indexes and no gap or next-key locks, a statement waits until every transaction it waits for has finished, and an aborted transaction is not retried. Durability, the log and crashes are not modelled.
- A search matches rows by the start of their name and, if one is given, an exact value. A lock on a search, and a conflict with it, looks at both the old and the new value of a row that is written.
Parameter values are illustrative. They are not benchmarks of any real product.
T1 takes A, then wants B. T2 takes B, then wants C. T3 takes C, then wants A. Each waits for the next, and the cycle closes when T3 asks for A. The database aborts T3. T1 and T2 commit, and the rows end at A = 1, B = 2 and C = 1.
Ordered locking would have prevented this one too, in the same way: if all three took A, then B, then C, there would be no ring.
What happens if there is no detection?
Section titled “What happens if there is no detection?”If the database did not look for cycles, T1 and T2 would wait forever. Real systems have a safety net, which is a timeout on lock waits, and a timeout has a cost: it cannot tell a deadlock from a transaction that is only slow, so it aborts both kinds. InnoDB can run without detection and rely on innodb_lock_wait_timeout instead. Detection is what lets the database abort a transaction only when waiting cannot end.
An application that retries immediately in a loop can recreate the cycle. A retry that starts after a short random pause can make it less likely that the same two transactions collide again.
- A deadlock is a cycle of transactions, each waiting for a lock held by the next. Waiting longer cannot end it.
- The database finds the cycle and aborts one transaction. Which one is its choice, and the application should not depend on it.
- The aborted transaction left nothing behind, so the application retries it. In the lab, T2 is aborted and A and B end at 90 and 110.
- Taking the rows in one fixed order prevents the cycle, at the price of some waiting. With the same order, T2 waits and A and B end at 110 and 90.
- A ring of three deadlocks the same way, and the database aborts T3.
Next: recap and quiz, the module on one page, and questions that cover all five lessons.
Your progress
Built by GhaziAlibi.
© ShardCraft. All rights reserved.