If your Laravel app reads from replicas and writes to a primary, you have probably seen this bug: a user saves a form, gets redirected, and the next page still shows the old data. The replica simply hasn’t caught up yet. Laravel 13.40 added commit ID methods that let you ask a replica whether it already has a specific write, and a Laravel News tutorial published on 12 November 2026 shows how to build “read your own writes” on top of them. This guide walks through the API, the database settings it needs, and two production patterns: a session middleware and a queued job.

Why time windows are not enough

Laravel 13.38 added a PreventStaleDatabaseReads middleware that sends a user’s reads to the primary for a short time after a write, with a two-second default. That works, but two seconds is a guess. If replication lag is longer, the user still sees stale data. If it is shorter, you send reads to the primary that a replica could have answered.

Commit IDs replace the guess with a check. You record the primary’s replication position after a write, then ask the replica whether it has reached that position.

The three new methods

The methods were contributed by Tobias Petry in laravel/framework#62198 and shipped in Laravel 13.40:

use Illuminate\Support\Facades\DB;

// After a write, on the primary
$order = Order::create([...]);
$commitId = DB::getLastCommitId();

// Later, on the read connection
DB::hasCommitId($commitId);          // checks once, returns at once
DB::hasCommitId($commitId, wait: 2); // waits up to 2 seconds

// Combine IDs from several writes into one
$combined = DB::mergeCommitIds([$firstId, $secondId]);
  • getLastCommitId() always queries the write connection and returns the primary’s current position as a string.
  • hasCommitId() returns true when the server has applied everything up to that ID. wait is a whole number of seconds; with the default 0 it checks once. With a higher value it blocks until the replica catches up or the timeout passes, then returns false.
  • mergeCommitIds() combines several IDs into one that covers all of them. It throws a RuntimeException for an empty array.

The ID format depends on the database:

Database Commit ID source Example
MySQL @@global.gtid_executed (GTID set) 3e11fa47-71ca-11e1-9e33-c80aa9429562:1-77
MariaDB @@gtid_binlog_pos 0-1-1052
PostgreSQL pg_current_wal_lsn() 0/16B3748

Check your database first

This feature depends on server settings, so confirm them before writing code:

Database Required settings wait supported
MySQL log_bin, gtid_mode = ON, enforce_gtid_consistency = ON Yes
MariaDB log_bin Yes
PostgreSQL None PostgreSQL 19 and later
SQLite, SQL Server Not supported Not supported

MySQL 8 enables binary logging by default but not GTIDs, and MariaDB disables binary logging by default. When a setting is missing, getLastCommitId() throws a RuntimeException naming what is missing. On PostgreSQL 18 and earlier, calling hasCommitId() with a wait value throws. Managed database services may not let you change these settings, so check your provider’s documentation.

A quick way to verify on MySQL:

SELECT @@log_bin, @@gtid_mode, @@enforce_gtid_consistency;

Which server does hasCommitId() ask?

hasCommitId() runs a select, so it goes wherever your other reads go in that request. In three cases that is the primary:

  • the call runs inside a database transaction,
  • the connection has sticky enabled and the request already wrote,
  • reads are forced to the writer with useWriteConnectionWhenReading() or usingWritePdo().

The primary always has its own commits, so the method returns true there, which is still correct for the reads that follow. Also note that a connection keeps one read PDO per request. With several replica hosts, the next request may land on a different replica, so check on every request instead of caching the result.

Pattern 1: read-your-own-writes middleware

This middleware stores a commit ID in the session instead of a timestamp. On each request it asks the replica if it has caught up. If yes, it clears the session key; if not, the request reads from the primary.

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpFoundation\Response;

class ReadYourOwnWrites
{
    public function handle(Request $request, Closure $next): Response
    {
        $pending = $request->session()->get('db_commit_id');

        if ($pending !== null) {
            if (DB::hasCommitId($pending)) {
                $request->session()->forget('db_commit_id');
                $pending = null;
            } else {
                DB::useWriteConnectionWhenReading();
            }
        }

        $response = $next($request);

        if (DB::hasModifiedRecords()) {
            $commitId = DB::getLastCommitId();

            $request->session()->put('db_commit_id', $pending === null
                ? $commitId
                : DB::mergeCommitIds([$pending, $commitId]));
        }

        return $response;
    }
}

Register it in the web group in bootstrap/app.php so it runs inside the session middleware:

use App\Http\Middleware\ReadYourOwnWrites;

->withMiddleware(function (Middleware $middleware) {
    $middleware->web(append: [
        ReadYourOwnWrites::class,
    ]);
})

Notice it uses an immediate check, not wait. Waiting inside a web request would hold the response open, while the primary could simply answer the read. The cost is one extra query on the replica for requests with a pending ID, and one extra query on the primary for requests that write. If replication stops entirely, that user keeps reading from the primary and still sees correct data.

Pattern 2: wait for the replica in a queued job

A job dispatched right after a write can start before the replica has the row. Workers have no session, so pass the commit ID to the job:

$order = DB::transaction(function () use ($request) {
    $order = Order::create([...]);
    $order->lines()->createMany([...]);

    return $order;
});

SendOrderConfirmation::dispatch($order->id, DB::getLastCommitId());

Call getLastCommitId() after the transaction commits. Inside the transaction the order isn’t committed yet, so the ID wouldn’t include it.

namespace App\Jobs;

use App\Mail\OrderConfirmation;
use App\Models\Order;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;

class SendOrderConfirmation implements ShouldQueue
{
    use Queueable;

    public function __construct(
        public int $orderId,
        public string $commitId,
    ) {}

    public function handle(): void
    {
        if (DB::hasCommitId($this->commitId, wait: 2)) {
            $this->send();

            return;
        }

        DB::usingWritePdo(fn () => $this->send());
    }

    protected function send(): void
    {
        $order = Order::with('lines', 'customer')->findOrFail($this->orderId);

        Mail::to($order->customer)->send(new OrderConfirmation($order));
    }
}

Two subtle points from the tutorial:

  • Pass the ID, not the Order model. With SerializesModels, Laravel reloads model properties before handle() runs, and on a lagging replica that query can throw ModelNotFoundException before your check even happens.
  • Use usingWritePdo() for the fallback rather than useWriteConnectionWhenReading(). Workers reuse connections across jobs, and usingWritePdo() restores the previous setting when the callback returns.

Rollout checklist

  1. Upgrade to Laravel 13.40 or later (composer update laravel/framework).
  2. Confirm GTID/binlog settings (MySQL/MariaDB) or your PostgreSQL version.
  3. Add the middleware to the web group and test a save-and-redirect flow.
  4. Update jobs that run right after writes to accept a commit ID.
  5. Watch query counts on the primary for a few days after rollout.

Takeaway

Commit IDs turn replica lag from a guess into a yes/no question. With three small methods you can send users to a replica as soon as it has their write, fall back to the primary only when needed, and make queued jobs safe right after a commit. Read the full Laravel News tutorial and PR #62198 for the details.