Tech Verse Logo
Enable dark mode
Laravel lockForUpdate: Pessimistic Locking Done Right

Laravel lockForUpdate: Pessimistic Locking Done Right

•Updated •10 min read

Read the row with lockForUpdate() inside DB::transaction(), then check and write it in the same closure, so MySQL or PostgreSQL makes a second request wait until the first commits. Outside a transaction the lock is released immediately, every path that writes the row must lock it too, and SQLite ignores it. For a single counter, a conditional decrement in the WHERE clause is simpler.

The bug pessimistic locking fixes is the lost update. Two requests load the same product with one unit in stock. Both see stock = 1, both decide the sale is fine, both write stock = 0 and both create an order. Nothing errors. You've just sold one item twice, and you'll find out from a customer.

lockForUpdate() stops that by making the database hand the row to one transaction at a time. It's a one-line change, but it only works under conditions that aren't obvious from the method name: it has to run inside a transaction, every code path that writes the row has to use it, and your SQLite test suite will never exercise it. This post goes through each of those.

What lockForUpdate() does

It appends a locking clause to the SELECT. I compiled the same query against each grammar with toSql():

mysql:  select * from `products` where `id` = ? for update
pgsql:  select * from "products" where "id" = ? for update
sqlite: select * from "products" where "id" = ?

On MySQL (InnoDB) and PostgreSQL, SELECT ... FOR UPDATE takes an exclusive row lock on the rows it returns, and that lock is held until the transaction commits or rolls back. Any other transaction that tries to update those rows, delete them, or lock them with its own FOR UPDATE or FOR SHARE waits until then. When the first transaction commits, the waiter's locking read returns the latest committed values, not the ones it would have seen earlier. That last part is what makes the check-then-write pattern safe.

Notice the SQLite line: there's no clause at all. SQLite's grammar in Laravel compiles locks to an empty string, because SQLite locks the whole database file rather than rows. We'll come back to what that means for your tests.

One more detail from the query builder source: calling lock(), which lockForUpdate() and sharedLock() are built on, switches the query to the write PDO. If you use read replicas, locking reads always go to the primary, which is what you want, since a replica can't hold a lock for the primary.

A safe stock reservation

Here's the pattern in full. The read, the check and the write all happen in one transaction, and the read takes the lock:

<?php

namespace App\Actions;

use App\Exceptions\OutOfStock;
use App\Models\Product;
use App\Models\Reservation;
use Illuminate\Support\Facades\DB;

class ReserveStock
{
    public function handle(int $productId, int $userId, int $quantity): Reservation
    {
        return DB::transaction(function () use ($productId, $userId, $quantity) {
            $product = Product::whereKey($productId)
                ->lockForUpdate()
                ->firstOrFail();

            if ($product->stock < $quantity) {
                throw new OutOfStock("Only {$product->stock} left of product {$product->id}.");
            }

            $product->decrement('stock', $quantity);

            return Reservation::create([
                'product_id' => $product->id,
                'user_id' => $userId,
                'quantity' => $quantity,
            ]);
        }, attempts: 3);
    }
}

With this in place, the second request blocks on the SELECT until the first commits, then reads stock = 0 and throws OutOfStock. Throwing inside the closure rolls the transaction back and releases the lock, so the failure path is clean. OutOfStock is a plain RuntimeException subclass; map it to a 409 or a validation error in your exception handler.

The attempts: 3 argument makes DB::transaction() rerun the closure if it fails with a deadlock or a lock wait timeout. That's covered in depth in how Laravel retries deadlocked transactions, including the case where retries silently don't happen.

If the model is already loaded (from route model binding, say), don't trust it. It was read without a lock, before the transaction started. Re-read it inside the transaction with Product::whereKey($product->id)->lockForUpdate()->firstOrFail() and use that instance.

Without a transaction, the lock is released immediately

Older posts claim the database throws an error if you call lockForUpdate() outside a transaction. It doesn't. In autocommit mode each statement is its own transaction, so the lock is taken and then released the moment the SELECT finishes. The MySQL manual puts it plainly: locking reads are only possible when autocommit is disabled, and all their locks are released at commit or rollback. You get no error and no protection, which is the worst combination. The pessimistic locking section of the Laravel docs calls wrapping the lock in a transaction "not obligatory". For a check-then-write, it is.

Who gets blocked, and who doesn't

A row lock doesn't stop plain reads. In both MySQL and PostgreSQL, an ordinary SELECT reads a consistent snapshot and ignores row locks entirely, so your product page and admin dashboard keep working while a checkout holds the lock. That's good for throughput, but it has a consequence people miss.

The lock only protects you if every read-modify-write path for that row also takes it. Suppose an admin "adjust stock" form loads the product without a lock, adds 10 to the value it read, and saves. Its UPDATE will wait for the checkout's lock, but then it writes a total computed from the stale number and wipes out the checkout's decrement. The fix is either to lock in that path too, or to make the write relative (increment('stock', 10) compiles to stock = stock + 10 and doesn't depend on what you read).

sharedLock() is the weaker option. It compiles to lock in share mode on MySQL and for share on PostgreSQL. Other transactions can still read and share-lock the row, but nobody can modify it until you commit. Use it when you need a row to stay unchanged while you write something that depends on it, like confirming a parent row exists and stays put while you insert children. PostgreSQL also has FOR NO KEY UPDATE, which doesn't block inserts into tables that reference the row by foreign key; the query builder has an undocumented lockForNoKeyUpdate() for it, and on other grammars it falls back to a normal FOR UPDATE.

Indexes decide how much you lock on MySQL

On InnoDB, a locking read locks every index record it scans, not just the rows that match. The manual's page on locks set by different statements is blunt about it: if there's no suitable index and MySQL has to scan the table, every row becomes locked, which also blocks inserts by other sessions. Lock by primary key or a unique column whenever you can. With a unique search condition, InnoDB locks only the record it found. With a range or a non-unique index, it uses gap or next-key locks that can block inserts near the range you touched.

PostgreSQL works differently: it locks exactly the rows the query returns and has no gap locks. That makes it easier to reason about, but it also means locking a row that doesn't exist yet does nothing on PostgreSQL. If your logic is "check no booking exists for this slot, then insert one", a FOR UPDATE on the empty result protects nothing. Use a unique index on the slot instead and handle the duplicate-key error, or lock a parent row that always exists (the room, the event) and serialise on that.

Lock waits and timeouts

A waiting transaction doesn't wait forever on MySQL. innodb_lock_wait_timeout defaults to 50 seconds, after which the statement fails with ERROR 1205: Lock wait timeout exceeded; try restarting transaction. Only that statement is rolled back by default, not the whole transaction, but DB::transaction() catches the exception and rolls everything back. Laravel's concurrency error detector recognises that message, so with attempts greater than one the closure is retried.

Fifty seconds is far too long for a web request. The variable has session scope, so you can lower it on the connection your request handlers use, or in a specific transaction:

<?php

use Illuminate\Support\Facades\DB;

// MySQL: applies to the rest of this connection's session.
DB::statement('SET SESSION innodb_lock_wait_timeout = 5');

// PostgreSQL: SET LOCAL lasts only until the current transaction ends.
DB::transaction(function () {
    DB::statement("SET LOCAL lock_timeout = '3s'");

    DB::table('products')->where('id', 42)->lockForUpdate()->first();
});

PostgreSQL's lock_timeout defaults to 0, which disables the timeout, so by default a locking read waits as long as the lock is held. When it does fire, the error is canceling statement due to lock timeout with SQLSTATE 55P03. That message isn't in Laravel's list of concurrency errors, so it isn't retried. Catch it and return a "try again" response; retrying a contended lock in a tight loop rarely helps anyway.

Don't wait at all: NOWAIT and SKIP LOCKED

There's no dedicated builder method for these, but lock() accepts a raw string, and both MySQL and PostgreSQL support the clauses. NOWAIT fails immediately if a row is locked, which suits "someone else is already editing this order". SKIP LOCKED leaves locked rows out of the result, which is the standard way to let several workers pull from a queue-like table without stepping on each other:

<?php

use Illuminate\Support\Facades\DB;

$batch = DB::transaction(function () {
    $rows = DB::table('outbox_messages')
        ->whereNull('claimed_at')
        ->orderBy('id')
        ->limit(50)
        ->lock('for update skip locked')
        ->get();

    DB::table('outbox_messages')
        ->whereIn('id', $rows->pluck('id'))
        ->update(['claimed_at' => now()]);

    return $rows;
});

Each worker claims a different set of up to 50 rows, then processes them outside the transaction. Both databases' manuals warn that skipping locked rows gives an inconsistent view of the data, so keep it to work queues and never use it for anything that has to see every row, like a balance calculation. That compiled to ... limit 50 for update skip locked on both MySQL and PostgreSQL in my check.

Often you don't need a lock: the conditional update

For a single counter, there's a simpler answer than locking. Put the check in the WHERE clause and let the database do it atomically:

<?php

use App\Exceptions\OutOfStock;
use App\Models\Product;

$updated = Product::whereKey($productId)
    ->where('stock', '>=', $quantity)
    ->decrement('stock', $quantity);

if ($updated === 0) {
    throw new OutOfStock("Product {$productId} doesn't have {$quantity} in stock.");
}

decrement() on a query returns the number of affected rows, so zero means either the product doesn't exist or there wasn't enough stock. One statement, the row lock lasts only as long as the UPDATE, and no read-modify-write window exists. I ran both versions as ten concurrent processes buying a product with one unit in stock, against a file-based SQLite database. The naive "load, check, save" version sold ten units. The conditional update sold exactly one.

Reach for lockForUpdate() when the decision needs more than one column or more than one row: checking a wallet balance and a daily limit, moving money between two accounts, reserving a seat and writing the booking in the same unit of work. If you lock several rows, always lock them in the same order (by primary key, say), or two transactions locking A-then-B and B-then-A will deadlock.

Keep the locked section short

Every millisecond the transaction is open, everyone else who wants that row is queued behind it. Do the slow work before the transaction (validation, loading related data that won't change, computing prices) or after it. Never make an HTTP call, send mail, or talk to a payment provider while holding the lock. If you need to dispatch a job from inside the transaction, use afterCommit() so the worker doesn't run before your data exists.

Pessimistic locking is also the wrong tool when contention is rare and the cost of a conflict is low, like two admins editing the same blog post. A version column checked in the UPDATE (optimistic locking) costs nothing until there's a conflict. And for coordinating things that aren't rows, such as "only one process rebuilds this report", use a cache lock instead; that approach is covered in preventing cache stampedes with atomic locks.

Testing: SQLite can't see your locks

Since SQLite compiles lockForUpdate() away, an in-memory SQLite test proves your business logic and nothing about concurrency. Worse, removing the lock wouldn't fail any test. Two practical steps help. First, run the tests that cover locking code against the same engine as production; this guide to testing against a real database without slowing the suite shows how. Second, add a cheap guard that the lock is actually in the query:

<?php

namespace Tests\Feature;

use App\Actions\ReserveStock;
use App\Exceptions\OutOfStock;
use App\Models\Product;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Tests\TestCase;

class ReserveStockTest extends TestCase
{
    use RefreshDatabase;

    public function test_it_refuses_to_oversell(): void
    {
        $product = Product::create(['name' => 'Mechanical keyboard', 'stock' => 2]);

        (new ReserveStock)->handle($product->id, userId: 1, quantity: 2);

        $this->assertSame(0, $product->fresh()->stock);

        $this->expectException(OutOfStock::class);

        (new ReserveStock)->handle($product->id, userId: 1, quantity: 1);
    }

    public function test_the_read_takes_a_row_lock_on_mysql(): void
    {
        $sql = DB::connection('mysql')
            ->table('products')
            ->where('id', 1)
            ->lockForUpdate()
            ->toSql();

        $this->assertStringEndsWith('for update', $sql);
    }
}

The second test builds SQL with the MySQL grammar without opening a connection, so it runs fine in a SQLite suite. It checks the builder rather than your action, so treat it as a smoke test. The real proof is a concurrent run against your production engine: two processes, one holding the lock with a sleep inside the transaction, and the other timing how long its SELECT ... FOR UPDATE waits. For the wider picture of where races hide in a Laravel app, see this guide to detecting and fixing race conditions.

WRITTEN BY

Full Stack Software Engineer | Laravel · Next.js · AWS

Full Stack Software Engineer with 7+ years of experience building scalable, secure web applications with Laravel, PHP, React, Next.js, and AWS for SaaS, CRM, telecom, and e-commerce companies. Specialized in cloud telephony (FreeSWITCH, SMPP, WebRTC): increased concurrent call capacity by 40% and cut report queries to under 500 ms. Author of open-source Laravel packages with 10K+ downloads on Packagist. Led a team of 4 engineers and shipped production systems for clients in the UAE, USA, India, Saudi Arabia, and Bangladesh.

How we research, write and check articles

    Latest Posts

    View All

    Next.js Middleware Authentication and Token Refresh Flows

    Next.js Middleware Authentication and Token Refresh Flows

    Livewire Performance Optimization Under High Load

    Livewire Performance Optimization Under High Load

    Configuring Nginx Upstream Keepalive for Node Backends

    Configuring Nginx Upstream Keepalive for Node Backends

    Enforcing Immutable State Patterns in React

    Enforcing Immutable State Patterns in React

    FastAPI Dependency Overrides for Integration Testing

    FastAPI Dependency Overrides for Integration Testing

    Stopping Layout Shifts in Next.js Dynamic Imports

    Stopping Layout Shifts in Next.js Dynamic Imports

    Optimizing Agentic Tool Calling Latency

    Optimizing Agentic Tool Calling Latency

    Fixing React Server Component Serialization Errors

    Fixing React Server Component Serialization Errors

    Next.js Route Handler Streaming with ReadableStream

    Next.js Route Handler Streaming with ReadableStream

    React Form Performance: Uncontrolled Inputs and FormData

    React Form Performance: Uncontrolled Inputs and FormData