Tutorial

How to Implement Database Read Replicas

Route read queries to replica databases and writes to the primary, with health checks and fallback when replicas lag or fail.

On this page

  1. Introduction
  2. The problem
  3. Design decisions
  4. Implementation
  5. Testing the boundary
  6. Common pitfalls
  7. Operational considerations
  8. Conclusion

Introduction

Read replicas scale read throughput by directing queries to copies of the primary database. The primary handles writes and replicates them to the replicas; the replicas serve reads. This works well for read-heavy workloads but introduces two challenges: routing queries to the right database and handling replication lag. This guide builds a router that sends writes to the primary, reads to a healthy replica, and falls back to the primary when consistency matters.

The problem

If every query goes to the primary, read load limits write throughput. If reads go to a replica without checking lag, a user who writes then reads may see stale data. If a replica fails and the router does not detect it, reads start timing out. A good router needs health checks, lag awareness, and a fallback strategy.

Design decisions

The router holds connection pools for the primary and each replica. It tracks the health of each replica with a periodic ping and a lag check. Writes always go to the primary. Reads go to the healthiest replica by default, but a session can mark a read as critical after a write, routing it to the primary for read-your-writes consistency. If all replicas are unhealthy, reads fall back to the primary.

class ReplicaRouter {
  primary; replicas = []; healthy = new Set();
  async read(sql, opts = {}) {
    if (opts.critical) return this.primary.query(sql);
    const replica = this.pickHealthyReplica();
    return (replica || this.primary).query(sql);
  }
  async write(sql) { return this.primary.query(sql); }
}

Implementation

The health check runs on a timer: it pings each replica and queries its lag. A replica is healthy if the ping succeeds and the lag is below a threshold. The picker selects a healthy replica round-robin, or the least-lag replica if configured. After a write, the request context sets a critical flag for the next read on the same key, so the router sends it to the primary. The flag expires after a short window or when the lag catches up.

async healthCheck() {
  for (const r of this.replicas) {
    try {
      const [{ lag }] = await r.query('SELECT EXTRACT(EPOCH FROM now() - pg_last_xact_replay_timestamp()) AS lag');
      if (lag < this.maxLag) this.healthy.add(r); else this.healthy.delete(r);
    } catch { this.healthy.delete(r); }
  }
}

Testing the boundary

Test that a write followed by a critical read returns the written data from the primary. Test that a non-critical read goes to a replica. Test that when all replicas are marked unhealthy, reads fall back to the primary without errors. Test that a replica with lag above the threshold is removed from the healthy set and reinstated when lag drops.

Common pitfalls

Avoid routing all reads to one replica; distribute load with round-robin or least-connections. Avoid ignoring lag; a replica hours behind the primary returns stale data silently. Avoid long-lived critical flags; they defeat the purpose of replicas by sending too many reads to the primary. Avoid failing open when all replicas are down; the primary should handle reads, not return an error.

Operational considerations

Route every write and every read inside a write transaction to the primary, and route standalone reads to a replica. The rule is simple to state and easy to get wrong in an ORM that lazily loads relations after the transaction closes, because the lazy load may hit a replica and read stale data the primary just wrote. To prevent read-after-write inconsistency, attach a read-after-write token to the request context after a write: for a short window, reads on the affected keys go to the primary, and only after the window expires do they return to the replica. The window should match your expected replication lag plus a margin, not a guess.

Measure replication lag continuously with a query against the replication status, and alert when lag exceeds a threshold. PostgreSQL exposes lag via pg_stat_replication, MySQL via SHOW REPLICA STATUS. A replica that lags beyond the threshold should be removed from the read pool until it catches up, because serving stale reads from a lagging replica is worse than routing the extra load to the primary. The health check that removes the replica should also drain its in-flight connections, not just stop new ones, so a query in flight on a failing replica is not cut off mid-execution.

Maintain separate connection pools for the primary and for each replica, and pick a replica per query with a round-robin or least-connections strategy. A single shared pool makes it impossible to fail over one replica without affecting the others, and it hides which replica a query landed on when you debug a stale-read report. Log the target node for every query at debug level, so a user who reports stale data can be traced to the specific replica and its lag at that moment.

On a primary failure, promote a replica and redirect the primary pool to the new primary. During the promotion, writes fail; accept that window and queue writes in a durable buffer if the application cannot tolerate write loss. After promotion, the old primary is out of sync and must not rejoin as a replica until rebuilt from the new primary. Automate the rebuild, because a manual rebuild under load is slow and error-prone. Test the failover regularly in staging, because an untested failover will fail the first time you need it in production.

Conclusion

Read replicas scale reads but need a router that handles health, lag, and consistency. Route writes to the primary, reads to a healthy replica, and critical reads after writes back to the primary. Monitor lag, test failover, and keep the critical window short. The result is read scaling without stale data or downtime when a replica fails.

Sources: PostgreSQL replication, read-your-writes.

FAQ

When should a read go to the primary instead of a replica?
After a write by the same user, route the next read to the primary to avoid stale data from replication lag; use a session-level sticky flag.
How many replicas do I need?
Start with one or two; add more when read load saturates the replicas. Each replica adds cost and operational complexity.
How do I monitor replica lag?
Query pg_stat_replication for Postgres or SHOW REPLICA STATUS for MySQL; alert when lag exceeds a threshold.

Related Examples