Ehsan Bagherzadegan
Back to articles
6 min read

Laravel 13.38: Prevent Stale Reads After Writes with New Middleware and DB::usingWritePdo()

Laravel 13.38 adds two tools for handling read replica lag: PreventStaleDatabaseReads middleware automatically routes reads to the primary after writes, and DB::usingWritePdo() gives explicit per-query control.

Laravel 13.38 shipped two new tools for a problem that bites almost every team running read replicas: stale reads after writes.

When your application writes to the primary database and immediately reads from a replica, the replica might not have caught up yet. The user sees old data — their new comment is missing, the order they just placed doesn't appear, the setting they changed hasn't taken effect.

Laravel 13.38 adds PreventStaleDatabaseReads middleware and DB::usingWritePdo() to tackle this from two angles: automatically at the request level, and surgically at the query level.

The problem: read replica lag

Read replicas are standard for scaling reads. The primary handles writes; one or more replicas handle reads. But replication is asynchronous. Under load, a replica can fall seconds behind.

// User submits a comment
$comment = Comment::create([
    'post_id' => $post->id,
    'user_id' => auth()->id(),
    'body' => $request->string('body'),
]);

// Immediately redirect to the post page
return redirect()->route('posts.show', $post);

// The post page loads comments from a replica
$comments = $post->comments()->latest()->get();
// The new comment might be missing!

The user just posted, but the replica hasn't replicated the insert yet. They see their comment disappear — or worse, think it failed and post again.

Solution 1: PreventStaleDatabaseReads middleware

This middleware tracks when the current user performs a write, then forces their subsequent reads to the primary for a short window.

// bootstrap/app.php
use Illuminate\Foundation\Http\Middleware\PreventStaleDatabaseReads;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        // ...
    )
    ->withMiddleware(function (Middleware $middleware): void {
        $middleware->web(append: [
            PreventStaleDatabaseReads::class,
        ]);
    })
    ->create();

By default it uses a 2-second window. After any write on the default connection, the user's reads stick to the primary for 2 seconds.

// Custom window (e.g., 5 seconds for slower replication)
$middleware->web(append: [
    PreventStaleDatabaseReads::for(5),
]);

// Or only on specific routes
Route::middleware(PreventStaleDatabaseReads::for(10))->group(function () {
    Route::get('/posts/{post}', PostController::class);
    Route::post('/comments', CommentController::class);
});

How it works

  1. After a write on the default connection, the middleware stores a timestamp in the session: _database_modified_at.
  2. On subsequent requests, if that timestamp is within the configured window, the middleware enables "sticky" reads — all queries use the write connection.
  3. Once the window expires, reads return to replicas.

Requirements and caveats

  • Runs after StartSession — it needs the session to store the timestamp.
  • Only tracks the default connection — if you write to mysql but read from pgsql, it won't help.
  • Per-user, not per-request — the window follows the user across requests. A write on page A affects reads on page B.
  • Not ideal for stateless APIs — no session means no tracking. For APIs, prefer usingWritePdo() (see below).

Solution 2: DB::usingWritePdo()

Sometimes you don't want a blanket rule. You know this specific query must be fresh — maybe it's the read immediately after a write in the same request, or a critical check that can't tolerate staleness.

$users = DB::connection()->usingWritePdo(fn ($connection) => 
    $connection->table('users')->where('verified', true)->get()
);

The callback receives the connection already pinned to the write PDO. You can also use the global helper without the connection instance:

$posts = DB::usingWritePdo(fn () => 
    User::where('email', $email)
        ->first()
        ?->posts()
        ->whereNull('published_at')
        ->get()
);

Why not onWriteConnection() or useWriteConnectionWhenReading()?

Method Scope Cleanup
onWriteConnection() Single query only Automatic
useWriteConnectionWhenReading() All subsequent queries Manual (dontUseWriteConnectionWhenReading())
usingWritePdo() Callback + any nested queries Automatic (even on exception)

usingWritePdo() is scoped to the callback. Any query inside — including relationship loads, eager loads, or nested callbacks — uses the write connection. When the callback returns or throws, the previous read preference is restored automatically.

// This works: the relationship query also hits the primary
$posts = DB::usingWritePdo(fn () => 
    User::where('email', $email)
        ->first()
        ?->posts()           // <-- this query also uses write connection
        ->whereNull('published_at')
        ->get()
);

// Exception safety: read preference is restored even if the callback fails
try {
    DB::usingWritePdo(fn () => 
        User::where('email', $email)->firstOrFail()
    );
} catch (ModelNotFoundException $e) {
    // Read preference is already back to normal here
}

When to use which

Use PreventStaleDatabaseReads middleware when:

  • You have a traditional web app with sessions
  • Users perform writes and immediately view the result (create → show, update → index)
  • You want a set-and-forget solution for the common case
  • Your replica lag is typically under a few seconds

Use DB::usingWritePdo() when:

  • You need fresh data for a specific operation (payment verification, inventory check, auth decisions)
  • You're building an API without sessions
  • You want explicit, auditable control in the code
  • The middleware's 2-second window is too broad or too narrow for a particular flow

Use both together when:

  • The middleware handles the common create → show flow
  • Critical sections (checkout, admin actions) use usingWritePdo() for extra safety

A practical pattern: write → read in the same request

A common pattern: create a resource, then fetch it for the response (API) or redirect (web).

// Controller
public function store(StoreCommentRequest $request, Post $post)
{
    $comment = $post->comments()->create([
        'user_id' => $request->user()->id,
        'body' => $request->string('body'),
    ]);

    // API: return the fresh comment with relationships
    if ($request->expectsJson()) {
        return DB::usingWritePdo(fn () => 
            $comment->load('user', 'reactions')
        );
    }

    // Web: middleware handles the redirect → show flow
    return redirect()->route('posts.show', $post);
}

The API response uses usingWritePdo() to guarantee the returned comment includes the fresh data. The web flow relies on the middleware to handle the subsequent GET request.

What about replica lag monitoring?

These tools mitigate the symptom. You should still monitor replication lag:

-- MySQL / MariaDB
SHOW REPLICA STATUS\G
-- Seconds_Behind_Source (or Seconds_Behind_Master on older versions)

-- PostgreSQL
SELECT EXTRACT(EPOCH FROM (now() - pg_last_xact_replay_timestamp())) 
AS replica_lag_seconds;

Alert when lag exceeds your middleware window. If replicas regularly lag 10+ seconds, a 2-second window won't help — fix the replication or increase the window.

TL;DR

  • Read replica lag causes stale reads after writes.
  • PreventStaleDatabaseReads middleware — automatic, session-based, 2-second default window. Add to web middleware group.
  • DB::usingWritePdo() — explicit, callback-scoped, exception-safe. Use for critical reads or APIs.
  • Both target the same problem from different angles. Use one, the other, or both.

Upgrade to Laravel 13.38 and pick the tool that fits your architecture. Your users will stop asking "where did my comment go?"

Sources