Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Cached Database Stickiness Laravel Package

mpyw/laravel-cached-database-stickiness

Keeps Laravel's read/write database stickiness alive across requests by caching it. After a write, later requests are routed to the primary connection for a set period, preventing stale reads from replicas when using read/write connection splitting.

View on GitHub
Deep Wiki
Context7

Getting Started

mpyw/laravel-cached-database-stickiness solves a problem Laravel's built-in sticky flag can't: read-replica lag across requests. Laravel's sticky => true only forces the write PDO for the remainder of the current request. This package caches the fact that a write happened, so the next few requests also read from the primary until the TTL expires.

Minimum setup:

  1. composer require mpyw/laravel-cached-database-stickiness — the service provider is auto-discovered. As of v2.2.1 the constraints accept Laravel through ^14.0 and CI covers PHP 8.5, so it will resolve on current and upcoming Laravel majors.
  2. Configure a read/write split connection in config/database.php as you normally would:
'mysql' => [
    'read'  => ['host' => ['replica-1', 'replica-2']],
    'write' => ['host' => ['primary']],
    'sticky' => true,          // still required — the package extends this behaviour
    'driver' => 'mysql',
    // ...
],
  1. Point the package at a shared, persistent cache store (Redis/Memcached/database — not array) and set a TTL roughly equal to your replica lag SLA.
  2. Register the package's HTTP middleware (see the README's Middleware section for the exact FQCN in your version) in the global stack or the web group — in Laravel 11+ that's bootstrap/app.php via ->withMiddleware(...).

Where to look first: the README is short and is the authoritative source for class names and config keys, then the package's service provider to see exactly what it decorates in DatabaseManager. First use case: a user saves a profile (write → primary), gets redirected, and the follow-up GET hits a replica that hasn't caught up and renders stale data. That redirect-then-read flow is exactly what this package fixes and is the fastest way to validate your install.

Implementation Patterns

  • Apply the middleware broadly, not per-route. Stickiness is only useful if the next request (usually a redirect target or an unrelated page) also sees it. Global or web-group registration is the sane default.
  • Non-HTTP contexts need manual handling. Middleware doesn't run in queued jobs, Artisan commands, or scheduled tasks. After a job writes, either call useWritePdo() explicitly or wrap the follow-up read in the package's helper so the cached stickiness is set.
  • Tune TTL against measured replica lag. TTL is the trade-off dial: too short and users still see stale reads; too long and you've quietly turned your primary into the read node. Start at your p99 lag plus headroom and measure primary QPS before/after.
  • Stickiness is per connection name. Multi-tenant or multi-database apps get independent keys per connection, which is usually what you want, but watch cache cardinality.
  • Testing: set the cache driver to array and disable stickiness in phpunit.xml, or test against SQLite with no read/write split. Assert on getReadPdo() vs getPdo() only in a dedicated integration test.
  • Observability: log the connection actually used for read paths for a week after rollout. Primary QPS is the metric that tells you whether TTL is too aggressive.

Gotchas and Tips

  • v2.2.1 is a maintenance release. No runtime code changed — only composer constraints (^14.0) and the CI matrix (PHP 8.5). Upgrading from 2.2.0 is risk-free, but note that widened constraints mean Composer can now install this on an unreleased Laravel major before broad real-world validation; pin if that makes you nervous.
  • Write detection is not magic. Laravel flags a connection as modified on affecting statements; raw SELECT-shaped writes, INSERT ... RETURNING executed via select(), and stored procedures that mutate data may not register. If writes go through those paths, set stickiness explicitly.
  • array or null cache driver silently kills the feature — state won't survive the request. Same for a per-server cache when you run multiple app servers behind a load balancer.
  • cache:clear and deploys drop all stickiness. Right after a deploy you're back to raw replica reads, which is precisely when you don't want stale reads. Consider a distinct cache store/prefix so routine cache flushes don't nuke it, and never share the key namespace between environments.
  • Transactions already read from the write PDO, so don't expect the package to change behaviour inside DB::transaction().
  • Debugging: compare DB::connection('mysql')->getReadPdo() with ->getPdo(), enable DB::listen() to see which host served each query, and confirm config('database.connections.mysql.sticky') is actually true — forgetting that flag is the most common "it does nothing" report.
  • Octane: long-lived workers make any static state suspect. This package is cache-backed, so it's generally safe, but verify stickiness resets correctly between requests on your Octane version.
  • Extension points: swap the cache store and TTL via config, and decorate connection classes if you need custom write-detection for a driver the package doesn't special-case.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
socialdept/atp-orm
cboxdk/laravel-assistant-client
socialdept/atp-resolver
socialdept/tenant-domains
tautvydasr/blade-class-names
socialdept/color-scales
maherelgamil/controller
coleus/widgets
coleus/table
coleus/users
coleus/music
coleus/health
coleus/calendar
coleus/notes
coleus/support
coleus/settings
coleus/apps
seampact/laravel
emmyconceptng/laravel-ng-postcode
jjsquady/round-robin