Book a 30-min callBook a call

Database replication and read replicas: lag, consistency and failover

How database replication works: streaming vs logical, sync vs async and quorum commit, measuring lag, read-your-writes routing, failover and split brain.

A primary database box streaming log arrows to two replica boxes, a router circle sending a write arrow to the primary and read arrows to the replicas, and a small clock on one arrow for lag.
Written by
BYD Tech
Published
Topic
Deep dives
Reading time
20 min read

Questions people ask

Is a read replica the same as a backup?

No. A replica copies every change within seconds or less, including an accidental delete or a bad migration, so it cannot take you back to before the mistake. Keep backups with point-in-time recovery as well; replicas cover hardware failure and read load, backups cover history.

How much replication lag is normal?

For PostgreSQL streaming replication on a healthy network, the documentation says the delay is typically under one second. Lag grows with heavy write bursts, slow standby disks, long queries that hold up replay, and distance between regions. Measure replay_lag and the byte gap in pg_stat_replication, and alert on sustained growth rather than single spikes.

Should I turn on synchronous replication?

Use it when losing an acknowledged commit is unacceptable, and plan for its costs: every commit waits at least one round trip to a standby, and commits stop completing if the required standbys are unavailable. Name more candidates than you wait for, for example ANY 1 (s1, s2), and raise synchronous_commit only for the transactions that need it.

Can I write to a read replica?

Not to a PostgreSQL hot standby: it is strictly read-only, and an insert fails with an error about a read-only transaction. A logical replication subscriber is an ordinary database and accepts writes, but writes to replicated tables can conflict with incoming changes, so most teams treat subscribers as read-only too.

How do I stop users from seeing stale data after they save something?

Either send that user's reads to the primary for a short window after a write, or store the write's log position (the LSN in PostgreSQL, a GTID set in MySQL) and only read from a replica that has applied it. Updating the stored position after every read also keeps a user's view from going backward between refreshes.

Building something like this?