← Back to SQL, page 17

sql-0325 · Medium mid

How do read replicas help scale a database, and what problems does replication lag cause?

Replicas copy changes from the primary and serve read queries, which spreads read load and adds failover options. Asynchronous replicas lag behind, so a user who just wrote data may not see it on a replica. Route read-your-own-writes requests to the primary, or wait until the replica has caught up to the write's position.

Full answer

Typical setup: one primary accepts writes; several replicas apply the primary's write-ahead log and answer SELECTs. Reports, search pages and analytics move to replicas.

Lag problems:

  • Read-your-writes: a user saves a profile and the next page, served by a replica, shows old data.
  • Monotonic reads: two requests hitting different replicas can make data appear to go backwards.
  • Long queries on a PostgreSQL replica can conflict with cleanup on the primary and get cancelled, or delay replay if configured to wait.

Mitigations:

  • Send a user's reads to the primary for a short time after they write (session stickiness).
  • Track the primary's log position after a write and read from a replica only once it has replayed past it.
  • Use synchronous replication for data that must never be lost on failover, accepting slower writes.

Replicas do not help write throughput; that needs partitioning, sharding or a lighter write path.

Key points

  • Replicas scale reads, not writes
  • Asynchronous lag breaks read-your-writes
  • Route recent writers to the primary or wait for replay
  • Synchronous replication trades latency for safety

Common mistakes

  • Sending every read to replicas without considering lag
  • Expecting replicas to increase write capacity

Follow-ups

  • When is synchronous replication worth its write latency?
  • How would you handle failover?

Tips

  • Give the read-your-writes example