Start free trial
Start free trial Log in

14-day free trial. No credit card.

Detecting and fixing Laravel deadlocks

Why deadlocks happen, how to detect and retry them safely, and the code patterns that stop them.

  • Guide
  • 4 min read

How do I detect and fix Laravel deadlocks?

Catch QueryException with SQLSTATE codes 40001 or 40P01 and retry the transaction with DB::transaction(fn() => ..., 3). For long-term prevention: order lock acquisition consistently, keep transactions short, use SELECT ... FOR UPDATE SKIP LOCKED for queue patterns, and prefer atomic updates over SELECT-then-UPDATE. Monitor deadlock rate and watch for sudden spikes. They often correlate with specific deploys.

Updated

Deadlocks are the kind of bug that doesn't reproduce when you go looking for it. The error fires under concurrency (two requests, or a request and a job, colliding on the same rows at the same instant), and then everything's fine again until traffic lines up just so. That intermittency is exactly why they're worth understanding properly: you can't single-step your way to the cause, so you fix them by knowing the patterns that produce them and by watching the rate.

What a deadlock looks like in Laravel

Postgres deadlock

text
ERROR:  deadlock detected
DETAIL:  Process 5234 waits for ShareLock on transaction 99812; blocked by process 5221.
         Process 5221 waits for ShareLock on transaction 99815; blocked by process 5234.
HINT:  See server log for query details.
CONTEXT:  while updating tuple (0,42) in relation "orders"

Surfaces in Laravel as

php
Illuminate\Database\QueryException
SQLSTATE[40P01]: Deadlock detected: 7 ERROR:  deadlock detected
DETAIL:  Process 5234 waits for ShareLock on transaction 99812; blocked by process 5221.
Process 5221 waits for ShareLock on transaction 99815; blocked by process 5234.
HINT:  See server log for query details.
CONTEXT:  while updating tuple (0,42) in relation "orders" (Connection: pgsql, Host: 127.0.0.1, Port: 5432, Database: shop, SQL: update "orders" set "status" = paid where "id" = 42 and "user_id" = 7)

The SQLSTATE codes to care about

Code Meaning Retry?
40P01Deadlock (Postgres)Yes
40001Serialization failure (Postgres), deadlock (MySQL error 1213)Yes
HY000Lock wait timeout (MySQL error 1205)DB::transaction retries it; the sample below doesn't
55P03Lock not available after lock_timeout (Postgres)No: find the transaction holding the lock

1205 and 1213 are MySQL error numbers, found in $e->errorInfo[1]. The SQLSTATE in $e->errorInfo[0] is what the sample below checks.

Retry with exponential backoff

Laravel's DB::transaction has a built-in retry count, but the retry happens immediately. For heavily contended rows, add jittered backoff:

php
use Closure;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB;

function withRetry(Closure $tx, int $maxAttempts = 3)
{
    for ($attempt = 1; $attempt <= $maxAttempts; $attempt++) {
        try {
            return DB::transaction($tx);
        } catch (QueryException $e) {
            $code = $e->errorInfo[0] ?? null;
            $deadlock = in_array($code, ['40001', '40P01']);

            if (!$deadlock || $attempt === $maxAttempts) {
                throw $e;
            }

            // Jittered exponential backoff: 100ms, then 200ms, plus up to 25ms
            usleep((2 ** $attempt) * 50000 + rand(0, 25000));
        }
    }
}

Retries buy time, not a fix

A retry loop turns a deadlock from an error your user sees into a few milliseconds they don't. That's worth having, and you should have it. But a rising retry rate is still telling you that two code paths are fighting over the same rows, and retries get more expensive as contention climbs: each collision now costs an extra round trip plus a backoff sleep. Treat the retry as a seatbelt and the prevention patterns below as the repair.

Prevention patterns

1. Consistent lock order

php
// Bad: different paths lock in different orders
DB::transaction(function () use ($userId, $accountId) {
    $user = User::lockForUpdate()->find($userId);
    $account = Account::lockForUpdate()->find($accountId);
});

DB::transaction(function () use ($userId, $accountId) {
    $account = Account::lockForUpdate()->find($accountId);
    $user = User::lockForUpdate()->find($userId);
});

// Good: every path locks in the same order (here: users, then accounts)
DB::transaction(function () use ($userId, $accountId) {
    $user = User::lockForUpdate()->find($userId);
    $account = Account::lockForUpdate()->find($accountId);
});

2. Atomic updates over read-modify-write

php
// Bad: window between SELECT and UPDATE where two workers can conflict
$user = User::find($id);
$user->balance += 10;
$user->save();

// Good: atomic, no lock window
User::where('id', $id)->update(['balance' => DB::raw('balance + 10')]);

// Or with increment
User::where('id', $id)->increment('balance', 10);

3. SKIP LOCKED for queue-like patterns

php
// Claim a pending job atomically so multiple workers won't collide
$job = DB::transaction(function () {
    $row = Job::where('status', 'pending')
        ->orderBy('created_at')
        ->limit(1)
        ->lock('for update skip locked')
        ->first();

    if ($row) {
        $row->update(['status' => 'claimed', 'claimed_at' => now()]);
    }

    return $row;
});

4. Keep transactions short

Move external HTTP calls, slow computations and user-facing IO out of DB::transaction. A transaction that holds locks for 500ms while waiting on Stripe is an incident waiting to happen.

Monitoring deadlock rate

Aggregate QueryExceptions by SQLSTATE code over time. A sudden jump in 40P01 (Postgres) or 40001 (MySQL deadlocks, error 1213) correlates with:

  • A recent deploy introducing a new lock-ordering bug
  • Traffic spike on a hot row (flash sale on a single product)
  • A long-running background job holding locks while user requests pile up
  • Stale query plan picking a table scan instead of an index (bigger lock footprint)

Find the code path behind each deadlock

A deadlock that reaches your exception handler becomes a NightOwl issue, one per code location and environment, linked to the request or job that hit it. You get an alert when the issue is new or comes back. Deadlocks your retry absorbs never reach the handler, so they don't show up.

No credit card needed.

Terminal
composer require nightowl/agent
php artisan nightowl:install
php artisan nightowl:agent

Frequently asked questions

Anything else, write to support@usenightowl.com

What causes deadlocks in Laravel?

Two or more transactions holding locks the other needs. Common Laravel patterns: (1) two requests updating the same rows in different orders within DB::transaction blocks, (2) a background job and a user request competing on the same aggregate (user balance, inventory count), (3) two transactions locking overlapping sets of rows with SELECT ... FOR UPDATE and no ORDER BY, so each grabs part of the set before waiting on the other, (4) long-running transactions holding locks while other transactions pile up.

How do I detect Laravel deadlocks?

Postgres writes every deadlock to its server log as ERROR: deadlock detected, since the default log_min_messages (warning) includes errors. MySQL only keeps the most recent one in SHOW ENGINE INNODB STATUS unless you turn on innodb_print_all_deadlocks, which writes each deadlock to the error log. In Laravel, the driver error arrives as an Illuminate\Database\QueryException; catch and retry. For production visibility, aggregate QueryExceptions by SQLSTATE code: 40P01 (deadlock in Postgres) and 40001 (serialization failure in Postgres, and the SQLSTATE MySQL reports for a deadlock) are the two you care about.

How do I handle Laravel deadlock retries?

Laravel's DB::transaction accepts a second argument for the number of attempts: DB::transaction(fn() => ..., 3) runs the closure up to three times in total. On a deadlock, a serialization failure or a MySQL lock wait timeout, it rolls back and retries immediately. Inside an outer transaction it doesn't retry: it throws a DeadlockException for the outer level to handle. Retry with backoff to avoid immediately re-colliding. Don't retry non-transient errors. A unique-key violation shouldn't retry indefinitely.

How do I prevent Laravel deadlocks in the first place?

Four patterns: (1) order lock acquisition consistently (always lock parent rows before child rows), (2) keep transactions short (don't do external HTTP calls inside a transaction), (3) use SELECT ... FOR UPDATE SKIP LOCKED for queue-like patterns, (4) batch updates where possible to reduce per-row locking. For aggregate counters (balances, counters), consider an atomic UPDATE ... SET x = x + 1 rather than SELECT-then-UPDATE.

What's the difference between a deadlock and a lock wait timeout?

Deadlock: two transactions cyclically waiting on each other. The DB detects the cycle and kills one automatically. Lock wait timeout: one transaction waits too long for a lock that another transaction is holding (no cycle, just a slow holder). Both reach Laravel as a QueryException. Deadlocks carry SQLSTATE 40P01 on Postgres and 40001 (error 1213) on MySQL. A MySQL lock wait timeout is error 1205, 'Lock wait timeout exceeded; try restarting transaction'. On Postgres a waiter only gives up if you set lock_timeout (or statement_timeout); a lock_timeout failure is SQLSTATE 55P03. Different causes, different fixes.

Should I alert on Laravel deadlocks?

Yes, but on rate, not absolute count. A few deadlocks per day at high traffic is normal. Alert if the rate jumps 5x above baseline over 10 minutes. Deadlock spikes usually correlate with specific deploys (new code path that grabs locks in a bad order) or traffic patterns (flash sale on a single SKU). NightOwl doesn't alert on a deadlock rate; it alerts when a deadlock's issue first appears or returns after you resolve it, so the 5x check needs your metrics stack or a scheduled query.

How do I debug a specific Laravel deadlock?

Postgres's pg_stat_activity during the incident and the server log afterwards both help (on MySQL, SHOW ENGINE INNODB STATUS or the error log with innodb_print_all_deadlocks on). The Postgres deadlock log line names both queries and the tables involved, which is usually enough to identify the conflicting code paths. Reproduce in staging by running the two transactions concurrently with sleep() in the middle to force the overlap window.

Does Laravel Eloquent cause more deadlocks than raw SQL?

Not inherently, but Eloquent's convenience hides lock behavior. Mass-updating thousands of rows with Model::where(...)->update([...]) holds row-level locks on every row in the set. Loading a relation with with() and then updating it in a loop creates many tiny transactions that can interleave. Awareness of what SQL actually fires is the fix.

Related

Flat pricing, whatever your traffic does

Every plan starts with a 14-day free trial. No credit card needed.

Hobby
$5 a month

One app for a side project. Issues and alerts, with a 14-day dashboard window.

Start my 14-day trial
TeamRecommended
$15 a month

Up to 3 apps and 5 people per team. Full history, the MCP server, data clearing and agent health.

Start my 14-day trial
Agency
$69 a month

Unlimited client apps and people, one overview of every app, and apps you can hand over.

Start my 14-day trial