Skip to content
FR
  1. LuzineDebug
  2. Databases (SQL)
  3. ERROR 1213 (40001): Deadlock found when trying t…
Databases (SQL) Advanced ≈ 30 min to fix

Fix "Deadlock found when trying to get lock; try restarting transaction" (MySQL, PostgreSQL)

Error message
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
In short

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.

Be the first to confirm this fix

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

  1. Different lock order: two processes update the same rows (stock, balance) in reverse order.
  2. Missing index: an UPDATE ... WHERE status = 'pending' without an index scans and locks far more rows than needed.
  3. Long transactions: HTTP calls, sending emails or heavy processing inside a transaction keep locks open.
  4. Gap locks: SELECT ... FOR UPDATE on a missing row followed by a concurrent INSERT, typical of job queues and counters.
  5. Foreign keys: inserting children takes a shared lock on the parent, which conflicts with an update of that parent.

Step-by-step fix

  1. Read the latest deadlock

    The LATEST DETECTED DEADLOCK section 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.

    sql
    SHOW ENGINE INNODB STATUS\G
    SET GLOBAL innodb_print_all_deadlocks = ON;
  2. 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::transaction retries the closure on deadlock. Do not run external side effects (email, API) in the closure, they would be repeated.

    php
    use Illuminate\Support\Facades\DB;
    
    DB::transaction(function () use ($orderId) {
        $order = Order::lockForUpdate()->findOrFail($orderId);
        $order->update(['status' => 'paid']);
    }, 3);
  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.

    sql
    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;
  4. Index the filtered columns

    Check with EXPLAIN that your UPDATE/DELETE use an index. Without one, InnoDB locks every row it scans.

    sql
    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);
  5. Shorten transactions

    Prepare data and call external services before BEGIN, only open the transaction for the writes. For large updates, work in batches (MySQL accepts LIMIT on a single-table UPDATE).

    sql
    UPDATE logs SET archived = 1 WHERE archived = 0 AND created_at < '2026-01-01' LIMIT 1000;
  6. Consider READ COMMITTED (MySQL)

    Under READ COMMITTED, InnoDB takes far fewer gap locks, which removes many INSERT-related deadlocks. Trade-off: repeated reads within one transaction may see different data. PostgreSQL already uses this level by default.

    sql
    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 = on in 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

All Databases (SQL) errors →