How-To Guide

How to Configure Read-Write Splitting

Route writes to the primary and reads to replicas, pin post-write reads, monitor replication lag, and keep failover semantics explicit.

On this page

  1. Introduction
  2. Classify queries before routing
  3. Implement the router at one choke point
  4. Pin sessions after writes
  5. Monitor lag as a first-class signal
  6. Failover and the split
  7. Test the routing policy
  8. Common pitfalls
  9. Conclusion

Introduction

Read traffic dominates most applications by an order of magnitude, and vertical scaling of a single database eventually loses to the simplest horizontal move: add replicas, send reads to them, and keep writes on the primary. The topology is easy; the correctness is not. Replication is asynchronous by default, so a replica can be arbitrarily behind, and three classes of bugs follow: read-your-writes violations, where a user edits a profile and immediately sees the old version from a lagging replica; monotonicity violations, where a user sees a newer value, then an older one, as they bounce between replicas at different positions; and replica-driven inconsistency inside analytics that mix replicas at different LSNs. Configuring read-write splitting properly is therefore mostly about routing policy: which reads may be stale, which must not, how sessions pin after their own writes, and what happens when lag exceeds tolerance. This tutorial implements the router, the pinning window, lag monitoring, and failover, treating the query classification as the actual engineering.

Classify queries before routing

The router is only as correct as the classification feeding it, and classification is a product decision per route. Four classes cover the space. Writes and the reads inside the same transaction: always the primary, non-negotiably, because transactional reads must see the transaction’s own writes and replicas cannot serve another node’s in-flight transaction. Stale-tolerant reads: listings, search, analytics, dashboards, anything where a few hundred milliseconds of staleness is invisible; these are the replica workload and the entire point of the topology. Read-your-writes flows: profile editing, settings changes, checkout after address entry; the session that wrote must read its own write within some bounded window, handled by pinning in the next section. Cross-route aggregates that combine multiple reads into one user view: they need either one replica for all parts, to avoid mixing positions, or the primary if any part is freshness-critical. Writing this classification down per endpoint is the work; the router then just executes tags.

Implement the router at one choke point

The split must live at exactly one layer, because two routing implementations drift apart silently. Three common shapes: an ORM session-level hook that inspects a read-write tag per query; a database client wrapper that exposes two handles and a policy function; or a proxy between application and database that parses and routes. The wrapper shape, one choke point with an explicit policy, is the easiest to test and audit.

export class SplitRouter {
 constructor(private primary: Db, private replicas: Db[],
       private lagMonitor: LagMonitor) {}

 async query<T>(sql: string, params: unknown[], opts: RouteOpts = {}): Promise<T> {
  const target = this.route(opts);
  return target.query(sql, params);
 }

 private route(opts: RouteOpts): Db {
  if (opts.role === 'write' || opts.inTransaction) return this.primary;
  if (opts.sessionPinnedUntil && Date.now() < opts.sessionPinnedUntil) return this.primary;
  const healthy = this.replicas.filter(
   r => this.lagMonitor.lagMs(r) < (opts.lagBudgetMs ?? 1000));
  if (healthy.length === 0) return this.primary;
  return healthy[stickyBucket(opts.sessionId, healthy.length)];
 }
}

Note the sticky bucket on session id in the replica choice: routing one user to one replica consistently gives monotonic reads for free, avoiding the seesaw of newer-then-older values, at the cost of slightly less even load, a trade almost always worth making.

Pin sessions after writes

Read-your-writes is the complaint that kills confidence in a split topology, and the fix is a pinning window: after a session performs a write, its subsequent reads go to the primary for a bounded period, typically one to five seconds, or until the monitor confirms every replica has replayed past the session’s last write LSN. The LSN-based form is precise: record the primary’s write position with the write, and unpin when the chosen replica reports being past that position. The time-based form is simpler and adequate for most products, sized to p99 replication lag plus margin. Pinning state lives with the session, a signed cookie or server-side session entry carrying pinned-until, so it survives the multiple requests of an edit flow. The failure mode to avoid is pinning forever: sessions that wrote once and never unpinned gradually concentrate all their traffic on the primary, silently undoing the split. Bound the window absolutely, and export the pinned-read fraction as a metric, because a pinned fraction creeping toward one hundred percent means the lag budget is being violated in production and the primary is absorbing the split’s intended workload.

Monitor lag as a first-class signal

Replica lag is the health metric of the entire topology, and it needs per-replica, second-resolution telemetry from pg_stat_replication on the primary or the equivalent per-replica replay position. Alert on two conditions: absolute lag exceeding the routing budget, which should trigger the router’s fallback, and lag trend, a replica whose lag grows monotonically for minutes is failing, replaying a giant transaction, or resource-starved, and it should be drained before users feel it. The router consumes the same signal: reads whose lag budget exceeds current lag go to replicas, and when no replica qualifies, the primary serves the read, an automatic degradation that trades primary load for correctness. That fallback needs capacity headroom on the primary, the second capacity planning number after the split ratio itself: the topology must survive all replicas lagging, or all replicas lost, with the primary carrying full read load, even briefly. Dashboards should show writes per second on the primary, reads per second split by target, pinned-read fraction, and per-replica lag, because together those four charts answer every splitting incident’s first question.

Failover and the split

Primary failure under a split topology has an extra failure mode: stale reads from a promoted replica. Promoting a replica that lagged means losing writes acknowledged on the old primary, and reads routed to other replicas that now lag behind the new primary see pre-promotion data. The procedure deserves explicit design. Promotion: choose the replica with the least lag, promote it, and repoint the router’s primary handle, through DNS, a proxy config, or a coordination service; client libraries with topology awareness can automate this, but the automation must be tested, because failover code paths rot. Stale reads during the window: route reads to the primary, or read from replicas with a lag budget of zero, until replicas catch up to the new primary’s position. Split-brain prevention: fencing the old primary, refusing its writes through a fencing mechanism, matters more in split topologies because a zombie primary accepting writes while a new one serves them forks the data set permanently. Rehearse the whole flow, promotion, router repoint, lag drain, zombie fencing, on a schedule, because an unrehearsed failover under load is where split topologies die publicly.

Test the routing policy

The router is pure logic over tags and lag numbers, which makes it table-testable: for each combination of role, transaction state, pin state, and lag, assert the target. The integration tests are where the real bugs live. Read-your-writes: write through the router, immediately read through a session, and assert the read sees the write even with a synthetic replica lag injected by pausing replay. Monotonicity: read a key repeatedly on one session with staggered replica positions and assert the observed value never regresses. Fallback: with all replicas’ lag inflated past the budget, assert reads land on the primary and that the pinned fraction metric moves. Failover drill: kill the primary, assert promotion completes, the router repoints, and reads during the drain window are correct. Inject lag deliberately in CI with replication pauses, because replication under normal operation is fast enough to hide every one of these bugs until production has its first bad hour.

it('pins reads after a session write', async () => {
 await router.query(updateProfile, [userId, 'Alice'], { role: 'write', sessionId });
 replica.pauseReplay();
 const row = await router.query(getProfile, [userId],
  { role: 'read', sessionId, lagBudgetMs: 1000 });
 expect(row.name).toBe('Alice');
});

Common pitfalls

  • Blind replica routing. Every read to replicas breaks read-your-writes on every edit flow; classification first, routing second.
  • Pinning that never releases. Sessions pinned indefinitely concentrate reads on the primary and quietly undo the split.
  • One global lag budget. Dashboards and profile pages tolerate different staleness; set budgets per route.
  • Bouncing between replicas. Per-request replica choice causes seesaw staleness; sticky sessions give monotonic reads.
  • No primary headroom. All-replicas-lagged fallback dumps full read load on the primary instantly; capacity for it.
  • **Unrehearsed failover. ** Promotion, repointing, and drain steps that are written but never drilled fail when needed.

Conclusion

Read-write splitting buys read throughput with a routing policy, and the policy is the product. Classify queries honestly: transactional reads and writes belong to the primary, stale-tolerant reads to replicas, and post-write sessions pin to the primary for a bounded window so users always see their own edits. Route at exactly one choke point with explicit tags, choose replicas stickily per session for monotonic reads, and consume per-replica lag telemetry as both a routing input and an alert. Give the primary headroom for the all-replicas-degraded fallback, design and rehearse promotion with its stale-read drain, and test the policy with injected lag, because replication working well hides exactly the bugs the topology creates. Done this way, replicas add capacity without subtracting correctness, and the first lag incident is a dashboard event instead of a support storm.

Sources: PostgreSQL: hot standby, MySQL: replication, PostgreSQL: transaction isolation.

FAQ

How much replication lag is acceptable?
It is a product decision per feature: an analytics dashboard tolerates seconds, a profile page right after an edit tolerates none. Set per-route lag budgets rather than one global number, and monitor actual lag against each budget.
Why do my users see their own edits disappear?
The write hit the primary and the immediate read hit a replica that had not replayed it yet. This read-your-writes violation is the top complaint after adopting splitting; fix it with post-write session pinning.
Should the router live in the app or a proxy?
App-level routing sees transaction and session context, which pinning requires, while proxies are language-agnostic and centrally configurable. Many deployments use a proxy for the mechanics and app tags for the policy.

Related Examples