TExcelTAD
Home › Docker Swarm › Raft & Quorum

Raft & Quorum

Every decision a swarm makes (create a service, scale it, schedule a task, store a secret) is written to a log that all manager nodes share. The managers keep that log consistent with the Raft consensus algorithm. Raft is why a swarm survives a manager crash, and also why it can freeze completely if you lose too many managers. This lesson explains the rules you need to size and operate the manager group, building on the overview in Swarm Architecture.

Leader, followers, and the log

At any time one manager is the leader; the others are followers. Only the leader accepts changes. When you run docker service scale api=5 on a follower, it forwards the request to the leader. The leader appends the change to its log, sends it to the followers, and commits it once a majority of managers (itself included) has stored it. Only committed entries are acted upon.

text
            ┌──────────── leader (manager-1) ─────────────┐
 change ───►│ log: … 41 42 [43: scale api=5]              │
            └──────┬──────────────────────────┬───────────┘
          append 43│                          │append 43
                   ▼                          ▼
          manager-2: ok (stored)     manager-3: ok (stored)
   2 of 3 stored = majority  ─►  entry 43 committed  ─►  scheduler acts

That majority is the quorum: floor(N / 2) + 1 managers out of N. As long as a quorum is alive and can talk, the swarm works. Each manager stores the full log and state in /var/lib/docker/swarm/raft.

How many failures can you survive?

python · try it yourself
print(f"{'managers':>8} {'quorum':>7} {'tolerated failures':>19}")
for n in range(1, 10):
    quorum = n // 2 + 1
    tolerated = n - quorum
    note = ""
    if n % 2 == 0:
        note = f"  <- no better than {n - 1}"
    if n == 1:
        note = "  <- no fault tolerance"
    print(f"{n:>8} {quorum:>7} {tolerated:>19}{note}")
managers  quorum  tolerated failures
       1       1                   0  <- no fault tolerance
       2       2                   0  <- no better than 1
       3       2                   1
       4       3                   1  <- no better than 3
       5       3                   2
       6       4                   2  <- no better than 5
       7       4                   3
       8       5                   3  <- no better than 7
       9       5                   4

The table explains the standard advice:

  • Use an odd number of managers. Going from 3 to 4 raises the quorum without tolerating one more failure, and adds one more machine that can fail.
  • 3 managers tolerate 1 failure, 5 tolerate 2: enough for almost every cluster. 7 is the practical maximum: every write has to reach a majority, so more managers make writes slower.
  • Managers are not about capacity. Workloads run on workers; adding managers adds safety, not throughput.

What happens without quorum

If too many managers fail, the survivors can't commit anything. The swarm is then read-only and frozen:

Still works Stops working
existing containers keep running on their nodes creating, updating, scaling or removing services
the routing mesh and overlay networks (already configured) rescheduling tasks of failed nodes
adding or removing nodes, rotating secrets

Commands fail with an error such as The swarm does not have a leader. It's possible that too few managers are online. Your application stays up for now, but it can't heal itself anymore. The recovery is covered in Backup & Restore: docker swarm init --force-new-cluster on a surviving manager.

Leader election

Followers expect regular heartbeats from the leader. Each follower has an election timeout with a random component; if it hears nothing before its timeout fires, it becomes a candidate, increases the term (an election counter), votes for itself and asks the others for votes. A manager grants at most one vote per term, and only to a candidate whose log is at least as up to date as its own. A candidate with a majority of votes becomes leader for that term. The randomised timeouts make it unlikely that two followers start an election at the same moment.

This model replays an election with fixed timeouts (the randomness is "pre-rolled" so the output is reproducible):

python · try it yourself
managers = {
    "m1": {"alive": True, "log": 43, "term": 7},
    "m2": {"alive": True, "log": 43, "term": 7},
    "m3": {"alive": True, "log": 42, "term": 7},
    "m4": {"alive": True, "log": 43, "term": 7},
    "m5": {"alive": True, "log": 43, "term": 7},
}
leader = "m1"
timeouts_ms = {"m2": 2310, "m3": 1720, "m4": 2950, "m5": 2480}   # timeouts fixed in advance

def election(dead):
    for m in dead:
        managers[m]["alive"] = False
    alive = [m for m, s in managers.items() if s["alive"]]
    down = [m for m in managers if m not in alive]
    quorum = len(managers) // 2 + 1
    print(f"down: {down}  alive: {alive}  quorum: {quorum}")
    for cand in sorted((m for m in alive if m in timeouts_ms), key=timeouts_ms.get):
        term = managers[cand]["term"] + 1
        votes = [cand]
        for voter in alive:
            if voter == cand:
                continue
            if managers[voter]["log"] <= managers[cand]["log"]:
                votes.append(voter)
            managers[voter]["term"] = term          # everyone moves to the new term
        managers[cand]["term"] = term
        won = len(votes) >= quorum
        print(f"  t={timeouts_ms[cand]}ms {cand} (log {managers[cand]['log']}) asks for term {term}: "
              f"votes {votes} -> {'LEADER' if won else 'lost'}")
        if won:
            return cand
    print("  no candidate reached quorum: swarm is frozen")

print("new leader:", election(["m1"]))
print()
print("new leader:", election(["m2", "m4"]))
down: ['m1']  alive: ['m2', 'm3', 'm4', 'm5']  quorum: 3
  t=1720ms m3 (log 42) asks for term 8: votes ['m3'] -> lost
  t=2310ms m2 (log 43) asks for term 9: votes ['m2', 'm3', 'm4', 'm5'] -> LEADER
new leader: m2

down: ['m1', 'm2', 'm4']  alive: ['m3', 'm5']  quorum: 3
  t=1720ms m3 (log 42) asks for term 10: votes ['m3'] -> lost
  t=2480ms m5 (log 43) asks for term 11: votes ['m5', 'm3'] -> lost
  no candidate reached quorum: swarm is frozen
new leader: None

In the first election m3 timed out first but lost: its log was behind (42 < 43), so the other managers refused their votes. Raft guarantees that a new leader always has every committed entry. m2 then won with 4 votes. In the second run m2 (the new leader) and m4 fail too, so three of five managers are down. m3 loses again because of its old log, and m5 collects 2 votes out of the 3 needed: no leader, no changes, until a manager comes back. Notice how the term keeps climbing with every failed election.

Seeing it on a real swarm

bash
$ docker node ls --filter role=manager
ID                            HOSTNAME    STATUS    AVAILABILITY   MANAGER STATUS   ENGINE VERSION
x1k8vq2m4n7p0r3t5w9y2z6b1 *   manager-1   Ready     Drain          Leader           29.0.2
c4h7j1l5o8s2u6x0a3d7f1g5k     manager-2   Ready     Drain          Reachable        29.0.2
q9w3e6r0t4y8u2i6o0p4a8s2d     manager-3   Down      Drain          Unreachable      29.0.2

$ docker info --format '{{.Swarm.Managers}} managers, {{.Swarm.Nodes}} nodes'
3 managers, 8 nodes

(sample output.) Reachable followers are healthy; an Unreachable manager still counts in N, which is why you should demote and remove a manager that is gone for good: docker node demote manager-3 then docker node rm manager-3. Otherwise a 3-manager swarm with one dead member is permanently one failure away from losing quorum.

Practical rules

  • Place managers in different failure domains (racks, availability zones): see High Availability.
  • Give managers stable IP addresses; Raft peers find each other by address.
  • Set managers to --availability drain in production so application load can't starve Raft of CPU or I/O.
  • Never restore a manager by copying a running manager's Raft directory: Raft state is per node. Follow the backup procedure.

Note: Kubernetes stores its state in etcd, which also uses Raft, so the same table (3 or 5 etcd members, odd numbers) applies there: Kubernetes Architecture.

Learn more: High Availability · Backup & Restore

Test yourself

A swarm has 5 managers. How many can fail while the swarm still accepts changes?

  1. 1
  2. 2
  3. 3
  4. 4

Why is 4 managers not better than 3?

  1. Swarm refuses even numbers
  2. Both tolerate only 1 failure, and 4 machines give one more thing that can break
  3. 4 managers can't elect a leader
  4. Raft needs a power of 2

A swarm lost quorum. What happens to the running containers?

  1. They are stopped immediately
  2. They keep running, but no changes or rescheduling can happen
  3. They move to the workers
  4. They restart in a loop