Skip to content

Read/Write Splitting and Sticky Reads in Laravel: A Production Guide

Configure Laravel's read/write connection splitting correctly, avoid stale-read bugs with sticky connections, and tune connection pooling for high-throughput apps — without reaching for a third-party package.

Published · Updated · 4 min read

Read/Write Splitting and Sticky Reads in Laravel: A Production Guide

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_size in Octane: Under Swoole/RoadRunner, connections persist across requests. Explicitly close or reset connections in the RequestHandled event 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 => true prevents stale reads within a single request but has no effect across jobs or separate processes.
  • Use DB::transaction() or Model::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_connections at scale.
  • Under Laravel Octane, purge connections on RequestHandled to prevent cross-request state leakage.

Frequently asked questions

Does `sticky => true` affect queue jobs?

No. The sticky flag only tracks writes within the current PHP process lifecycle (a single HTTP request). Queue workers are separate processes with no memory of prior writes, so you must explicitly use the write connection or wrap logic in a transaction.

How do I send a specific Eloquent query to the read replica?

Use `Model::on('mysql::read')->where(...)->get()` or `DB::connection('mysql')->select(...)`. Laravel resolves `mysql::read` and `mysql::write` as virtual connection names that map to the configured read/write hosts.

Can I use read/write splitting with Laravel Octane?

Yes, but you must reset connections between requests. Call `DB::purge('mysql')` in a listener for the `RequestHandled` event, or use `DB::reconnect()`. Otherwise a worker may reuse a connection that was left in a transaction or pointing to the wrong host.

Mohamed Said

About the author

Senior Backend Engineer specializing in Laravel, scalable SaaS platforms, APIs, and cloud infrastructure. I build secure, high-performance web applications that help businesses grow.

About GitHub LinkedIn WhatsApp Email Address My CV

Have a technical challenge?

Tell me what you’re building. I reply within two working days.

Discuss your project