← 中文资源

简体中文版本

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.

阅读英文原文

引言

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. 本文将逐步拆解设计与实现,帮助你在生产环境中安全落地。

问题

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. 理解问题的全貌是设计正确方案的前提。

设计决策

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); }
}

实现

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); }
  }
}

测试边界

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. 测试应覆盖正常路径与异常路径,确保系统在边界条件下行为正确。

常见陷阱

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. 避开这些陷阱可以减少生产事故。

结论

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.