You push an order through, the page spins, and then this lands in your logs:
ERROR 1213 (40001): Deadlock found when trying to get lock; try restarting transaction
Nothing is broken in the way you usually mean "broken". Your tables are fine, your data is fine, and if you run the same query again it will probably work. That is what makes deadlocks so confusing the first time you meet one: the error is real, but the fix is not in the query that failed. It is in the order your code touches rows, and in how your application reacts when MySQL says "try again".
What a MySQL deadlock actually is
A deadlock happens when 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, and neither will ever give up on its own โ so InnoDB steps in, picks one transaction as the victim, rolls it back completely, and lets the other one finish. The victim gets error 1213.
Two details matter here. First, the whole transaction is rolled back, not just the statement that failed. Everything the victim did before the error is gone, so retrying means running the entire transaction again from the beginning, not re-running one query. Second, a deadlock is a normal outcome of concurrent writes, not a sign that your database is corrupt. An application that writes to the same tables from many users at once and never retries a deadlocked transaction is the actual bug.
How to reproduce a deadlock in two minutes
The fastest way to understand a deadlock is to cause one on purpose. Open two MySQL sessions โ two terminal windows, or two tabs in your database client โ and run these statements quickly, one after the other:
-- Session 1
START TRANSACTION;
UPDATE orders SET status = 'paid' WHERE id = 1; -- locks row 1
SELECT SLEEP(2);
UPDATE orders SET status = 'paid' WHERE id = 2; -- wants row 2
COMMIT;
-- Session 2 (run within those 2 seconds)
START TRANSACTION;
UPDATE orders SET status = 'paid' WHERE id = 2; -- locks row 2
SELECT SLEEP(2);
UPDATE orders SET status = 'paid' WHERE id = 1; -- wants row 1
COMMIT;
One of the two sessions will fail with error 1213 and the other will commit. Look closely at why: the two transactions lock the same two rows in opposite orders. That opposite order is the entire cause of the deadlock โ and, as you will see, the entire fix.
Deadlock (1213) vs lock wait timeout (1205): do not confuse them
Beginners mix these two errors up constantly, and the fixes are different, so it is worth getting this straight:
| Deadlock (1213) | Lock wait timeout (1205) | |
|---|---|---|
| What happened | Two transactions wait on each other in a circle | One transaction waited too long for a lock held by another |
| What MySQL does | Kills one transaction immediately and rolls it back | Kills only the waiting statement after innodb_lock_wait_timeout seconds (default 50) |
| The transaction | Fully rolled back โ retry from the start | Still open and still holding its locks โ roll it back yourself |
| The fix | Consistent lock order, plus retry | Shorter transactions, better indexes |
If your error says "Lock wait timeout exceeded", you have a slow or stuck transaction holding locks, not a deadlock. Fixing your lock order will not help that problem โ how to fix slow MySQL queries with EXPLAIN is the right place to start instead, because a query that takes minutes to finish holds its locks for minutes too.
How to diagnose a deadlock: read the evidence MySQL leaves
When InnoDB kills a transaction, it keeps a full report of the most recent deadlock. You can read it any time with one command:
SHOW ENGINE INNODB STATUS\G
Scroll to the section called LATEST DETECTED DEADLOCK. It is long, but you only need four things from it: the two statements each transaction was blocked on, what each one holds, what each one wants, and which one was rolled back. Those two statements are what you take back to your code โ they name the two access paths that run in opposite orders, and that is where your fix goes.
If deadlocks happen often, turn on full deadlock logging so every one is written to the error log:
SET GLOBAL innodb_print_all_deadlocks = ON;
Remember to turn it back OFF once you have finished diagnosing, because it writes a lot. On MySQL 8.0 and later you can also watch locks live while the problem is happening:
SELECT * FROM performance_schema.data_locks;
SELECT * FROM performance_schema.data_lock_waits;
These two tables show you exactly which transaction is blocking which, in real time, without waiting for a deadlock to happen first.
Fix 1: lock rows in the same order, every time
This is the fix that actually prevents deadlocks. If every transaction touches rows in the same order, a cycle can never form. The simplest rule is: always order by primary key.
-- Every transaction does the rows in the same order, so no cycle can form.
START TRANSACTION;
SELECT id FROM orders WHERE id IN (1, 2) ORDER BY id FOR UPDATE;
UPDATE orders SET status = 'paid' WHERE id IN (1, 2);
COMMIT;
The SELECT ... FOR UPDATE line locks both rows up front, in id order, before any update runs. If a second transaction tries the same thing, it simply waits for the first one to finish instead of deadlocking with it.
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. Two code paths that update the same tables in opposite orders are the most common real-world cause of deadlocks, and the fix is just agreeing on one order and sticking to it everywhere.
A related cause is gap locks. Under MySQL's default isolation level, REPEATABLE READ, InnoDB does not only lock the rows that exist โ it also locks the gaps between them, so a range query cannot suddenly see new rows. Switching to READ COMMITTED removes most gap locking and genuinely reduces deadlocks, at the cost of allowing non-repeatable reads inside a transaction. Try the lock-order fix first โ it solves the problem without changing what your transactions can see.
Fix 2: retry the whole transaction, safely
Even with perfect lock order, a deadlock can still happen under heavy load, so your application must be ready to try again. The retry has three rules: retry the whole transaction from the start, retry only a few times (three is a good number), and make the work safe to repeat โ a retry that charges a customer twice is worse than the deadlock.
In plain PHP with PDO, the pattern looks like this:
<?php
$attempts = 0;
while (true) {
try {
$pdo->beginTransaction();
// ... all of your updates, in a consistent order ...
$pdo->commit();
break; // Success โ stop retrying.
} catch (PDOException $e) {
$pdo->rollBack();
// MySQL error 1213 = deadlock. Anything else is a real bug โ let it fail.
$isDeadlock = ($e->errorInfo[1] ?? 0) === 1213;
$attempts++;
if (! $isDeadlock || $attempts >= 3) {
throw $e;
}
usleep(100000 * $attempts); // Wait a little longer each time.
}
}
Notice what this code does not do: it never retries a different error. A deadlock is recoverable; a foreign key violation or a syntax error is not, and retrying those would just fail three times and waste your time.
In Laravel, this is built in. DB::transaction() takes a second argument โ the number of attempts โ and retries automatically when the transaction fails with a deadlock:
use Illuminate\Support\Facades\DB;
DB::transaction(function () {
// ... your updates, in a consistent order ...
}, 3);
That one number is the difference between a checkout that fails once in a hundred orders and one that simply works. If you are seeing error 1213 in a Laravel app, wrap the transaction this way first โ then fix the lock order so the retries are rarely needed.
Three more habits that keep deadlocks away
Lock order and retries do the heavy lifting, but three smaller habits make deadlocks much rarer:
- Keep transactions short. Do your slow work โ API calls, file uploads, sending emails โ before you open the transaction or after you commit it. A transaction that stays open for seconds holds its locks for seconds.
- Index the columns you update by. An
UPDATE ... WHERE status = 'pending'with no index onstatuscan lock far more rows than you intended, because InnoDB has to scan โ and lock โ rows it will never change. The same scan-first thinking helps when finding duplicate records in MySQL: run the heavy scan first, then open a short transaction only for the writes. - Do not open a transaction just to read. A plain
SELECToutside a transaction takes no locks worth worrying about. Wrapping reads in transactions "just in case" is how long-running locks are born.
Frequently asked questions
Can deadlocks be eliminated completely? No โ any system where two transactions can write to the same rows can deadlock. The goal is not zero deadlocks; it is deadlocks so rare, and handled so gracefully, that your users never notice them.
Why does MySQL kill one transaction instead of waiting? Because waiting would never end. Each transaction is waiting for a lock the other one holds, and neither will release its locks until it finishes. Detecting the cycle and rolling back one side is the only way out, and it happens in milliseconds.
Should I just increase innodb_lock_wait_timeout? No. That setting only controls error 1205, the lock wait timeout โ it has nothing to do with deadlocks, which are detected and resolved immediately no matter what the timeout is.
Is a deadlock a sign my database is broken? No. It is a sign that two pieces of code touched the same rows in opposite orders at the same moment. The database did exactly what it was designed to do, and the fix belongs in your code.
Conclusion
Fixing MySQL deadlock error 1213 comes down to two things. First, find the cause: run SHOW ENGINE INNODB STATUS and read the LATEST DETECTED DEADLOCK section to see which two statements locked rows in opposite orders. Second, fix the cause, not the symptom: make every transaction lock rows in the same order โ by primary key, with SELECT ... FOR UPDATE when you need to โ and make your application retry the whole transaction a few times when a deadlock still slips through. In Laravel, DB::transaction($callback, 3) gives you the retry for free.


