MySQL deadlocks: how to read them and how to prevent them
InnoDB resolves deadlocks automatically by rolling one transaction back. Here's how to read the deadlock report and the changes that make them rare.
A deadlock happens when two transactions each hold a lock the other needs. Neither can continue, so InnoDB detects the cycle and rolls back one of them (usually the one that has changed the fewest rows). The application gets error 1213, "Deadlock found when trying to get lock; try restarting transaction".
An occasional deadlock is normal in a busy database. Frequent ones point to something you can fix.
Read the latest one
SHOW ENGINE INNODB STATUS\G
Look for the LATEST DETECTED DEADLOCK section. It shows, for each transaction:
- the statement it was running,
- the lock it held ("HOLDS THE LOCK(S)"),
- the lock it was waiting for,
- and which transaction InnoDB rolled back.
Only the most recent deadlock is shown. To log every one to the error log, turn on:
SET PERSIST innodb_print_all_deadlocks = ON;
The usual causes
- Different order. Transaction A updates
ordersthenpayments; transaction B updatespaymentsthenorders. Run both at once and they can deadlock. - Scanning instead of seeking. An UPDATE or DELETE without a usable index locks every row it scans, not just the ones it changes, so unrelated transactions collide.
- Long transactions. The longer a transaction holds locks, the more likely another one wants them.
- Gap locks. Under the default REPEATABLE READ isolation, InnoDB also locks gaps between index records to prevent phantom rows. Range updates and inserts into the same range can deadlock.
Making them rare
- Touch tables and rows in the same order in every code path. Sorting the IDs you're about to update is a cheap way to do it.
- Index the WHERE clauses of your UPDATE and DELETE statements so InnoDB locks only the rows it needs.
- Keep transactions short. Do the slow work (API calls, file processing) before you open the transaction.
- Retry. Deadlocks can't be eliminated completely, so any code that writes in a transaction should catch error 1213 and retry once or twice.
- Consider READ COMMITTED for workloads that don't need repeatable reads. It takes far fewer gap locks. Test it, because it changes what your transactions see.
SQLNirvana records each new deadlock InnoDB reports, keeps the full text in the Diagnostics tab, and logs it in the activity timeline so you can line it up with deploys.