AlgoViz

Implementing database replication

hard 30 min

Running 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

0:00 / 3:48

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

  1. 1979

    David Gifford publishes weighted voting: give copies votes, and make read and write quorums overlap.

  2. 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.

  3. 2014

    Diego Ongaro and John Ousterhout publish Raft, a consensus algorithm designed to be understandable. Many failover tools build on it.

  4. 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.

Step 1 of 3

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?

When the lead lamp goes dark
Log 8Log 8Log 7

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. 1

    Prepare the primary

    Allow replication connections, create a login for replication only, keep enough log.

  2. 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. 3

    Take a base backup

    A consistent copy of the whole server while it keeps working.

  4. 4

    Start the replica

    It replays from the start of the backup and then streams.

  5. 5

    Wait until it has caught up

    Only now may it serve reads or count for failover.

  6. 6

    Rehearse

    Promote it on purpose, measure the time, switch back.

A cluster that can fail over by itself

A proxy sends the applications' queries to the current primary. The primary in zone A streams to replica 1 in zone B and replica 2 in zone C. A group of coordinators with three votes holds one leader lock, which the primary renews and the replicas watch.
Dashed orange is replication, blue is the leader lock. Three zones, three votes. The proxy follows the leader lock, so applications do not need to know which node leads.

Failover

Automatic, manual and planned

KindWho decidesUse it forDanger
AutomaticSoftware, by timeout and voteShort interruptions, nightsWrong decision in a network fault
ManualA person, with a runbookFar regions, where a wrong failover loses dataSlow, and stress causes mistakes
Planned (switchover)A person, while all is wellUpgrades and maintenanceLittle: wait for zero lag, then swap roles
A common split is automatic inside one region and manual between regions.

Automatic failover

The six stages

  1. 1

    Initial state

    All nodes are healthy and the primary serves requests.

  2. 2

    Primary failure

    The primary crashes, hangs or can no longer be reached.

  3. 3

    Failure detection

    Heartbeats are missed for longer than the timeout, as seen by a majority.

  4. 4

    Leader election

    The voters choose the follower with the newest log.

  5. 5

    Promotion

    The old leader is fenced, then the chosen replica becomes primary with a higher term.

  6. 6

    Reconfiguration

    Other replicas follow the new primary, clients reconnect, and the old node is marked for recovery.

How long is the interruption?

t=tdetect+tvote+tpromote+treconnect10+1+4+5=20 st = t_{\text{detect}} + t_{\text{vote}} + t_{\text{promote}} + t_{\text{reconnect}} \qquad 10 + 1 + 4 + 5 = 20 \text{ s}
Example values. Detection usually dominates. A shorter timeout shortens the outage and causes more failovers that were not needed. MongoDB, for example, uses a 10 second election timeout by default and says a new primary is normally elected in a median of no more than 12 seconds.

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

Without fencing both sides accept writes, and nobody can merge them automatically.

Four layers of protection

LayerHowStops
Majority voteA leader needs more than half of the votesTwo elected leaders in the same term
LeaseThe leader must renew a lock, and steps down by itself when it cannotA cut-off leader that goes on for ever
Fencing (STONITH)Cut power, network or disk of the old nodeA leader that does not notice it was replaced
Term numberEvery write carries the leader's term and older terms are refusedLate messages from a paused leader
A vote alone is not enough: the old leader may not know the result. PostgreSQL's documentation says that the old primary must be told it is no longer the primary, and names STONITH.

Explaining fencing

  1. Interviewer

    The primary stopped answering. Why not simply promote the replica?

  2. 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.

  3. Interviewer

    And if you cannot reach it to fence it?

  4. 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

W+R>N;⇒;overlap≥W+R−NN=3,;W=2,;R=2:;2+2−3=1W + R > N ;\Rightarrow; \text{overlap} \ge W + R - N \qquad N=3,; W=2,; R=2:; 2 + 2 - 3 = 1
Two groups that together are larger than N cannot be disjoint. At least one node is in both.

Settings for N = 3 and N = 5

NWRW + R > NWrites survive losingReads survive losing
3224 > 3 yes1 node1 node
3314 > 3 yes0 nodes2 nodes
3134 > 3 yes2 nodes0 nodes
3112 > 3 no2 nodes2 nodes, may be old
5336 > 5 yes2 nodes2 nodes
Majority both ways is the balanced choice. To survive f failures with majorities you need 2f + 1 nodes.

A write and a read that meet

Monitoring

What to watch

Four signals and an example set of thresholds

SignalWhyWarningCritical
Replication lagOld reads, and data lost if you fail over nowOver 5 sOver 30 s
Log position differenceWorks even when nobody writesOver 100 MBOver 1 GB
Slot and log retentionA dead replica's slot can fill the primary's disk20% of the disk50% of the disk
Connection stateA disconnected replica does not countReconnectingDisconnected
Round trip between nodesExplains lag and slow commitsTwice normalTen times normal
Examples. Derive yours from the product: the critical lag must be below the data loss you have promised.

A replica is behind: what now?

Take a lagging replica out of the read pool first. Then look for the reason.

Recovery 1

A replica failed

  1. 1

    Take it out of service

    Stop sending it reads, then stop it.

  2. 2

    Find its position

    What is the last log position it replayed?

  3. 3

    Is that log still available?

    On the primary or in the archive. If not, rebuild from a fresh base backup.

  4. 4

    Reconnect and catch up

    Compare replay rate with write rate first.

  5. 5

    Verify

    Check row counts and checksums on samples, then put it back.

Recovery 2

The old leader returns

  1. 1

    Confirm that failover is complete

    There must be exactly one leader. The old node must stay fenced until you know.

  2. 2

    Save what is different

    Copy the writes that only the old leader has before you remove them.

  3. 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. 4

    Join as a replica

    Never as a leader. Follow the new one and catch up.

  5. 5

    Switch back only if needed

    As a planned switchover, at a quiet time.

How much was lost?

lost writes≈lag at the crash×write rate=2 s×500/s=1,000\text{lost writes} \approx \text{lag at the crash} \times \text{write rate} = 2 \text{ s} \times 500/\text{s} = 1{,}000
With asynchronous replication these writes were confirmed to clients and exist only on the old leader. A synchronous standby makes this zero, if that standby is the one promoted.

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.

Sources