ealeng

Episode 44 of 55 · Failover and recovery

Split brain and fencing: the old primary said yes about 1,200 times after its replacement, and fencing stopped that but not the loss

The primary database was cut off from its replica and from etcd, the shared store that holds the leader lock, for 12 seconds, while one client kept using its old address. Without fencing, the old primary kept saying yes to that client, about 1,200 times per run after the replica had taken over, and when the network healed it was still a primary: rebuilding it threw away 2,814 to 2,916 acknowledged writes per run. With fencing, the old primary made itself read-only 1.2 seconds after its last renewal, and it said yes zero times after the replacement, but it still lost 195 to 212 writes per run that it had accepted before the fence.

Lab 18 · Failure, Failover and Recovery9 min read
Video transcript7:59

0:00Cold open

0:01

I cut my main database off from its copy, and from the service that records who’s leader, for twelve seconds. The copy took over, as designed. But one client still had the old address.

0:14

The old database kept telling that client “yes, saved”: about twelve hundred times per run, after it had been replaced.

0:24

When I made it a copy again, every write it had taken since the cut was thrown away. Over twenty-eight hundred per run.

0:33

With one setting on, it said yes zero times after the replacement. And it still lost about two hundred.

0:41

So how does a database keep saying yes after it’s been replaced? And why doesn’t the fix save everything?

0:49Intro

0:51

Hands-on system design, part forty-four.

0:54

Today: split brain, two databases that both think they’re in charge, and fencing: a primary stepping down on its own, before it can be replaced.

1:05Meet Lucía

1:07

I’m Lucía, a platform engineer, and last time I broke our database on purpose, to see how fast a copy takes over.

1:15

Only one database may take writes. That’s the primary. It sends every change to a replica, a copy, just after telling the client yes.

1:26

If the primary dies, the replica takes over. Something has to decide when.

1:32

Here that’s etcd, a small shared store. It holds one line: “node one is the primary”. The line lasts two seconds: that’s a lease. The primary renews it every quarter second. If the renewals stop, the line expires, and the replica takes it.

1:49

Think of a shop with one till. The manager may sell only while head office renews a two-second permit. No call, and head office gives the permit to the deputy.

2:0101 · What you need

2:03

To run it yourself: Docker, for two Postgres databases, each with a small controller that follows those rules, plus etcd, and a proxy that can cut a network link on command.

2:16

The quick tests check every branch of the takeover rule, and the loss formulas, without Docker, in a couple of seconds. No cloud, nothing to pay for.

2:2802 · The test

2:29

The test: I cut the primary off from etcd and from its replica, for twelve seconds. It’s still alive, and clients can still reach it. It’s just alone. That’s a network partition.

2:42

Two clients write a hundred rows a second each. Client A asks etcd which node is the primary. But like many clients, it asks again only after one of its writes fails.

2:55

Client B is pinned to the old primary’s address, like an app that saved the address once and never looks again.

3:04

Afterwards I check: is every “yes” still in the database that’s left? Five runs without fencing, five with it.

3:1303 · No fencing

3:15

First, without fencing. Between two and three seconds after the cut, the lease had expired, and the replica promoted itself. Now there’s a new primary.

3:26

How many writes do you think the old primary said yes to, after that?

3:33

About twelve hundred per run, counting client B only. It couldn’t hear it had been replaced. And even after the cut ended and it could hear, it kept going.

3:44

And client A? Not one of its writes failed, so it never asked etcd again. Both clients stayed on the old primary. The new one got none of their writes.

3:5604 · Rejoining

3:57

When the cut ended, the old primary was still a primary. Two tills selling the same stock: that’s split brain. To fix it, I rebuilt it as a copy of the new one. Postgres can’t merge two histories, so rebuilding it threw away everything only it had.

4:14

The test wrote two hundred a second for about fourteen seconds after the cut began: the twelve-second cut, plus the two seconds the test kept writing after it ended. About twenty-eight hundred. Run it longer, and the loss keeps growing.

4:30

Measured: from twenty-eight hundred to just over twenty-nine hundred per run. Writes a client had been told were saved, gone.

4:4005 · Fencing

4:42

The fix is fencing: the manager closing their own till before the permit can run out. The cut-off primary can’t hear etcd, so it can’t know when it’s replaced. But it knows when it last renewed its lease.

4:56

So it fences itself at six tenths of the lease: one point two seconds after its last renewal, it stops itself, before anyone else can be promoted.

5:07

The lease expires at two seconds, and the replica takes over a moment later.

5:13

In between, about a second with no primary at all. Last time, clients measured that gap. That’s the price.

5:2206 · In code

5:24

In code, the controller asks this every quarter second. If I’m the primary, and it’s been more than six tenths of the lease since I renewed, fence.

5:34

And this line: once it hears someone else is primary, it should fence. With fencing off, it just kept going.

5:42

To fence, it makes new writes read-only by default, and cuts off every client connection. Client B’s next write is refused.

5:5307 · With fencing

5:54

With fencing on: client B got zero yeses from the old primary after the replacement, in all five runs.

6:03

Client B was refused from the fence on. Client A’s writes failed, so it asked etcd again, and the rest of its writes most likely landed on the new primary.

6:15

But each run still lost about two hundred writes.

6:19

Those are the writes it took in the second between the cut and its fence: two hundred a second. The replica never got them. Last time, the same cut lost a similar number.

6:3208 · Assumptions

6:34

One thing fencing assumes, which I didn’t test, and one limit.

6:39

It trusts the old primary’s clock. If that clock ran slow, it would fence late, and for a moment there could be two primaries again.

6:48

A stronger fix is a fencing token: every leader gets a number, and the storage refuses any write from an older number.

6:57

Losing nothing needs every write copied before the yes. Last time, with the only copy cut off, that stopped all writes.

7:07Back to Lucía

7:09

So, three lessons.

7:12

Split brain needs no bug. A partition, and a client that kept the old address, is enough.

7:19

Fence yourself before your lease can run out. You pay for it with about a second of no primary.

7:26

And fencing stops two primaries, not the loss. The writes before the fence were still gone.

7:33

Next time: a slow service that takes down parts of the system that never call it, and a delete without a where clause.

7:42

For today: close your own till first.Lucía: Close your own till first.

7:46Summary

7:47

A partition and a client with an old address make two primaries. Fence before your lease runs out, and expect to lose what it took before the fence.

Key takeaways

  • ✓Split brain needs no bug: when the primary was cut off and one client still pointed at its address, the old primary kept saying yes to that client, 1,212 to 1,231 times per run, after the replica had been promoted and the lock had moved.
  • ✓Rebuilding the old primary as a copy of the new one, the only way back to one history, threw away every acknowledged write only it had: 2,814 to 2,916 per run without fencing, from both clients together.
  • ✓Self-fencing at 0.6 × the 2-second lease makes the old primary read-only 1.2 seconds after its last renewal, before the lease can run out, and with it on the pinned client got zero yeses after the promotion in all five runs.
  • ✓Fencing stops two primaries but not the loss: 195 to 212 acknowledged writes per run were still gone, because they were accepted in the window before the fence, when the replica could no longer receive them.
  • ✓Self-fencing trusts the old primary's clock, which this lab did not test; a fencing token, a number that only goes up and that the storage checks on every write, does not depend on clocks, and building one is an exercise in the lab rather than something measured here.

The primary database was cut off from its replica and from etcd for 12 seconds. The replica took over, as designed. But one client still had the old address, and the old primary kept saying yes to it, about 1,200 times per run, after it had been replaced. Fencing, where the old primary stops itself first, stopped the second primary. It did not stop the loss: about 200 writes per run were still gone. This chapter takes apart what each part of that means, and why the fix is partial.

The examples come from Lab 18 (Failure, Failover and Recovery) of the system design labs, script 02_split_brain.py, and the failover controller's rule in election.py. The lab runs two Postgres 17 nodes, node1 and node2, each with a small controller that owns its database. They share an etcd 3.5 cluster, which holds the leader key on a lease. Toxiproxy, a proxy that can cut a network link on command, sits between each node and etcd, and between the two nodes. Everything ran in Docker on one Apple M4 Max laptop. The lab's README puts the whole lab at about 70 minutes; this exercise takes about 5.

The setup: a leader key on a lease

Only one of the two databases may accept writes. That is the primary. It sends each change to the other node, the replica, just after it says yes to the client. The primary holds a key in etcd, named /pg/leader, attached to a lease. A lease is a timer: the key disappears when the lease runs out, unless the holder renews it. The lab's TTL (time to live) is 2 seconds, and the controller renews every quarter-second.

When the primary stops renewing, the lease runs out after 2 seconds, the key is free, and the replica takes it and promotes itself. The controller's rule for this is short. A primary that sees another node holding the key fences if fencing is on. A primary that cannot reach etcd fences itself at 0.6 × the TTL after its last renewal. A replica takes the key when nobody holds it.

The test

The test cuts the primary off from etcd and from its replica for 12 seconds. It is still running, and clients can still reach it. It has only lost its links to the two things that decide who is primary and to its copy. That is a network partition.

Two clients write 100 rows a second each, for 20 seconds:

  • Client A finds the primary by asking etcd. Like many clients, it asks again only after one of its writes fails.
  • Client B is pinned to the old primary's address, like an application that looked the address up once and cached it.

Each run then checks what survived. The rows each node holds are compared after the partition heals, and before the old primary is rebuilt. The lab ran five runs with fencing off and five with it on.

Try it · A partitioned primary and a pinned clientrecorded run, 02_split_brain.py

Nothing stops the cut-off primary. After the replica promotes, the old primary keeps saying yes to the pinned client, and after the heal it is still a primary.

Seconds after the cut began (the cut lasts 12 s)
cut
lease ends (2 s)
promoted (median 2.37 s)

The fence and lease marks come from the controller’s settings; the promotion mark is the recorded median.

Yes to pinned client after promotion
6,122
Acked writes lost on re-clone
14,290
Old primary after heal
primary
RunPromoted afterYes after promotionLost on re-clone
12.37 s1,2182,814
22.29 s1,2302,841
32.65 s1,2312,916
42.35 s1,2312,854
52.53 s1,2122,865

Yes after promotion counts the pinned client only: 1,212 to 1,231 per run. Lost on re-clone counts both clients’ acknowledged writes that only the old primary held.

What the old primary did without fencing

The replica was promoted 2.37 seconds after the cut began (median). The old primary did not know it had been replaced: it could not reach etcd, so it never saw the new leader. So it kept accepting writes, and it kept saying yes to client B, which was still pointed at it.

  • Client B was told yes about 1,200 times per run after the promotion: 1,212 to 1,231 in the five runs. That count includes writes after the heal, because the old primary stayed a primary the whole time.
  • Client A's writes did not fail, so it never asked etcd again. Both clients stayed on the old primary, and from that moment the two nodes were taking writes independently.
  • When the heal came, the old primary was still a primary. The lab's table shows primary in every unfenced run.

Rebuilding it throws the history away

Two primaries that both took writes have two histories, and Postgres cannot merge them. To get back to one history, the lab rebuilt the old primary as a copy of the new one, a step the lab calls a re-clone. That threw away every acknowledged write that only the old primary held. Without fencing, that was 2,814 to 2,916 per run, from both clients together.

The count is about what the arithmetic predicts. The writers ran at 200 a second in total for about 14 seconds after the cut began: the 12-second cut, plus the 2 seconds the test kept writing after it ended. That is about 2,800 writes, the same order as the loss.

Fencing: the old primary stops itself

The old primary cannot hear etcd, so it cannot learn it was replaced. But it does know when it last renewed its lease. The rule uses that: once more than 0.6 × the TTL has passed since the last renewal, the primary fences itself. With a 2-second lease, that is 1.2 seconds.

That is well before the lease can run out at 2 seconds, which is when the replica is allowed to take over. The controller checks every quarter-second, so it fences in the gap between the cut and the lease's end.

To fence, the controller makes new writes read-only by default and cuts off every client connection. Client B's next write is refused.

The workflow and the results

Each row is a recorded value from data/results/02_split_brain.json. The promotion times are measured from the moment the cut began.

Fencing Replica promoted after (median) Yes to the pinned client after promotion Rows only the old primary had, lost on re-clone Old primary after the heal
Off 2.37 s 1,212–1,231 per run (6,122 in five runs) 2,814–2,916 per run (14,290 in five runs) still primary
On 2.63 s 0 in all five runs 195–212 per run (1,008 in five runs) fenced

Two readings from the table matter most:

  • With fencing on, the pinned client's yeses after the promotion were zero in every run. The fence came at 1.2 seconds, before the promotion at 2.6 seconds (median), so the old primary was no longer taking writes by the time the new one was promoted.
  • Fencing reduced the loss by about 14 times, but not to zero. Rows lost fell from 14,290 to 1,008 across the five runs. The 195 to 212 per run that remain were accepted before the fence.

Lab 18's first exercise ran the same kind of partition, with writes at 200 a second and asynchronous replication, and lost 162 to 202 per run. The two numbers are close because they are the same mechanism: writes accepted by a primary the replica cannot reach.

What fencing does not fix

Fencing decides who may accept writes. It does not decide what happened to the writes already accepted. In the lab, the old primary accepted about one second's worth of writes before it fenced itself (195 to 212 per run, at 200 a second). The replica never received them, because its link was cut. Those writes were acknowledged to clients and are gone after the re-clone.

Losing nothing needs a different rule: the primary must not say yes until a copy has the write. Lab 18's first exercise tests synchronous replication, including a strict mode that never drops the copy, and strict mode has a cost. With only two nodes, a strict primary stops taking writes when its only copy is cut off.

The assumptions, and a stronger fix

Self-fencing assumes the old primary's clock runs at about the same rate as everyone else's. If the old primary's clock ran slow, it would fence late, and for a moment there could be two primaries again. The lab did not test a slow clock.

The stronger fix is a fencing token: each new leader gets a number that only goes up, and the storage refuses any write that carries an older number. Storage then decides, not the clock. The lab's controller records the etcd revision as its term, but the storage does not check it, so this is not a fencing token yet. The README's second exercise asks you to build one.

Caveats

  • One set of runs, on one laptop. Five runs per setting, a 12-second cut, and two clients at 100 writes a second each. The numbers are recorded results from that setup, not a production measurement.
  • Client A's behavior was not recorded separately. The lab counts the pinned client's yeses and the rows each node held. That client A's later writes landed on the new primary is inferred from the counts, not measured.
  • The 1,212–1,231 count is not only the cut period. It counts every yes from the pinned client after the promotion, including the time after the heal.
  • The fence timing was not measured. The 1.2 seconds is the controller's setting. The cut and the controller's last renewal are not timed against each other in this run.
  • The two cuts are not simultaneous. Toxiproxy cuts the etcd link and the replication link in two separate commands, a few hundred milliseconds apart.
  • The loss counts assume the script counts correctly. The first run of the script merged the row ids of the two writers and undercounted the loss by about half. The script now counts (writer, id) pairs, and the numbers above are from the rerun.
  • Not covered: a slow clock, fencing tokens, three nodes, and strict synchronous replication in this exercise. The lab's README lists fencing tokens as an exercise.

The checklist

  1. A partition and a client that didn't move is enough. Two primaries need no bug, only a cut link and a cached address.
  2. Fence before your lease can run out. Stop accepting writes at a fraction of the TTL, measured from your last successful renewal.
  3. Expect to lose what was accepted before the fence. Fencing stops new writes, not the ones already acknowledged.
  4. Rebuilding the old primary discards its history. Count what it held alone before you rebuild it, and treat that as the loss.
  5. Trust the storage, not only the clock, for the final word. A fencing token, checked by the storage, closes the gap that a slow clock leaves.

Quiz

Try it · Check your understanding0 of 3 answered
  1. 1.With fencing off, the replica has been promoted, and a client still connected to the old primary keeps writing. What does that client get back, and what happens to those writes?

  2. 2.Fencing was on, and about 200 acknowledged writes per run were still lost. Why?

  3. 3.Why does the primary fence itself at 0.6 × the lease, after its last renewal, rather than waiting for the lease to expire?

Check your understanding

Try each question before opening its answer.

With fencing off, what made the old primary keep saying yes after the replica was promoted, when no part of it was broken?

It was alive and reachable by client B, which still had its address, but it could not reach etcd or its replica. So it never learned that the lease had moved, and it kept accepting writes as a primary. A partition and a client that didn't move were enough. Client A, which only looks up the primary after a failed write, never failed, so it never moved either.

Fencing was on, and the pinned client got zero yeses after the promotion. Why were 195 to 212 writes per run still lost?

Because they were accepted before the fence. The old primary fenced itself 1.2 seconds after its last renewal, and until then it accepted writes that the replica never received. Fencing stops new writes after the fence. It doesn't undo the writes accepted before it.

The primary fences at 1.2 seconds, but the lease doesn't run out until 2 seconds. Why not fence at 2 seconds, to avoid any unnecessary fence?

Because the replica may take the lease the moment it expires. If the old primary waited until then, both nodes could be accepting writes during the handover. Fencing before the lease ends means the old primary has stopped by the time anyone else is allowed to promote.

Why did rebuilding the old primary as a copy throw away 2,814 to 2,916 writes per run?

Because while both nodes were primaries, each had accepted writes the other never received, and Postgres cannot merge two histories. Rebuilding the old primary as a copy of the new one made the new history the only one, so the rows that only the old primary held were discarded.

Next up: Chapter 45, backups and point-in-time restore: the replica that copied a bad DELETE in milliseconds, and the restore that undid it.

Learning something useful?

New labs, articles, and videos on evaluating and testing AI systems come out regularly. Follow along so you don't miss the next one.