TExcelTAD
Home › Docker Swarm › High Availability

High Availability

A swarm heals itself: when a task dies it is restarted, when a node disappears its tasks are scheduled elsewhere. But self-healing only helps if there is somewhere healthy to heal to, and if the control plane that does the healing survives the same failure. High availability (HA) is the practice of arranging managers, workers, replicas and capacity so that any single failure (a container, a node, a whole data-centre zone) leaves the application running.

Think in failure domains

A failure domain is a set of things that fail together: the containers of one node, the nodes on one rack or power feed, the machines in one cloud availability zone (AZ). HA design asks one question per layer: if this whole domain disappears, what is left?

text
           zone a                  zone b                  zone c
   ┌──────────────────┐   ┌──────────────────┐   ┌──────────────────┐
   │ manager-1        │   │ manager-2        │   │ manager-3        │
   │ worker-a1 worker-a2  │ worker-b1 worker-b2  │ worker-c1 worker-c2
   │ api.1  api.4     │   │ api.2  api.5     │   │ api.3  api.6     │
   └──────────────────┘   └──────────────────┘   └──────────────────┘
        lose any one zone: 2 of 3 managers left (quorum), 4 of 6 api tasks left

Layer 1: managers across zones

Raft needs a majority of managers. Where you put them matters as much as how many you have:

python · try it yourself
from itertools import combinations

def survives(layout):
    """layout: managers per zone. Can the swarm keep quorum if any ONE zone fails?"""
    total = sum(layout.values())
    quorum = total // 2 + 1
    worst = min(total - n for n in layout.values())
    return worst >= quorum, worst, quorum

layouts = {
    "3 managers, 1 zone":      {"a": 3},
    "3 managers, 2 zones":     {"a": 2, "b": 1},
    "3 managers, 3 zones":     {"a": 1, "b": 1, "c": 1},
    "5 managers, 2 zones":     {"a": 3, "b": 2},
    "5 managers, 3 zones":     {"a": 2, "b": 2, "c": 1},
    "7 managers, 3 zones":     {"a": 3, "b": 2, "c": 2},
}
for name, layout in layouts.items():
    ok, left, quorum = survives(layout)
    print(f"{name:<22} {layout}  worst case {left} left, quorum {quorum}: "
          f"{'survives a zone outage' if ok else 'LOSES QUORUM'}")
3 managers, 1 zone     {'a': 3}  worst case 0 left, quorum 2: LOSES QUORUM
3 managers, 2 zones    {'a': 2, 'b': 1}  worst case 1 left, quorum 2: LOSES QUORUM
3 managers, 3 zones    {'a': 1, 'b': 1, 'c': 1}  worst case 2 left, quorum 2: survives a zone outage
5 managers, 2 zones    {'a': 3, 'b': 2}  worst case 2 left, quorum 3: LOSES QUORUM
5 managers, 3 zones    {'a': 2, 'b': 2, 'c': 1}  worst case 3 left, quorum 3: survives a zone outage
7 managers, 3 zones    {'a': 3, 'b': 2, 'c': 2}  worst case 4 left, quorum 4: survives a zone outage

With only two zones, one of them always holds the majority of managers, and losing that zone freezes the swarm. Two zones protect against node failures, not zone failures. You need three zones (or two zones plus a small "tie-breaker" manager somewhere else) to survive a zone outage.

Also keep managers out of the application's way: set them to drain availability so containers never compete with Raft for CPU and disk, and give them stable addresses.

Layer 2: replicas spread over failure domains

The scheduler already spreads replicas over nodes, but two nodes in the same zone are one failure domain. Label the nodes with their zone and ask the scheduler to spread over the label:

bash
$ docker node update --label-add zone=a worker-a1
$ docker node update --label-add zone=b worker-b1
compose · try it yourself
# $ docker stack config -c stack.yaml
# --- stack.yaml
services:
  api:
    image: ghcr.io/acme/shop-api:2.4.1
    healthcheck:
      test: ["CMD", "wget", "-qO-", "http://localhost:9000/health"]
      interval: 10s
      retries: 3
    deploy:
      replicas: 6
      placement:
        constraints: [node.role == worker]
        preferences:
          - spread: node.labels.zone
        max_replicas_per_node: 2
      restart_policy:
        condition: any
        delay: 5s
      update_config:
        parallelism: 1
        order: start-first
        failure_action: rollback
version: "3.13"
services:
  api:
    deploy:
      replicas: 6
      update_config:
        parallelism: 1
        failure_action: rollback
        order: start-first
      restart_policy:
        condition: any
        delay: 5s
      placement:
        constraints:
          - node.role == worker
        preferences:
          - spread: node.labels.zone
        max_replicas_per_node: 2
    healthcheck:
      test:
        - CMD
        - wget
        - -qO-
        - http://localhost:9000/health
      interval: 10s
      retries: 3
    image: ghcr.io/acme/shop-api:2.4.1

spread: node.labels.zone balances tasks evenly across the label's values; max_replicas_per_node: 2 stops a single node from collecting too many after a failure. Here's the effect of a zone outage, with and without the spread preference:

python · try it yourself
from collections import Counter

workers = {"a1": "a", "a2": "a", "b1": "b", "b2": "b", "c1": "c", "c2": "c"}

def place(replicas, spread_zone):
    placed = Counter()
    zones = Counter()
    for _ in range(replicas):
        if spread_zone:
            key = lambda n: (zones[workers[n]], placed[n], n)
        else:  # node spread only; ties broken by name, so zone "a" fills first
            key = lambda n: (placed[n], n)
        node = min(workers, key=key)
        placed[node] += 1
        zones[workers[node]] += 1
    return placed

def report(title, placed, replicas):
    by_zone = Counter()
    for node, n in placed.items():
        by_zone[workers[node]] += n
    worst = min(replicas - n for n in by_zone.values())
    print(f"{title}: per zone {dict(sorted(by_zone.items()))}, worst zone outage leaves {worst}/{replicas}")

report("3 replicas, node spread only ", place(3, False), 3)
report("3 replicas, spread over zone ", place(3, True), 3)
report("6 replicas, spread over zone ", place(6, True), 6)
3 replicas, node spread only : per zone {'a': 2, 'b': 1}, worst zone outage leaves 1/3
3 replicas, spread over zone : per zone {'a': 1, 'b': 1, 'c': 1}, worst zone outage leaves 2/3
6 replicas, spread over zone : per zone {'a': 2, 'b': 2, 'c': 2}, worst zone outage leaves 4/6

With only node spreading, three replicas can land on a1, a2 and b1: two of them share zone a, and losing that zone leaves one replica to carry everything. Spreading over the zone label caps the loss at one replica in three (or two in six).

Layer 3: capacity for the failure (N+1)

Surviving a failure also means the remaining nodes can carry the load. If a zone holds a third of your capacity, the other two thirds must handle peak traffic alone, so plan to run at no more than about two thirds utilisation. Reservations (Reservations & Limits) make this visible: if the rescheduled tasks don't fit, they stay Pending, which is better than overloading the survivors, but still an outage for those replicas.

python · try it yourself
zones = 3
peak_load = 900                 # requests/s at peak
per_replica = 100               # one replica handles 100 req/s
for replicas in (9, 12, 14):
    after = replicas - -(-replicas // zones)       # lose the zone with the most replicas
    print(f"{replicas} replicas: {replicas * per_replica} req/s normally, "
          f"{after * per_replica} req/s after a zone outage -> "
          f"{'enough' if after * per_replica >= peak_load else 'NOT enough'} for {peak_load}")
9 replicas: 900 req/s normally, 600 req/s after a zone outage -> NOT enough for 900
12 replicas: 1200 req/s normally, 800 req/s after a zone outage -> NOT enough for 900
14 replicas: 1400 req/s normally, 900 req/s after a zone outage -> enough for 900

Layer 4: the edges

  • Entry point: clients reach the cluster through an external load balancer or DNS with several node addresses, never through one node.
  • State: a database pinned to one node is a single point of failure, however many web replicas you run. Use a replicated database, a managed service, or storage that can move (Volumes in a Swarm).
  • Registry: if the image registry is down, rescheduled tasks can't pull images. Mirror critical images or keep them cached on every node.
  • Rebalancing: when a failed node comes back, Swarm does not move tasks back to it. Tasks stay where they were rescheduled until they are replaced. Run docker service update --force <service> (a rolling restart) to rebalance after an outage.

Test the failure, don't assume it

Rehearse: drain a node during business hours, stop a manager, block a zone in a staging environment. Watch docker service ps, the LB health checks and your dashboards (Logging & Monitoring). A failover that has never been tested is a hope, not a plan.

Note: Kubernetes expresses the same ideas with topologySpreadConstraints, PodDisruptionBudgets and control planes across zones: see Scheduling.

Learn more: Raft & Quorum · Placement Constraints · Backup & Restore

Test yourself

You have 5 managers in two availability zones (3 + 2). What happens if the zone with 3 managers fails?

  1. The swarm continues with 2 managers
  2. The swarm loses quorum and can't make changes
  3. The workers become managers
  4. Swarm promotes the 2 survivors to quorum automatically

What does placement.preferences: [spread: node.labels.zone] do?

  1. Only schedules on nodes with a zone label
  2. Balances tasks evenly across the values of the zone label
  3. Moves tasks between zones every hour
  4. Limits the service to one zone

A failed node rejoins the swarm. What happens to the tasks that were moved away from it?

  1. They move back automatically
  2. They stay where they are until replaced; use docker service update --force to rebalance
  3. They are duplicated
  4. They are stopped