What Is a Deadlock?
Two transactions each hold a lock the other needs, so both wait forever. InnoDB detects the cycle immediately, chooses a victim (usually the one that changed fewer rows), rolls it back and returns error 1213. The other transaction then continues.
A Real Reproduction
This is the real output of two connections that follow exactly that order:
B was chosen as the victim and rolled back. A committed, so the final balances are 90 and 110: A's transfer was applied, B's was not. B's application code must run the transfer again.
Reading the Last Deadlock
These commands need administrator privileges and print server-specific text, so they are shown without output.
How to Prevent Most Deadlocks
- Same order everywhere. Always touch rows (or tables) in the same order, for example lowest id first. A transfer between accounts 1 and 2 should lock id 1 before id 2 regardless of direction.
- Short transactions. Less time holding locks means fewer collisions.
- Lock by index. Statements without a usable index lock many rows.
- Use
READ COMMITTEDif gap locks cause conflicts and phantoms are acceptable. - Lock what you need at once with one
SELECT ... ORDER BY id FOR UPDATEbefore updating.
Result:
| id |
|---|
| 1 |
| 2 |
Result:
| id | balance |
|---|---|
| 1 | 110 |
| 2 | 90 |
Locking both rows in id order first means two opposite transfers cannot form a cycle.
Retry Logic in the Application
Retry on error 1213 (deadlock) and also 1205 (lock wait timeout), with a short random pause and a limit. This Python sketch uses PyMySQL and is shown, not executed here:
The work function must contain all statements of the transaction, so a retry repeats everything from the start.
Monitoring
Result:
| innodb_metrics_rows |
|---|
| 1 |
The counter lock_deadlocks (and SHOW GLOBAL STATUS LIKE 'Innodb_deadlocks' on some builds) lets monitoring tools alert when deadlocks suddenly increase.
Common Beginner Mistakes
| Mistake | What happens | Fix |
|---|---|---|
| No retry on error 1213 | Random failures for users | Retry the whole transaction |
| Retrying only the failed statement | Inconsistent data | Rerun all statements |
| Different lock order in different code paths | Frequent deadlocks | Agree an order |
| Huge transactions | More collisions | Split into small ones |
| Ignoring the deadlock log | Same problem keeps happening | Turn on innodb_print_all_deadlocks |
Practice
- Reproduce the deadlock with two
mysqlwindows. - Fix it by locking rows in id order.
- Write a retry wrapper in your favourite language.
- Find the
LATEST DETECTED DEADLOCKsection on a test server.
Conclusion
A deadlock is two transactions waiting for each other. InnoDB breaks it by rolling one back with error 1213. Prevent with a consistent lock order and short transactions, and always retry the whole transaction.

