Why Read/Write Splitting Matters
Once your application crosses a few hundred requests per second, a single database node becomes the bottleneck. Adding a read replica is the standard first move, but Laravel's built-in support for read/write splitting has several sharp edges that can silently serve stale data or exhaust your replica's connection pool.
This article covers the mechanics, the pitfalls, and the production-safe patterns.
The Basics: Configuring a Read Replica
// config/database.php
'mysql' => [
'driver' => 'mysql',
'read' => [
'host' => [
env('DB_READ_HOST_1', '10.0.1.11'),
env('DB_READ_HOST_2', '10.0.1.12'),
],
],
'write' => [
'host' => env('DB_WRITE_HOST', '10.0.1.10'),
],
'sticky' => true,
'database' => env('DB_DATABASE', 'app'),
'username' => env('DB_USERNAME'),
'password' => env('DB_PASSWORD'),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
],
Laravel randomly selects one host from the read.host array per request. All SELECT queries go to the read connection; INSERT, UPDATE, DELETE, and DDL go to the write connection.
The sticky Option: What It Actually Does
The sticky flag is the most misunderstood setting. When true, Laravel records whether the write connection was used during the current request. If it was, all subsequent reads in that same request are also routed to the write connection.
This prevents the classic stale-read bug:
// Without sticky=true this can return the old value
$user = User::create(['email' => 'new@example.com']);
$found = User::where('email', 'new@example.com')->first(); // reads from replica!
With sticky => true, the second query hits the primary because a write already occurred in this request lifecycle.
Caveat: Sticky reads only apply within a single PHP process/request. Queue jobs, scheduled commands, and separate HTTP requests have no memory of prior writes. For those cases you need explicit connection hints.
Forcing a Connection Explicitly
For queue jobs that process data immediately after a write, force the primary:
// In a job's handle() method
public function handle(): void
{
// Always read from primary in this job
$order = Order::on('mysql::write')->find($this->orderId);
// Or use the DB facade
$result = DB::connection('mysql')->select(
'SELECT * FROM orders WHERE id = ?',
[$this->orderId]
);
}
Alternatively, wrap the critical section:
DB::transaction(function () use ($orderId) {
// Inside a transaction, Laravel always uses the write connection
$order = Order::lockForUpdate()->find($orderId);
$order->update(['status' => 'processed']);
});
Transactions are always routed to the write connection — this is a safe, idiomatic way to guarantee consistency.
Connection Pooling Considerations
Laravel does not maintain persistent connection pools itself; each PHP-FPM worker opens its own connection. With 50 workers × 3 replicas, you can easily exhaust max_connections.
Practical mitigations:
- PgBouncer (PostgreSQL) / ProxySQL (MySQL): Place a pooler in front of your replicas. Laravel connects to the pooler; the pooler multiplexes to the DB.
options.PDO::ATTR_PERSISTENT: Persistent PDO connections reuse the socket across FPM requests. Use with care — they can hold locks and transactions across requests if not cleaned up.pool_sizein Octane: Under Swoole/RoadRunner, connections persist across requests. Explicitly close or reset connections in theRequestHandledevent if you use Octane.
// Octane-safe connection reset
Event::listen(RequestHandled::class, function () {
DB::purge('mysql'); // drops and re-opens on next query
});
Monitoring Which Connection Is Used
During development, log the connection name alongside slow queries:
DB::listen(function ($query) {
if ($query->time > 100) {
Log::warning('Slow query', [
'connection' => $query->connectionName,
'sql' => $query->sql,
'time_ms' => $query->time,
]);
}
});
In production, Telescope's query watcher surfaces the connection name in the UI — invaluable for confirming that analytics queries are actually hitting replicas.
Key Takeaways
sticky => trueprevents stale reads within a single request but has no effect across jobs or separate processes.- Use
DB::transaction()orModel::on('mysql::write')to guarantee primary reads in async contexts. - Route long-running analytics queries explicitly to a replica with
Model::on('mysql::read'). - Use PgBouncer or ProxySQL to avoid exhausting
max_connectionsat scale. - Under Laravel Octane, purge connections on
RequestHandledto prevent cross-request state leakage.