Database Distributed Systems · Lesson 108 of 112

Database Consensus and Failure in Plain Words

What you will learn

  • Why a slow machine and a dead machine look the same from outside
  • What split brain is
  • How a majority (quorum) prevents two leaders
  • What consensus means and where databases use it
  • How a term (epoch) stops an old leader from doing harm

All code in this lesson is a simulation that imitates an idea. It is not a real database. You can run each block on its own.

1. Failure is normal

In a system of many machines, something is always failing: a machine crashes, a disk fills up, a network cable is cut, a message is delayed or lost. The design question is not "how do we avoid failure" but "how do we keep working correctly when parts fail".

A hard fact makes this difficult: from outside, a machine that is dead and a machine that is only very slow look the same. If a machine does not answer within a timeout, the others cannot know which it is. A failure detector (for example "no heartbeat message for 5 seconds") can only suspect; it can be wrong. This matters because the next decision, "who is the leader now?", is dangerous if made on a wrong guess.

2. Electing a leader

Many systems have one leader (the primary of lesson 14.2) and need a new one when it fails. The simplest rule is "the running node with the highest id wins":

nodes = {1: True, 2: True, 3: True, 4: True, 5: True}     # node id -> is it running?

def elect(reachable_from):
    """Simplest rule: the running node with the highest id becomes leader."""
    alive = [n for n in reachable_from if nodes[n]]
    return max(alive) if alive else None

print("All five nodes running -> leader:", elect(nodes))
nodes[5] = False
print("Node 5 fails          -> leader:", elect(nodes))
nodes[4] = False
print("Node 4 fails too      -> leader:", elect(nodes))
nodes[5] = nodes[4] = True
print("Both come back        -> leader:", elect(nodes), "(the highest id takes over again)")

print("\nNetwork partition: {1,2,3} cannot reach {4,5}")
side_a, side_b = [1, 2, 3], [4, 5]
nodes = {n: True for n in range(1, 6)}
print("  side A elects", elect(side_a), "| side B elects", elect(side_b), "-> TWO leaders (split brain)")

def elect_with_majority(group, total=5):
    alive = [n for n in group if nodes[n]]
    if len(alive) * 2 > total:
        return max(alive)
    return None

print("\nSame partition, but a leader needs a MAJORITY of all 5 nodes:")
print("  side A (3 of 5):", elect_with_majority(side_a))
print("  side B (2 of 5):", elect_with_majority(side_b), "(no leader: it cannot be sure the other side is down)")
All five nodes running -> leader: 5
Node 5 fails          -> leader: 4
Node 4 fails too      -> leader: 3
Both come back        -> leader: 5 (the highest id takes over again)

Network partition: {1,2,3} cannot reach {4,5}
  side A elects 3 | side B elects 5 -> TWO leaders (split brain)

Same partition, but a leader needs a MAJORITY of all 5 nodes:
  side A (3 of 5): 3
  side B (2 of 5): None (no leader: it cannot be sure the other side is down)

Read the output:

  • With the simple rule, leaders change as nodes fail and come back. This works while every node sees the same set of running nodes.
  • After a network partition, side {1,2,3} cannot reach side {4,5}. Each side believes the other side is dead and elects its own leader: two leaders at the same time, called split brain. Both accept writes, and the data diverges: this can cause lost or corrupted updates.
  • The fix is a majority rule: a leader can be chosen only by more than half of all nodes. Side A has 3 of 5 and can elect a leader. Side B has only 2 of 5, so it elects nobody and waits: it cannot tell whether the other side is down or just unreachable. Two groups can never both hold a majority of the same set, so two leaders cannot happen.

The majority table in SQL. This lesson runs on the sample database you chose in lesson 4.1 (use the Example data picker at the top). A recursive query counts cluster sizes, and a small table of nodes plays the election with the majority rule:

WITH RECURSIVE sizes(n) AS (SELECT 1 UNION ALL SELECT n + 1 FROM sizes WHERE n < 7)
SELECT n AS nodes, n / 2 + 1 AS majority, n - (n / 2 + 1) AS failures_survived FROM sizes;
nodes  majority  failures_survived
-----  --------  -----------------
    1         1                  0
    2         2                  0
    3         2                  1
    4         3                  1
    5         3                  2
    6         4                  2
    7         4                  3
(7 rows)
CREATE TABLE cluster (id INTEGER PRIMARY KEY, side TEXT);
INSERT INTO cluster VALUES (1, 'A'), (2, 'A'), (3, 'A'), (4, 'B'), (5, 'B');
SELECT side, COUNT(*) AS nodes, MAX(id) AS highest_id,
       CASE WHEN COUNT(*) * 2 > (SELECT COUNT(*) FROM cluster) THEN MAX(id) END AS leader_if_majority_needed
FROM cluster GROUP BY side ORDER BY side;
side  nodes  highest_id  leader_if_majority_needed
----  -----  ----------  -------------------------
A         3           3                          3
B         2           5                       NULL
(2 rows)
WITH RECURSIVE sizes(n) AS (SELECT 1 UNION ALL SELECT n + 1 FROM sizes WHERE n < 7)
SELECT n AS nodes, n / 2 + 1 AS majority, n - (n / 2 + 1) AS failures_survived FROM sizes;
nodes  majority  failures_survived
-----  --------  -----------------
    1         1                  0
    2         2                  0
    3         2                  1
    4         3                  1
    5         3                  2
    6         4                  2
    7         4                  3
(7 rows)
CREATE TABLE cluster (id INTEGER PRIMARY KEY, side TEXT);
INSERT INTO cluster VALUES (1, 'A'), (2, 'A'), (3, 'A'), (4, 'B'), (5, 'B');
SELECT side, COUNT(*) AS nodes, MAX(id) AS highest_id,
       CASE WHEN COUNT(*) * 2 > (SELECT COUNT(*) FROM cluster) THEN MAX(id) END AS leader_if_majority_needed
FROM cluster GROUP BY side ORDER BY side;
side  nodes  highest_id  leader_if_majority_needed
----  -----  ----------  -------------------------
A         3           3                          3
B         2           5                       NULL
(2 rows)
WITH RECURSIVE sizes(n) AS (SELECT 1 UNION ALL SELECT n + 1 FROM sizes WHERE n < 7)
SELECT n AS nodes, n / 2 + 1 AS majority, n - (n / 2 + 1) AS failures_survived FROM sizes;
nodes  majority  failures_survived
-----  --------  -----------------
    1         1                  0
    2         2                  0
    3         2                  1
    4         3                  1
    5         3                  2
    6         4                  2
    7         4                  3
(7 rows)
CREATE TABLE cluster (id INTEGER PRIMARY KEY, side TEXT);
INSERT INTO cluster VALUES (1, 'A'), (2, 'A'), (3, 'A'), (4, 'B'), (5, 'B');
SELECT side, COUNT(*) AS nodes, MAX(id) AS highest_id,
       CASE WHEN COUNT(*) * 2 > (SELECT COUNT(*) FROM cluster) THEN MAX(id) END AS leader_if_majority_needed
FROM cluster GROUP BY side ORDER BY side;
side  nodes  highest_id  leader_if_majority_needed
----  -----  ----------  -------------------------
A         3           3                          3
B         2           5                       NULL
(2 rows)

Without the majority rule both sides would elect a leader (3 and 5). With it only side A, which holds 3 of the 5 nodes, can.

The cost of the majority rule is that the side without a majority becomes unavailable for writes. This is the consistency-over-availability choice of lesson 14.5.

3. How many failures can you survive?

Because a majority is needed, the size of the group decides how many failures it can tolerate:

# Majority rule: how many failures can a cluster of n nodes survive?
for n in [1, 2, 3, 4, 5, 6, 7]:
    majority = n // 2 + 1
    print(f"{n} nodes: majority = {majority}, survives {n - majority} failed node(s)")
1 nodes: majority = 1, survives 0 failed node(s)
2 nodes: majority = 2, survives 0 failed node(s)
3 nodes: majority = 2, survives 1 failed node(s)
4 nodes: majority = 3, survives 1 failed node(s)
5 nodes: majority = 3, survives 2 failed node(s)
6 nodes: majority = 4, survives 2 failed node(s)
7 nodes: majority = 4, survives 3 failed node(s)

Two things follow from the table:

  • Three nodes survive one failure and five survive two. Odd numbers are efficient: 4 nodes survive the same single failure as 3, and 6 survive the same two as 5, so the extra node adds cost and no extra tolerance.
  • One or two nodes survive no failure if a majority is required: with two nodes both must be up.
Quick check: a group of 7 nodes is split by a partition into 4 and 3. Which side can elect a leader?

The side with 4 nodes, because 4 is more than half of 7. The side with 3 cannot.

4. Consensus

Consensus is the problem of getting several machines to agree on one value (who is leader, or which change is next in the log), even when machines crash and messages are lost, and never to disagree afterwards. The majority idea above is the heart of it. Well-known algorithms that solve it include Paxos and Raft; this lesson does not describe their details. Databases and coordination services use consensus to:

  • choose a leader and replace it safely
  • agree on the order of changes in the replicated log (lesson 14.2), so all replicas apply the same changes in the same order
  • store small, important configuration that every machine must see identically

Consensus is slow compared with a single machine: each decision needs a majority to answer. For that reason it is used for the small, critical decisions, not for bulk data.

5. Terms: stopping an old leader

There is one more danger. A leader can be wrongly suspected: it is only slow, and the others elect a new leader. The old one then wakes up and still thinks it is the leader. To stop it from doing harm, each leadership period gets a number called a term (or epoch) that only goes up. Every write carries its leader's term, and a node refuses writes from an older term:

class Storage:
    """A shared resource that only accepts writes from the leader with the newest term."""
    def __init__(self):
        self.highest_term = 0
        self.log = []
    def write(self, leader, term, value):
        if term < self.highest_term:
            return f"REJECTED {value!r} from {leader} (term {term} is older than term {self.highest_term})"
        self.highest_term = term
        self.log.append(value)
        return f"accepted {value!r} from {leader} (term {term})"

store = Storage()
print(store.write("node 5", 1, "write A"))
print("node 5 is slow (not dead). The others elect node 4 in term 2.")
print(store.write("node 4", 2, "write B"))
print("node 5 wakes up and still believes it is the leader:")
print(store.write("node 5", 1, "write C"))
print("final log:", store.log)
accepted 'write A' from node 5 (term 1)
node 5 is slow (not dead). The others elect node 4 in term 2.
accepted 'write B' from node 4 (term 2)
node 5 wakes up and still believes it is the leader:
REJECTED 'write C' from node 5 (term 1 is older than term 2)
final log: ['write A', 'write B']

Node 5 was only slow, not dead. When it returned and tried to write with its old term 1, the storage had already accepted term 2 from node 4, so the stale write was rejected. The log stays correct. This idea is sometimes called fencing: the old leader is "fenced off" by the higher term.

Fencing in SQL. The storage accepts a write only when its term is at least the highest term it has seen. The tables are small ones of their own; Reset data removes them.

CREATE TABLE fenced_log (id INTEGER PRIMARY KEY, term INTEGER, leader TEXT, value TEXT);
INSERT INTO fenced_log (term, leader, value) SELECT 1, 'node 5', 'write A'
WHERE 1 >= COALESCE((SELECT MAX(term) FROM fenced_log), 0);
INSERT INTO fenced_log (term, leader, value) SELECT 2, 'node 4', 'write B'
WHERE 2 >= COALESCE((SELECT MAX(term) FROM fenced_log), 0);
(1 row changed)

Node 5 wakes up and still believes it is the leader (term 1). Its write changes no row:

INSERT INTO fenced_log (term, leader, value) SELECT 1, 'node 5', 'write C'
WHERE 1 >= COALESCE((SELECT MAX(term) FROM fenced_log), 0);
(0 rows changed)
SELECT term, leader, value FROM fenced_log ORDER BY id;
term  leader  value
----  ------  -------
   1  node 5  write A
   2  node 4  write B
(2 rows)
CREATE TABLE fenced_log (id INTEGER PRIMARY KEY, term INTEGER, leader TEXT, value TEXT);
INSERT INTO fenced_log (term, leader, value) SELECT 1, 'node 5', 'write A'
WHERE 1 >= COALESCE((SELECT MAX(term) FROM fenced_log), 0);
INSERT INTO fenced_log (term, leader, value) SELECT 2, 'node 4', 'write B'
WHERE 2 >= COALESCE((SELECT MAX(term) FROM fenced_log), 0);
(1 row changed)

Node 5 wakes up and still believes it is the leader (term 1). Its write changes no row:

INSERT INTO fenced_log (term, leader, value) SELECT 1, 'node 5', 'write C'
WHERE 1 >= COALESCE((SELECT MAX(term) FROM fenced_log), 0);
(0 rows changed)
SELECT term, leader, value FROM fenced_log ORDER BY id;
term  leader  value
----  ------  -------
   1  node 5  write A
   2  node 4  write B
(2 rows)
CREATE TABLE fenced_log (id INTEGER PRIMARY KEY, term INTEGER, leader TEXT, value TEXT);
INSERT INTO fenced_log (term, leader, value) SELECT 1, 'node 5', 'write A'
WHERE 1 >= COALESCE((SELECT MAX(term) FROM fenced_log), 0);
INSERT INTO fenced_log (term, leader, value) SELECT 2, 'node 4', 'write B'
WHERE 2 >= COALESCE((SELECT MAX(term) FROM fenced_log), 0);
(1 row changed)

Node 5 wakes up and still believes it is the leader (term 1). Its write changes no row:

INSERT INTO fenced_log (term, leader, value) SELECT 1, 'node 5', 'write C'
WHERE 1 >= COALESCE((SELECT MAX(term) FROM fenced_log), 0);
(0 rows changed)
SELECT term, leader, value FROM fenced_log ORDER BY id;
term  leader  value
----  ------  -------
   1  node 5  write A
   2  node 4  write B
(2 rows)

Worked example: sizing a small cluster

A made-up team wants a coordination group that keeps working when any two machines fail at once.

  1. To survive 2 failures with a majority rule, the number of running machines must still be a majority. If n machines are needed, the majority is n // 2 + 1, and survivors = n − majority.
  2. From the table in section 3: 5 nodes survive 2 failures; 3 do not.
  3. So they need 5 nodes. A sixth node would not add tolerance.

The numbers come from the simulation above and the team is made up.

Common mistakes

  • Treating a timeout as proof that a machine is dead. It is only a suspicion.
  • Choosing a leader without a majority. A partition can then produce two leaders.
  • Using an even number of nodes and expecting more tolerance than the next lower odd number.
  • Letting an old leader keep writing. Use terms or fencing so that stale leaders are rejected.
  • Using consensus for all data. It is meant for small, critical decisions.

Key takeaways

  • From outside, a dead machine and a slow machine look alike, so failure detection is only suspicion.
  • Two leaders at once (split brain) can corrupt data; a majority rule prevents it, at the cost of availability on the minority side.
  • A group of n nodes needs n // 2 + 1 for a majority, so 3 nodes survive 1 failure and 5 survive 2.
  • Consensus makes machines agree on one value or order of changes despite failures; Paxos and Raft are well-known algorithms for it.
  • Terms (epochs) let nodes reject writes from an old leader.

Practice

1. Why can a failure detector be wrong?

Show answer

Because a machine that does not answer in time may be only slow or cut off by the network, not dead. The detector can only suspect failure.

2. What is split brain and why is it dangerous?

Show answer

Two parts of a system each believe they have the leader and both accept writes. The data then diverges and updates can be lost or conflict.

3. How does requiring a majority prevent split brain?

Show answer

Two groups cannot both contain more than half of the same set of nodes, so only one side of a partition can elect a leader.

4. How many failures can a group of 7 nodes survive with a majority rule?

Show answer

Three (the majority is 4, so up to 7 − 4 = 3 nodes can fail).

5. In the simulation, why was node 5's write rejected?

Show answer

It carried term 1, but the storage had already accepted term 2 from the new leader (node 4), so the older term was refused.

6. Why is consensus used for small decisions rather than all of a large database?

Show answer

Each decision needs a majority of machines to respond, which is much slower than a single machine, so it is reserved for small, critical decisions such as leader choice and the order of changes.