Recipe: Read replica routing strategy
Route read queries to replicas while directing writes to the primary node. This pattern keeps your database responsive under load without sacrificing consistency guarantees.
Overview
When your application grows beyond a single database instance, introducing read replicas offloads SELECT traffic. The challenge is routing correctly — stale reads on a replica that hasn't caught up can break user expectations. This recipe covers connection-pool splitting, lag-aware routing, and write-after-read consistency.
Connection pool split
Maintain two connection pools: one for the primary (writes + strongly-consistent reads) and one for replicas (eventually-consistent reads). Tag each query at the application layer so the ORM or query builder selects the correct pool automatically.
replica → SELECT (no locking)
Lag-aware routing
Monitor replication lag per replica. If lag exceeds your threshold (commonly 1–2 seconds), temporarily remove that replica from the read pool. Reintroduce it once lag drops back within bounds. Most managed databases expose lag as a metric.
Write-after-read consistency
After a user performs a mutation, route their subsequent reads to the primary for a short window (e.g. 5 seconds). Use a session-scoped flag or a sticky cookie. This prevents the “I just saved but it disappeared” UX bug.