Concurrent transactions occasionally fail with 'Deadlock found when trying to get lock; try restarting transaction' when two transactions lock the same rows in a different order.

Keep transactions short, always access tables and rows in a consistent order, add proper indexes to reduce lock scope, and add retry logic for the specific deadlock error code.

Step-by-Step Guide

1

Run SHOW ENGINE INNODB STATUS to inspect the last deadlock's details

2

Ensure all transactions touch tables/rows in the same consistent order

3

Keep transactions as short as possible - commit as soon as work is done

4

Add indexes on columns used in WHERE/JOIN clauses to shrink lock scope

5

Use SELECT ... FOR UPDATE deliberately, and only where truly needed

6

Add retry logic in the application layer specifically for error code 1213

7

Consider READ COMMITTED isolation if REPEATABLE READ is causing excess locking

8

Batch large UPDATE/DELETE operations into smaller chunks

Found an issue with this solution?

Related Topics

mysql innodb lock wait timeouttransaction isolation levelsmysql index optimization