Replication: Leader, Follower, Failover

What if the DB dies? Primary-replica setups, replication lag, failover, and the split-brain danger.

Intermediate7 min read
Language
Theme
Primaryall writesReplica 1readsReplica 2readssync?asyncReplication lagread primary after own writesFailover + split-brainpromote replica via quorumAsync = fast but small loss window. Sync = safe but slower writes
Key idea at a glance
INTERACTIVE

Playground: replication lag

Writes land on the primary instantly, replicas catch up after a lag you control. Read from a replica during the lag and you get stale data. That is eventual consistency.

Primary
v = 0
→
→
Replica 1
v = 0
Replica 2
v = 0

Replication: why your database has clones

Replication keeps copies of the same data on multiple servers. It buys three things: read scaling (replicas answer reads, the primary only writes), availability (primary dies, a replica is promoted), and proximity (replicas in other regions serve local users faster). The shape is almost always single-leader: one primary accepts writes; followers apply the same changes in the same order from the primary's log (WAL/binlog/oplog).

Sync vs async: the fundamental choice

  • Synchronous: a write is confirmed only after a replica has it too. Survives primary death with zero loss, but every write is as slow as the slowest replica, and a dead replica blocks writes.
  • Asynchronous: primary confirms immediately; replicas catch up behind. Fast and resilient, but a primary crash can lose the last few seconds of writes.
  • Semi-sync (common compromise): one sync replica, the rest async: bounded staleness, bounded risk.

Replication lag and read-your-writes

Async replicas lag: milliseconds normally, seconds or worse under load. The user who just updated their profile and reads from a lagging replica sees the old value. Fixes: read-your-writes (route the writer's own reads to the primary for a window, or wait for the replica to pass the write's log position), pin critical reads (balances) to the primary always, and monitor lag as a first-class metric.

Failover: the dangerous 60 seconds

  1. Detect: health checks and heartbeats decide the primary is dead (too eager = flapping; too slow = long outage).
  2. Elect: remaining nodes choose a new primary. This needs consensus (a majority must agree), or a network partition can produce split-brain: two primaries accepting writes, diverging data, reconciliation nightmare.
  3. Repoint: clients and the old primary (when it returns, demoted) switch to the new leader. DNS, a proxy (ProxySQL) or a discovery service (etcd/ZooKeeper) handles this.

Multi-leader and leaderless (know they exist)

Multi-leader: primaries in multiple regions accept local writes and sync to each other: great regional latency, but write conflicts need resolution (last-write-wins, CRDTs, app logic). Leaderless (Dynamo-style): no primary; clients write to W of N replicas and read from R of N (W + R > N for consistency). Cassandra/DynamoDB. Maximum availability, eventual consistency, conflict handling pushed to reads.

Worked example: Postgres for a growing SaaS

Primary in the main region; 2 async read replicas for dashboards and search indexing; 1 semi-sync replica as the failover candidate (managed RDS promotes it in ~60-120s); pgbouncer pooling; lag alerting at 5s; writes always to the primary; "my own recent writes" reads pinned to the primary for 10s after a write.

Common interview traps

  • "Add replicas" without saying sync or async and what that implies.
  • Failover described in one line with no detection, election or split-brain story.
  • Sending all reads to replicas including ones that must be fresh.

Interview Q&A

Q: After a failover, a user says their last order vanished. Explain.
A: Classic async loss window: the order was written to the old primary after its last replication to the promoted replica. Mitigations: semi-sync on one replica, or on failover check the new primary's log position vs clients' last confirmed writes and reconcile (order systems usually re-verify with the payment gateway anyway).

Q: How do replicas stay in sync, concretely?
A: The primary appends every change to a write-ahead log; replicas stream and replay it in order, tracking their replay position (LSN/GTID). Lag = primary position minus replica position.

Key takeaways

Interview pointer

Say SQL and the follow-up is 'how does it scale?' Answer in order: indexes, cache, read replicas, and only then sharding. With replicas, always mention lag and failover.