Fix "Deadlock found when trying to get lock; try restarting transaction" (MySQL, PostgreSQL)
ERROR 1213 (40001): Deadlock found when trying to get lock; try restarting transaction
- SQLSTATE[40001]: Serialization failure: 1213 Deadlock found when trying to get lock; try restarting transaction
- ERROR: deadlock detected DETAIL: Process 4182 waits for ShareLock on transaction 912345; blocked by process 4190.
- com.mysql.cj.jdbc.exceptions.MySQLTransactionRollbackException: Deadlock found when trying to get lock; try restarting transaction
- SQLSTATE[40P01]: Deadlock detected: 7 ERROR: deadlock detected
Two transactions are waiting on each other’s locks; the engine rolls one back to unblock the other. Retry the rolled-back transaction automatically, then reduce deadlocks: always lock rows in the same order, index the columns in WHERE clauses and keep transactions short.
What this error means
InnoDB locks the rows (and, under REPEATABLE READ, the gaps between them) that your queries modify or read with FOR UPDATE. If transaction A holds row 1 and waits for row 2, while B holds row 2 and waits for row 1, neither can progress. The deadlock detector spots that cycle, picks the cheapest transaction to undo, rolls it back entirely (a full ROLLBACK, not just the last statement) and returns error 1213 with SQLSTATE 40001. PostgreSQL does the same after deadlock_timeout (1 s) with "deadlock detected" (40P01). The other transaction carries on normally.
Common causes
- Different lock order: two processes update the same rows (stock, balance) in reverse order.
- Missing index: an
UPDATE ... WHERE status = 'pending'without an index scans and locks far more rows than needed. - Long transactions: HTTP calls, sending emails or heavy processing inside a transaction keep locks open.
- Gap locks:
SELECT ... FOR UPDATEon a missing row followed by a concurrentINSERT, typical of job queues and counters. - Foreign keys: inserting children takes a shared lock on the parent, which conflicts with an update of that parent.
Step-by-step fix
-
Read the latest deadlock
The
LATEST DETECTED DEADLOCKsection shows both transactions, their queries, the locks held and awaited, and which one was rolled back. To keep a history, log every deadlock to the error log.SHOW ENGINE INNODB STATUS\G SET GLOBAL innodb_print_all_deadlocks = ON; -
Retry the transaction automatically
An occasional deadlock is normal under high concurrency: the message itself says "try restarting transaction". In Laravel, the second argument of
DB::transactionretries the closure on deadlock. Do not run external side effects (email, API) in the closure, they would be repeated.use Illuminate\Support\Facades\DB; DB::transaction(function () use ($orderId) { $order = Order::lockForUpdate()->findOrFail($orderId); $order->update(['status' => 'paid']); }, 3); -
Lock in a consistent order
Always sort identifiers before locking or updating several rows, in every process. Two transactions that take locks in the same order cannot form a cycle.
START TRANSACTION; SELECT id, stock FROM products WHERE id IN (12, 7, 31) ORDER BY id FOR UPDATE; UPDATE products SET stock = stock - 1 WHERE id IN (7, 12, 31); COMMIT; -
Index the filtered columns
Check with
EXPLAINthat yourUPDATE/DELETEuse an index. Without one, InnoDB locks every row it scans.EXPLAIN UPDATE jobs SET reserved_at = NOW() WHERE queue = 'default' AND reserved_at IS NULL; CREATE INDEX jobs_queue_reserved_at_index ON jobs (queue, reserved_at); -
Shorten transactions
Prepare data and call external services before
BEGIN, only open the transaction for the writes. For large updates, work in batches (MySQL acceptsLIMITon a single-tableUPDATE).UPDATE logs SET archived = 1 WHERE archived = 0 AND created_at < '2026-01-01' LIMIT 1000; -
Consider READ COMMITTED (MySQL)
Under
READ COMMITTED, InnoDB takes far fewer gap locks, which removes manyINSERT-related deadlocks. Trade-off: repeated reads within one transaction may see different data. PostgreSQL already uses this level by default.SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
Did this fix work for you?
Confirm it in one click: it will rise for the next developers stuck on the same error.
Keep it from coming back
- Always plan a retry (2 to 5 attempts) for concurrent transactions.
- Document a single lock order (for example by ascending
id) for heavily used tables. - Monitor deadlocks (
innodb_print_all_deadlocks,log_lock_waits = onin PostgreSQL) to spot the queries involved before they multiply.
Frequently asked questions
Should I retry the whole transaction or just the last query?
The whole transaction: the engine did a full ROLLBACK. Replaying only the last query would leave inconsistent data.
How is it different from "Lock wait timeout exceeded" (1205)?
With error 1205 there is no cycle: a transaction waits too long for a lock (innodb_lock_wait_timeout, 50 s by default) and only the statement is rolled back. Look for the long transaction holding the lock.
Do deadlocks mean my database is broken?
No. They are normal in a transactional database under load. They become a problem when frequent: that signals an inconsistent lock order or missing indexes.
Useful tools for this error
More Databases (SQL) errors
- Fix "ERROR 1045 (28000): Access denied for user 'root'@'localhost'" (MySQL, MariaDB)
- Fix "ERROR 1062 (23000): Duplicate entry for key" (MySQL, MariaDB, PostgreSQL)
- Fix FATAL: password authentication failed for user "postgres" (PostgreSQL)
- Fix "ERROR 1040: Too many connections" (MySQL) and "too many clients already" (PostgreSQL)
- Fix "ERROR 2006 (HY000): MySQL server has gone away"
- Fix "ERROR 1054 (42S22): Unknown column in 'field list'" (MySQL)
- Fix "ERROR: relation "users" does not exist" (PostgreSQL)