DEV Community

Raja Hunain
Raja Hunain

Posted on

MySQL Deadlock Error 1213? Lock Your Rows in the Same Order Every Time

You run an order through, the page spins, and then this shows up in your logs: ERROR 1213 (40001): Deadlock found when trying to get lock; try restarting transaction. Your tables are fine. Your data is fine. Run the same query again and it will probably work. That is what makes this error so confusing the first time you meet it: the fix is not in the query that failed. It is in the order your code touches rows.

What is actually happening

A deadlock means two transactions each hold a lock the other one needs. Transaction A locks row 1 and wants row 2. Transaction B locks row 2 and wants row 1. Neither can move forward, so InnoDB picks one transaction as the victim, rolls it back completely, and lets the other one finish. The victim gets error 1213.

Two things to remember: the whole transaction is rolled back, not just the failing statement, so a retry means running everything again from the start. And a deadlock is a normal outcome of concurrent writes, not a sign your database is broken.

The fix: one rule

Lock rows in the same order, every time. If every transaction touches rows in the same order, a cycle can never form. The simplest version of the rule is: always order by primary key.

SELECT id FROM orders WHERE id IN (1, 2) ORDER BY id FOR UPDATE;
Enter fullscreen mode Exit fullscreen mode

then

UPDATE orders SET status = 'paid' WHERE id IN (1, 2);
Enter fullscreen mode Exit fullscreen mode

The SELECT ... FOR UPDATE line locks both rows up front, in id order. If a second transaction tries the same thing, it simply waits instead of deadlocking. The same rule applies to the order you update tables in: if one part of your code writes to orders and then to order_items, every other part must do it in that same order.

The second half: retry safely

Even with perfect lock order, a deadlock can still happen under heavy load, so your application must be ready to try again. Retry the whole transaction, only a few times (three is good), and only when the error is actually 1213. In Laravel, this is built in:

DB::transaction(function () { ... }, 3);
Enter fullscreen mode Exit fullscreen mode

retries automatically on deadlock.

How to find the cause

When InnoDB kills a transaction, it keeps a full report. Run SHOW ENGINE INNODB STATUS and read the LATEST DETECTED DEADLOCK section.

I wrote a full step-by-step guide on this, including how to reproduce a deadlock in two terminal windows, the difference between error 1213 and lock wait timeout 1205, and the retry pattern in plain PHP: https://rajadevsolutions.online/blog/how-to-fix-mysql-deadlock-error-1213

The short version: lock in one consistent order, retry the whole transaction when 1213 still slips through, and keep your transactions short. Do that, and error 1213 becomes a line in a log file instead of a page that fails in front of a customer.

Top comments (0)