Back to Blog
PostgreSQL 19's WAIT FOR LSN and Laravel Read Replicas
PostgreSQL 19 adds a WAIT FOR LSN command so a read replica can wait until it has caught up with a write before you query it. Laravel already has sticky connections and a time-based middleware for stale reads. I compare the two and sketch a middleware that uses both.
Back
Engineering
Table of contents
If you've ever put a Laravel app on a primary plus one or two read replicas, you probably know this bug report. A user saves a form, gets redirected, and the page shows the old data. Refresh, and it's fine. The write went to the primary. The next request read from a replica that hadn't replayed it yet.
PostgreSQL 19, released on November 19, 2026, adds a command aimed at exactly this: WAIT FOR LSN. The release announcement describes it as "read-your-writes" consistency for applications that send reads to standbys. I read the docs page for the command and compared it with what Laravel already offers. This post is based on the docs and the Laravel source, not on a production rollout. I haven't run the sketch below against a real PostgreSQL 19 replica yet.
What Laravel does today
Laravel has two tools for this, and both are documented on the 13.x database page.
The sticky option. On a read/write connection, once a write happens during a request, every later read in that same request goes to the write connection. It only covers the current request, so it does nothing for the redirect case above.
The PreventStaleDatabaseReads middleware. It covers later requests in the same session. Looking at the source, it's simple: when a request modified records, it stores a timestamp in the session, and for the next two seconds (configurable with PreventStaleDatabaseReads::for(5)) reads on the default connection go to the write connection. It only tracks the default connection and only the current user's session.
Laravel 13.43 (November 17) also added DB::withoutAffectingStickiness(), so a small bookkeeping write, like a job progress update, doesn't push the rest of the request onto the primary.
All of these work by guessing. Two seconds is a guess about replication lag. If your replica is usually 50 ms behind, you send two seconds of reads to the primary for nothing. If it falls 10 seconds behind during a heavy migration, two seconds isn't enough and the stale page comes back.
What WAIT FOR LSN does
Every change in PostgreSQL is written to the WAL, and every position in it has a log sequence number (LSN). WAIT FOR LSN runs on a standby and blocks until that standby has reached a given LSN:
sql
WAIT FOR LSN '0/0306EE20' WITH (TIMEOUT '200ms', NO_THROW);The details from the docs that matter for an app:
- The default mode is
standby_replay, which waits until the change is actually applied and visible to queries. There are alsostandby_writeandstandby_flush(WAL received, not necessarily applied) andprimary_flushfor the primary. For read-your-writes you want the default. - Without a timeout, or with a timeout of zero, it waits forever. Always set one. The docs also warn that a timeout of half a millisecond or less rounds down to zero.
- Without
NO_THROW, a timeout raises an error. With it, the command returns a status:success,timeout, ornot in recovery. The last one means you ran it on a primary, or the standby was promoted while you waited. - It has to run as a top-level command, not inside a function or a
DOblock, and not inside a transaction that already holds a snapshot. If the session already holds a lock and the target is not reached yet, the wait is rejected. The docs say to run it outside a transaction block, or as the first statement of one, before anything that takes locks. - The LSN to wait for comes from the primary after the write commits. The docs example uses
pg_current_wal_insert_lsn()right after the write, and they say the application or the connection pooler has to keep track of it.
With WAIT FOR LSN you can wait on the replica until it has caught up to a specific write, with a timeout you choose, rather than sending every read to the primary for a fixed window.
A sketch for Laravel
Laravel has no built-in support for this, as far as I can see in the 13.x docs and source. But the pieces are already there. Connection has hasModifiedRecords(), selectFromWriteConnection() and useWriteConnectionWhenReading(), which is exactly what PreventStaleDatabaseReads uses. So a middleware with the same shape could store an LSN instead of a timestamp:
php
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class WaitForReplicaLsn
{
public function handle(Request $request, Closure $next)
{
$db = DB::connection('pgsql');
$lsn = $request->session()->get('pg_last_write_lsn');
if ($lsn !== null && preg_match('#^[0-9A-F]{1,8}/[0-9A-F]{1,8}$#i', $lsn)) {
$row = $db->selectOne(
"WAIT FOR LSN '{$lsn}' WITH (TIMEOUT '200ms', NO_THROW)"
);
if (($row->status ?? null) === 'success') {
$request->session()->forget('pg_last_write_lsn');
} else {
// Replica too far behind, or we are talking to a primary.
$db->useWriteConnectionWhenReading();
}
}
$response = $next($request);
if ($db->hasModifiedRecords()) {
$request->session()->put(
'pg_last_write_lsn',
$db->selectFromWriteConnection('select pg_current_wal_insert_lsn() as lsn')[0]->lsn
);
}
return $response;
}
}A few notes on why it looks like this:
selectOne()uses the read connection by default, so the wait runs on the replica that the rest of the request will read from. Laravel picks one read host per connection, so the wait and the later queries should hit the same server.- The LSN is put into the SQL string instead of a binding. PostgreSQL utility commands generally do not accept bind parameters, and I'd rather not find out at runtime. That is why the value is checked against the LSN format first. It comes from our own session, but I still wouldn't interpolate anything unchecked.
- On anything other than
success, it falls back to the write connection for the request, which is the same behavior the existing middleware gives you. - The middleware has to run after
StartSession, likePreventStaleDatabaseReads, and it should run early, before your app opens a transaction.
Things I'm not sure about yet, and would test first: whether pdo_pgsql prepares this statement without complaint (Laravel's select goes through prepare()), and how it behaves through PgBouncer in transaction mode. The wait itself is about the server's replay position, not the session, so I expect it to be fine as long as the pooler points at one replica, but I haven't checked.
When I would not bother
- If you have no read replicas, none of this matters. On a primary, the command just returns
not in recovery. - Your replicas must run PostgreSQL 19, since the command runs on the standby. With physical streaming replication the primary and the standbys are on the same major version anyway, so in practice this means the whole cluster is upgraded. I haven't checked which managed providers offer PostgreSQL 19 yet.
- Queued jobs and API clients without a session need a different place to keep the LSN. For a job, you could pass it in the payload when you dispatch it right after a write.
- If two seconds of reads on the primary after each write is cheap for you, the existing middleware is simpler and already maintained by Laravel.
Where I think it pays off is an app with a lot of reads, replicas that are usually close behind but sometimes lag badly, and users who notice stale pages. There, waiting a few milliseconds on the replica is cheaper than sending reads to the primary, and the timeout keeps the worst case bounded.
PostgreSQL 19 has plenty of other things in it, like REPACK (CONCURRENTLY), pg_plan_advice, INSERT ... ON CONFLICT DO SELECT and JIT being off by default. The release notes are worth a read before you upgrade. This is just the one that maps most directly onto a problem I've seen in Laravel apps.
Sources
Comments
No comments yet
Loading comments...