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.
Video lesson · Chapter 1 of 5
The primary goes quiet at position eight
Failover without two leaders, in 90 seconds
1:30Reel coming soon
Theory
Read or listen first. About 2 min.
What it is
Implementing replication means making copies useful when something breaks. It has four parts, easy to remember as FQMR: Failover, Quorums, Monitoring and Recovery.
Failover replaces a lost leader. Quorums make sure that only one answer can win, whether the question is who leads or which value is newest. Monitoring tells you, before the failure, whether a replica is good enough to take over. Recovery brings the failed node back without bringing its old mistakes back with it.
Why it exists
A replica that nobody can promote is only a warm disk. Most of the damage in real incidents does not come from the first failure. It comes from what the system or a tired person does next: promoting the wrong node, leaving two leaders, or wiping the wrong server.
The central difficulty is that no node can tell a dead leader from a leader it cannot reach. Every technique here, from timeouts and votes to fencing, is a way to act safely without knowing which of the two it is.
A short history
1979
David Gifford publishes weighted voting: give copies votes, and make read and write quorums overlap.
2007
The Dynamo paper describes quorum-like reads and writes with N, R and W as settings, and hinted handoff for nodes that are down.
2014
Diego Ongaro and John Ousterhout publish Raft, a consensus algorithm designed to be understandable. Many failover tools build on it.
2018
On 21 October, 43 seconds without a network link make GitHub's automation fail over across the country while both sides hold writes the other lacks. Service is degraded for 24 hours and 11 minutes.
Words to know
- Heartbeat
- A small regular message that says: I am alive.
- Split brain
- Two nodes both believe that they are the leader and accept writes.
- Fencing
- Making sure the old leader cannot do damage, for example by cutting its power, network or disk.
- STONITH
- Shoot The Other Node In The Head: fencing by switching the node off.
- Term (epoch)
- A number that grows with every new leader, so that messages from an old leader can be refused.
- Replication slot
- A marker on the primary that keeps the log until a given replica has received it.
- RPO and RTO
- How much recent data you may lose, and how long you may be down.
- Timeline divergence
- The old leader has writes that the new history does not contain.
How it works
Step through the idea, or press Play.
Detect. Missed heartbeats, agreed by a majority
Understand it
Start here
The relay of lighthouses
Three lighthouse keepers stand along a coast. The first one sends signals with its lamp and writes each one in a log. The other two repeat the signal and write it in theirs. What happens when the first lamp goes dark?
The order in the fourth picture matters most: first make sure that the old lamp cannot shine, then raise the flag.
FQMR
Failover
A replica is promoted when the leader fails.
Quorums
The smallest number of nodes that must agree.
Monitoring
Lag, health and log retention, with alerts.
Recovery
Bringing failed nodes back safely.
Set it up
From one server to a healthy replica
- 1
Prepare the primary
Allow replication connections, create a login for replication only, keep enough log.
- 2
Create a replication slot
So the primary keeps the log the new replica will need. Set a limit on how much it may keep.
- 3
Take a base backup
A consistent copy of the whole server while it keeps working.
- 4
Start the replica
It replays from the start of the backup and then streams.
- 5
Wait until it has caught up
Only now may it serve reads or count for failover.
- 6
Rehearse
Promote it on purpose, measure the time, switch back.
A cluster that can fail over by itself
Failover
Automatic, manual and planned
| Kind | Who decides | Use it for | Danger |
|---|---|---|---|
| Automatic | Software, by timeout and vote | Short interruptions, nights | Wrong decision in a network fault |
| Manual | A person, with a runbook | Far regions, where a wrong failover loses data | Slow, and stress causes mistakes |
| Planned (switchover) | A person, while all is well | Upgrades and maintenance | Little: wait for zero lag, then swap roles |
Automatic failover
The six stages
- 1
Initial state
All nodes are healthy and the primary serves requests.
- 2
Primary failure
The primary crashes, hangs or can no longer be reached.
- 3
Failure detection
Heartbeats are missed for longer than the timeout, as seen by a majority.
- 4
Leader election
The voters choose the follower with the newest log.
- 5
Promotion
The old leader is fenced, then the chosen replica becomes primary with a higher term.
- 6
Reconfiguration
Other replicas follow the new primary, clients reconnect, and the old node is marked for recovery.
How long is the interruption?
The worst case
Split brain and how to prevent it
The old leader may not be dead. It may be slow, paused or cut off, and still accept writes from clients that can reach it. If another node is promoted, there are two leaders and two histories.
A cut network
Four layers of protection
| Layer | How | Stops |
|---|---|---|
| Majority vote | A leader needs more than half of the votes | Two elected leaders in the same term |
| Lease | The leader must renew a lock, and steps down by itself when it cannot | A cut-off leader that goes on for ever |
| Fencing (STONITH) | Cut power, network or disk of the old node | A leader that does not notice it was replaced |
| Term number | Every write carries the leader's term and older terms are refused | Late messages from a paused leader |
Explaining fencing
Interviewer
The primary stopped answering. Why not simply promote the replica?
You
Because not answering is not the same as dead. If it is only cut off, some clients may still write to it. I need a majority to agree, then I fence it: its lease expires so it steps down, and the proxy or the hypervisor blocks it. After that I promote.
Interviewer
And if you cannot reach it to fence it?
You
Then I wait until its lease has certainly run out, which costs a few seconds, or I use a fence that does not need its help, such as power or storage.
Quorums
Why majorities work
With N copies, a write waits for W of them and a read asks R. If the two groups must overlap, a read meets at least one copy that has the newest completed write.
The overlap rule
Settings for N = 3 and N = 5
| N | W | R | W + R > N | Writes survive losing | Reads survive losing |
|---|---|---|---|---|---|
| 3 | 2 | 2 | 4 > 3 yes | 1 node | 1 node |
| 3 | 3 | 1 | 4 > 3 yes | 0 nodes | 2 nodes |
| 3 | 1 | 3 | 4 > 3 yes | 2 nodes | 0 nodes |
| 3 | 1 | 1 | 2 > 3 no | 2 nodes | 2 nodes, may be old |
| 5 | 3 | 3 | 6 > 5 yes | 2 nodes | 2 nodes |
A write and a read that meet
Monitoring
What to watch
Four signals and an example set of thresholds
| Signal | Why | Warning | Critical |
|---|---|---|---|
| Replication lag | Old reads, and data lost if you fail over now | Over 5 s | Over 30 s |
| Log position difference | Works even when nobody writes | Over 100 MB | Over 1 GB |
| Slot and log retention | A dead replica's slot can fill the primary's disk | 20% of the disk | 50% of the disk |
| Connection state | A disconnected replica does not count | Reconnecting | Disconnected |
| Round trip between nodes | Explains lag and slow commits | Twice normal | Ten times normal |
A replica is behind: what now?
Recovery 1
A replica failed
- 1
Take it out of service
Stop sending it reads, then stop it.
- 2
Find its position
What is the last log position it replayed?
- 3
Is that log still available?
On the primary or in the archive. If not, rebuild from a fresh base backup.
- 4
Reconnect and catch up
Compare replay rate with write rate first.
- 5
Verify
Check row counts and checksums on samples, then put it back.
Recovery 2
The old leader returns
- 1
Confirm that failover is complete
There must be exactly one leader. The old node must stay fenced until you know.
- 2
Save what is different
Copy the writes that only the old leader has before you remove them.
- 3
Rewind or rebuild
pg_rewind brings a diverged PostgreSQL node back to the point where the histories split. Otherwise start from a base backup.
- 4
Join as a replica
Never as a leader. Follow the new one and catch up.
- 5
Switch back only if needed
As a planned switchover, at a quiet time.
How much was lost?
Practise
Drills and dangers
Do
- Rehearse failover every few months, in working hours
- Measure detection, promotion and reconnection separately
- Keep a runbook with exact commands
- Put the prompt and colour of each server's name where nobody can mix them up
- Keep restore-tested backups
Do not
- Fail over automatically across regions without counting the loss
- Use two voters
- Promote the replica that is easiest to reach
- Let clients cache the old address for ever
- Count on a standby nobody has tested
How much availability this buys, and how to state it as a target, is in high availability.
Summary
The whole topic in one minute.
Failover is detect, decide, fence, promote, redirect. The decision needs a majority, the candidate must have the newest log, and the old leader must be stopped before the new one writes.
Quorums work because any two majorities share a node. R + W > N makes a read meet the newest completed write, but it does not by itself make a system linearizable. Watch lag, log retention and connection state, and rejoin a failed leader only after its diverged writes have been dealt with.
- FQMR: Failover, Quorums, Monitoring, Recovery.
- Detect, decide by majority, fence, promote, redirect. Fence before you promote.
- The winner is the replica with the newest log.
- Majorities overlap, so N = 2f + 1 survives f failures. W + R > N makes reads meet writes.
- Bring the old leader back as a replica, after saving and rewinding what diverged.