14. Replication
1
The picture to keep in your head2
14.1 Why keep copies of the same data?3
14.2 How does leader-follower replication work?4
14.3 Should the leader wait for followers before confirming a write?5
14.4 What is replication lag, and why does it happen?6
14.5 How do you stop lag from confusing users?7
14.6 How do you use read replicas in practice?8
14.7 What happens when the leader fails?9
14.8 What is split brain, and how is a leader safely chosen?10
14.9 When would you have more than one leader?11
14.10 How does leaderless replication work, and what are quorums?12
Memory card and where the analogy breaks13
Practice: five levels14
Interview questions15
Solutions16
Sources17
Code lab14. Replication
14.7 What happens when the leader fails?
3 min read+10 XP
When the leader dies
At the bank: Head office goes silent. Someone has to notice, pick the branch with the most up-to-date copies, announce "this branch is now head office", and make sure every courier now goes there.
In the system: Failover turns a follower into the new leader. Steps, whether automatic or by hand:
- Detect the failure: the leader stops answering health checks or heartbeats for some timeout. Too short a timeout causes needless failovers during a brief slowdown; too long means a longer outage.
- Choose a new leader: usually the follower that's most up to date, to lose the least data.
- Promote it, and reconfigure everything: the other followers now replicate from it, and apps send writes to it (by updating a DNS name, a virtual IP, or a proxy's configuration).
- Deal with the old leader: if it comes back, it must not think it's still in charge (14.8).
What can go wrong:
- With asynchronous replication, writes the old leader confirmed but never shipped are lost (14.3).
- If those lost rows had IDs that the new leader reuses, other systems (a cache, an email already sent) may now point at the wrong data.
- Failover takes time: typically seconds to a minute or two. Apps need retries with backoff (Chapter 29).
Tools like Patroni (PostgreSQL) or Orchestrator (MySQL), and managed cloud databases, automate this.
Memory code: "Notice, choose the freshest, promote, redirect, and silence the old boss."