Leader-follower replication and replication lag
MediumDatabasesReplicationScaling
How does leader-follower replication work, and what problems does replication lag cause?
TL;DR
In leader-follower (primary-replica) replication, all writes go to the leader, which streams its change log to followers. Followers serve reads, which scales read traffic and gives you a hot standby for failover. Replication is usually asynchronous: the leader doesn't wait for followers, so writes stay fast, but followers can be behind (replication lag). Reading from a lagging follower causes stale reads, like a user not seeing the comment they just posted.
Key points
- Synchronous replication waits for at least one follower before confirming a write: no data loss on failover, but slower writes. Many setups use one synchronous follower and the rest asynchronous.
- Lag problems and fixes:
- Read-your-writes: read from the leader for a short time after a user writes, or track the write's log position.
- Monotonic reads: pin a user to the same replica so they don't jump between replicas at different lag.
- Failover: promote a follower when the leader dies. Risks include losing unreplicated writes and split brain (two leaders). Use a consensus-based tool (Patroni, managed RDS or Cloud SQL) with fencing.
- Multi-leader and leaderless (Dynamo-style quorum) replication allow writes in several places but need conflict resolution.
- Replication isn't a backup: a bad
DELETEreplicates instantly. Keep point-in-time backups too.
Example
text
writes ──► Leader ──WAL stream──► Follower 1 ──► reads
└───────────► Follower 2 ──► readsCommon follow-ups
- How do you monitor lag? Compare log positions (
pg_stat_replicationin PostgreSQL, or seconds behind the primary in MySQL), and alert when lag passes a threshold. - Does adding replicas scale writes? No. Every write still goes through one leader; scaling writes needs sharding.
What interviewers look for
Tip
Writes to the leader, reads from followers, async lag and its user-visible symptoms, and a concrete fix such as read-your-writes.
- Red flag: "replicas are our backup."