Laravel Read Replica Lag: PreventStaleDatabaseReads, usingWritePdo, and Commit IDs
Laravel 13.38 adds PreventStaleDatabaseReads and usingWritePdo(), and 13.40 adds commit IDs. Fix read replica lag so users see their own writes.
You save a record, the app redirects you back, and the page shows the old data. You reload and the new data appears. Nothing is broken in your code. Your read replica was a few milliseconds behind the primary, and you hit it before it caught up.
Laravel has had read and write connections for years, but it only helped inside a single request. Two recent releases give you better tools. Laravel 13.38 added a middleware and a helper method, and 13.40 added commit IDs that let you ask a replica whether it has caught up. Here is how each one works and when to pick it.
The problem in one request cycle
With a replicated MySQL setup, you configure separate read and write hosts in config/database.php. Laravel sends SELECT queries to a read host and everything else to the write host.
'mysql' => [
'read' => [
'host' => ['192.168.1.10', '192.168.1.11'],
],
'write' => [
'host' => ['192.168.1.20'],
],
'sticky' => true,
'driver' => 'mysql',
'database' => env('DB_DATABASE', 'laravel'),
// ...
],
The sticky option is documented in the Laravel database docs. It lets reads in the same request cycle see records written earlier in that request. That covers a controller that writes and then reads.
It does not cover the classic post/redirect/get flow. The write happens in one request and the read happens in the next. Sticky has no memory across requests, so the second request goes straight to a replica that may not have the row yet.
Fix 1: PreventStaleDatabaseReads middleware (13.38)
Laravel 13.38 shipped an opt-in middleware for exactly this case. Jack Bayliss added it in pull request 62078.
After a request writes to the default connection, the middleware stores a timestamp in the session. For the next two seconds, that user’s reads go to the write connection. After that, reads go back to the replicas.
You can append it to the web group in bootstrap/app.php:
use Illuminate\Foundation\Http\Middleware\PreventStaleDatabaseReads;
->withMiddleware(function (Middleware $middleware) {
$middleware->web(append: [
PreventStaleDatabaseReads::class,
]);
})
Or apply it to specific routes with a longer window:
Route::middleware(PreventStaleDatabaseReads::for(10))->group(function () {
Route::get('/posts/{post}', [PostController::class, 'show']);
Route::put('/posts/{post}', [PostController::class, 'update']);
});
The release notes list three limits worth knowing:
- It needs a session, so it will not help stateless API routes.
- It only tracks the default connection.
- It only covers the user who made the write. Other users can still read older data from a replica.
That last point is usually fine. Other users never saw the new value, so they cannot tell it is missing. The person who just saved a form is the one who notices.
The window is a guess, though. Two seconds works until replication lag spikes to five. That is the gap commit IDs fill, and I cover them below.
Fix 2: DB::usingWritePdo() (13.38)
The same release added usingWritePdo() in pull request 62099. It solves a subtler problem with the existing onWriteConnection() method.
onWriteConnection() only applies to the query it starts. Anything you load from the result, such as a relationship, still reads from a replica:
// The posts query still runs on a replica
$posts = User::onWriteConnection()
->where('email', $email)
->first()
?->posts()
->whereNull('published_at')
->get();
usingWritePdo() takes a callback and sends every read inside it to the write connection. It then restores the previous setting, even if the callback throws:
use Illuminate\Support\Facades\DB;
$posts = DB::usingWritePdo(fn () => User::query()
->where('email', $email)
->first()
?->posts()
->whereNull('published_at')
->get()
);
Use it for a short, specific block where correctness matters more than offloading reads, like checking an order right after payment. Wrapping a whole controller in it defeats the point of having replicas.
Fix 3: Commit IDs (13.40)
Laravel 13.40 added the most precise option. Tobias Petry contributed methods that tell you whether a replica has received a specific write (pull request 62198). Instead of guessing how long the lag is, you ask the replica.
use Illuminate\Support\Facades\DB;
// After a write, on the primary
$order = $user->orders()->create($attributes);
$commitId = DB::getLastCommitId();
// Later, on a replica
DB::hasCommitId($commitId); // Check now
DB::hasCommitId($commitId, wait: 2); // Wait up to two seconds
A mergeCommitIds() method combines several commit IDs into one, so you can wait for all of them at once.
The requirements matter here. According to the release notes, the methods work on MySQL with GTIDs enabled, MariaDB with the binary log enabled, and PostgreSQL. Waiting on PostgreSQL requires PostgreSQL 19. Other drivers throw a RuntimeException. If you run MySQL, check that GTID mode is on before you build anything around this.
One place this shines is queued work. Say a controller creates an order and dispatches a job that reads it on a worker. You can pass the commit ID along and have the job wait for the replica:
// PHP Architect ticket order job (illustrative example, not from the release notes)
class SendPhpTekReceipt implements ShouldQueue
{
public function __construct(
public int $orderId,
public string $commitId,
) {}
public function handle(): void
{
if (! DB::hasCommitId($this->commitId, wait: 2)) {
$this->release(5);
return;
}
$order = Order::findOrFail($this->orderId);
// send the PHPTek receipt
}
}
I wrote this example myself to show the shape of the idea. I have not run it against a real replica pair, so test it on your own setup first. Note that hasCommitId() is documented as checking on a replica. Make sure the connection your job uses actually reads from one.
Which one should you use?
Here is how I would pick:
- Redirect after a form post: use
PreventStaleDatabaseReads. It is one line in your middleware stack and needs no code changes. - One block that must be correct: use
DB::usingWritePdo(). It is explicit and scoped to a callback. - Cross-process work such as jobs and webhooks: use commit IDs. A session timestamp does not exist there, and a fixed window is a guess.
You can combine them. The middleware handles the common web case, and commit IDs handle the rare one where lag matters.
Related fixes worth knowing
A few smaller changes in these releases affect replica users:
- In 13.38,
lazy()andlazyById()free the previous chunk before fetching the next one. Before, two chunks sat in memory at once. See pull request 62086. - In 13.40, the
BelongsToManycreateOrFirstlookup uses the write connection (pull request 62223). A lookup on a lagging replica could otherwise miss a row that exists. - In 13.40, a connection dropped inside a transaction is discarded and re-established on the next query. Before, long-running workers could fail every later transaction with “There is already an active transaction” (pull request 62211).
Test before you trust it
Replica lag is hard to reproduce on a laptop. If you can, add artificial delay to a test replica, or pause the replication SQL thread on a staging replica, then walk through your save-and-redirect flows. If you cannot, at least confirm which connection each query uses with DB::listen() during a test run.
Also remember that Laravel 13.40 includes a security fix for Concurrency::run() with the process driver. If you use it, upgrade while you are at it.
Wrapping up
Read replicas buy you capacity, and they cost you consistency. Laravel now gives you three levels of control: a middleware for the common web flow, a callback for scoped correctness, and commit IDs for the cases where a timer is not good enough. Start with the middleware, watch your logs, and reach for the others when you find a flow that still shows old data.
Sources
- Prevent Stale Database Reads in Laravel 13.38, Laravel News
- Slow Job Alerts and Replica Commit IDs in Laravel 13.40, Laravel News
- Laravel Database documentation: read and write connections, laravel.com
- PreventStaleDatabaseReads pull request 62078, GitHub
- usingWritePdo pull request 62099, GitHub
- Commit ID pull request 62198, GitHub