Implementing database replication
hard 30 minRunning replication in production: how to set up a replica, detect that the leader is gone, choose and promote a new one without ending up with two, use quorums, watch lag and slots, and bring the failed node back safely.
See it run
Failover, quorums, monitoring and recovery, step by step.
Operations
Automatic failover
The primary dies. Two live nodes of three decide, fence and promote.
Step 1 of 7
Initial state
Primary serves requests
All three are healthy. Logs: 8, 8 and 7.
Step 1: Initial state
if missed_heartbeats(primary) > TIMEOUT: if not majority_agrees(): return # do nothing alone best = max(live_replicas, key=lambda r: r.position) fence(primary) # first best.promote(term + 1) # then others.follow(best) proxy.point_to(best)- Time
- About 20 s
- At risk
- Unreplicated writes
- By hand at night
- many minutes
Say fence before promote. It is the most common missing word.
In the real world
The same implementing database replication doing real jobs. Pick one and step through it.
A replica was switched off and forgotten.
Step 1 of 3
Normal
- Primary disk
- 40%
Healthy
The slot keeps the log until the replica has it. That takes a moment.
Step 1: Normal
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Promoting without fencing
criticalThe old primary may still take writes. You get two histories that cannot be merged automatically.
Wrongif not ping(primary): replica.promote()Rightif majority_says_dead(primary): fence(primary) replica.promote(term + 1)Choosing by priority
criticalThe highest priority may be far behind. Every missing record was confirmed to somebody.
Wrongmax(replicas, key=lambda r: r.priority)Rightmax(live, key=lambda r: (r.position, r.priority))A slot without a limit
majorA replica that never returns keeps log on the primary until the disk is full.
Wrongcreate_slot("replica_9") # and forget itRightmax_slot_wal_keep_size = "50GB"alert_if(retained_log > "20GB")Counting one failure as total failure
majorA quorum write must count the successes. One exception does not mean the write failed.
Wrongawait all(writes) # throws if one failsRightok = count_success(await settle(writes))if ok < W: raise NoQuorum
Interview tips
How to explain it
- Detect, decide, fence, promote, redirect.
- Newest log wins.
- Outage is detection plus vote plus promotion plus reconnect.
Memory trick: FQMR
- Failover.
- Quorums.
- Monitoring.
- Recovery.
Safe defaults
- Three voters in three zones.
- A lease on the leader.
- Automatic inside a region, a person between regions.
Stop and think when
- The best replica is too far behind.
- You cannot fence the old node.
- Only one side of the network answers.