Sub topic 13
Split brain and fencing
This chapter assumes you know what a heartbeat and a health check are, how a primary and a standby pair works, and what synchronous and asynchronous replication mean. It also builds on the previous chapter's quorum and leader election. Here you will see how a cluster ends up with two leaders, what damage that causes, and how fencing stops it.
What split brain is
Split brain is a state in which two or more nodes each believe they are the primary and each accept writes. Each node is behaving correctly according to what it can see. The fault is that they cannot see each other.
The usual path to split brain goes through failure detection. A standby promotes itself when it stops hearing the primary's heartbeat. But silence has more than one cause:
- The primary crashed.
- The network between the two nodes failed, and the primary is still running and serving clients.
- The primary is alive but frozen, for example by a long garbage collection pause, a stalled virtual machine, or an overloaded disk.
From the standby's side, these three look identical. If it promotes itself in all three cases, then in the last two there are two primaries.
Why it is damaging
While both nodes accept writes, their data diverges. Typical consequences:
- Conflicting updates. Two clients update the same row to different values on different nodes. When the partition heals, there is no single correct value.
- Duplicate side effects. Both nodes run the same scheduled job, send the same email, or charge the same card.
- Corrupted shared storage. If both nodes mount the same disk or volume with a non-cluster-aware file system, interleaved writes can destroy the file system's metadata. This is the worst case, because it can be unrecoverable.
- Hard reconciliation. Merging two histories usually means discarding one side's writes. With asynchronous replication, some writes may already be lost on failover. Split brain adds more.
A related failure is the zombie primary: an old primary that was paused, not partitioned, and resumes after a new primary has been promoted. It still believes it holds the role, because nothing told it otherwise.
Prevention layer 1: quorum
Quorum is the first defense. A node may act as primary only if it can reach a majority of the voting members. In a cluster of N voters, a majority is floor(N/2) + 1.
Consider five voters split by a partition into groups of three and two. Only the group of three has a majority, so only it can elect or keep a leader. The group of two must stop accepting writes, even if its node was the leader a moment ago.
| Voters | Majority needed | Failures tolerated |
|---|---|---|
| 2 | 2 | 0 |
| 3 | 2 | 1 |
| 4 | 3 | 1 |
| 5 | 3 | 2 |
Two consequences follow from the table:
- A two-node cluster cannot tolerate any failure and still have a majority. This is why two-node primary and standby setups are the classic split brain risk. The usual fix is a third voter: a witness, arbiter, or tiebreaker that holds a vote but stores no data.
- Even sizes add cost without adding tolerance. Four voters tolerate one failure, the same as three.
Place voters in different fault domains. If three voters sit in one rack, a rack failure removes the majority. With three zones, one voter per zone lets the cluster survive the loss of any single zone.
Quorum guarantees that two sides cannot both elect a leader at the same time. It does not guarantee that the old leader has noticed it lost leadership. That gap is what fencing closes.
Prevention layer 2: fencing
Fencing makes sure a node that has lost the leader role can no longer cause damage, whether or not it knows it lost the role. There are two broad approaches.
Resource fencing: fencing tokens
Each time a new primary is promoted, the cluster issues a token that is larger than every earlier one. Clients and primaries attach the token to every write. The storage layer remembers the highest token it has seen and rejects anything lower. A zombie primary that wakes up with an old token is refused.
This is the pattern from the topic's code example:
class FencedStorage:
def __init__(self):
self.highest_token = 0
self.value = None
def write(self, token, value):
if token < self.highest_token:
raise PermissionError("stale fencing token")
self.highest_token = token
self.value = value
store = FencedStorage()
store.write(1, "from old primary")
store.write(2, "from new primary")
try:
store.write(1, "late write from old primary")
except PermissionError as err:
print(err) # stale fencing tokenThe check lives in the storage, not in the primary. That placement matters. A zombie cannot be trusted to check its own status, because the reason it is dangerous is that its view of the world is out of date. A lease or a "am I still leader?" check inside the primary has the same weakness: the process can pass the check, get paused, and then write after the lease expired.
Fencing tokens require the storage to cooperate. Databases that support term numbers or epochs, such as Raft-based systems, do this internally. If you build on a plain object store or a shared file system, you may need to add the check yourself, for example with a conditional write that compares a version number.
Node fencing: cutting the old primary off
The alternative is to make the old node unable to act at all. The cluster manager does this before it lets the new primary start. This approach is commonly called STONITH, short for "shoot the other node in the head". Typical methods:
- Power fencing. Use an out-of-band management interface or a smart power switch to power off or reboot the node.
- Hypervisor or cloud fencing. Call the cloud API to stop the instance, or detach its volume.
- Storage fencing. Revoke the node's access to shared storage, for example with SCSI persistent reservations.
- Network fencing. Remove the node from the load balancer or block it at a switch port.
The key rule is order. Fence first, confirm the fence succeeded, then promote. If the fence call fails or cannot be confirmed, the safe action is to not promote and alert a human. This trades availability for consistency: you accept downtime rather than risk two primaries.
Comparing the two fencing styles
| Aspect | Fencing tokens | Node fencing (STONITH) |
|---|---|---|
| What it blocks | Stale writes at the storage | The old node entirely |
| Requires | Storage that checks tokens | Reliable out-of-band control of the node |
| Effect on old node | Keeps running, writes rejected | Powered off, stopped, or cut off |
| Failure mode | Storage lacks a check, so stale writes slip through | Fence call fails, so failover is blocked |
| Protects other side effects (email, jobs) | No, only writes to the checked store | Yes, the node stops everything |
Many production systems use both. Quorum decides who should lead, node fencing removes the loser where possible, and tokens protect the data even if a fence is late.
Other defenses
- Self-fencing. A primary that loses contact with a majority demotes itself, stops serving writes, or restarts. This works well when the node is partitioned. It does not help with a frozen process, which cannot run its own check, so pair it with a token or node fence.
- Leases with margin. A leader holds a time-limited lease and must renew it. Set the standby's wait to longer than the lease plus allowed clock drift. Leases alone are not safe against pauses, which is why tokens exist.
- Shared-nothing replication. If each node has its own storage, a zombie cannot corrupt a shared volume. It can still diverge, so you still need the controls above.
- Reconciliation plan. Decide beforehand how to detect and repair divergence. A common rule is that the side with quorum wins and the other side's unreplicated writes are exported for manual review.
Common mistakes
- Two-node clusters with no tiebreaker. Each node either never fails over, or both promote during a partition.
- Promoting on a single missed heartbeat. Short detection timeouts raise the rate of false failovers, and each false failover is a chance for split brain. Tune timeouts against the false-positive cost discussed earlier.
- Trusting the old primary to stand down. Fencing must work even when the old primary is unresponsive.
- Fencing over the failing network. The fence command cannot reach the node that most needs it.
- Voters in one fault domain. The majority disappears with the domain.
- Never testing the partition case. Most failover tests kill a process. Few cut the network between nodes while leaving both nodes alive.
Checking your design
For any primary and standby design, ask these questions:
- What does the standby do when it sees silence? Does it need a majority to promote?
- How many voters exist, and in which fault domains?
- If the old primary is alive, what stops it from writing? Is that check in the storage or in the node?
- If fencing fails, does the system stay down or promote anyway?
- After a heal, how is divergent data detected and resolved?
Exercise
A database cluster has three nodes: two in zone A and one in zone B. A network partition separates zone A from zone B. Which side can keep a leader, and what weakness does this layout have? How would you change it, and what extra protection stops a leader that was paused (not partitioned) from writing after a new leader is elected?
Show answer
The two nodes in zone A form a majority (2 of 3), so zone A keeps or elects the leader and zone B's node must stop accepting writes. The weakness is that losing zone A removes the majority, so the cluster goes down even though one healthy node remains. Place one voter in each of three zones (or add a lightweight witness in a third zone), so any single zone can fail and two voters still remain. For a paused old leader, quorum is not enough because it does not know it lost the role when it wakes. Use fencing: issue a higher token or epoch with each election and have the storage reject writes with older tokens, optionally combined with node fencing that stops the old leader before the new one is promoted.
Exercise
Your failover script promotes the standby first and then calls the cloud API to stop the old primary. The stop call sometimes times out. What is wrong with this order, and what should the script do instead?
Show answer
Promoting before the old primary is confirmed stopped opens a window with two primaries, and if the stop call times out, that window stays open. The script should fence first, confirm the old primary is stopped (or its storage access revoked), and only then promote. If the fence cannot be confirmed, it should not promote and should alert an operator, accepting downtime to avoid divergent data.