etcd cluster inconsistency after Docker overlay restart causing wrong leader election

Problem

A three‑node etcd cluster running inside Docker containers provides the distributed configuration store for Patroni in a PostgreSQL high‑availability (HA) deployment. After a Docker overlay network restart, the cluster entered an inconsistent state: members reported different revisions, the leader election process repeatedly chose different nodes, and Patroni performed split‑brain failovers, promoting multiple primary PostgreSQL instances simultaneously.

Observed symptoms

  • Patroni logs show “etcd member node‑X is not the leader” followed by “Failover triggered”.
  • etcdctl member list reports differing raft term and revision values across members.
  • Network overlay restart logs contain “docker0: link down” and “docker0: link up”.
  • PostgreSQL instances on two nodes both report role=primary in pg_stat_replication.

Root Cause

The overlay network restart caused a temporary loss of connectivity between the three etcd containers. During the outage, each member continued to accept client requests because the etcd client timeout was longer than the network partition. The following sequence produced the inconsistency:

  1. Network partition: Docker overlay removed the vxlan tunnel for ~8 seconds.
  2. Quorum loss detection delay: etcd uses a --heartbeat-interval (default 100 ms) and --election-timeout (default 1000 ms). The partition was shorter than the election timeout, so the remaining nodes did not step down.
  3. Stale leader continues to accept writes: The isolated leader kept committing entries locally, incrementing its revision while the other two nodes could not replicate those entries.
  4. Re‑join without snapshot sync: When the overlay recovered, the isolated node re‑joined but could not catch up because the leader’s etcd snapshot size exceeded the default --max-snapshots limit, causing the node to start a new election with a higher term but a lower revision.
  5. Split‑brain detection failure in Patroni: Patroni queries etcd for the leader_key. Due to divergent revisions, two nodes each believed they held the latest leader_key, leading to simultaneous primary promotion.

The core issue is the combination of:

  • Short network outage that does not trigger an immediate election.
  • Insufficient etcd snapshot/compaction configuration to reconcile divergent logs.
  • Patroni’s reliance on a single etcd key without additional quorum verification.

Debug

1. Verify cluster health and member status

docker exec etcd-node-1 etcdctl endpoint health --cluster
docker exec etcd-node-2 etcdctl member list -w table

Typical output after the incident:

+----------------+----------+----------+------------+-----------+------------+
| ID             | STATUS   | NAME     | PEER ADDRS | CLIENT ADDRS | IS LEADER |
+----------------+----------+----------+------------+-----------+------------+
| 8b3c2a...      | started  | node-1   | http://10.0.0.1:2380 | http://10.0.0.1:2379 | false |
| 6d9f4e...      | started  | node-2   | http://10.0.0.2:2380 | http://10.0.0.2:2379 | true |
| a1f7c9...      | started  | node-3   | http://10.0.0.3:2380 | http://10.0.0.3:2379 | false |
+----------------+----------+----------+------------+-----------+------------+

Notice that node-2 reports itself as leader, but etcdctl endpoint status shows different raft term values:

docker exec etcd-node-1 etcdctl endpoint status -w json
[
  {
    "Endpoint": "http://10.0.0.1:2379",
    "Status": {
      "version": "3.5.9",
      "dbSize": 1048576,
      "leader": "6d9f4e...",
      "raftTerm": 12,
      "raftIndex": 3421,
      "raftAppliedIndex": 3420
    }
  },
  ...
]

2. Inspect recent log entries around the overlay restart

docker logs etcd-node-1 2>&1 | grep -i "raft\|network\|snapshot"

Sample excerpt:

2024-11-21T12:34:45.112Z [warn] raft: failed to send message to 6d9f4e...: transport: connection refused
2024-11-21T12:34:45.215Z [info] raft: leader 6d9f4e... stepped down to follower
2024-11-21T12:34:46.001Z [info] snapshot: saved snapshot at index 3400 term 12
2024-11-21T12:34:47.873Z [error] transport: failed to start peer listener: listen tcp 0.0.0.0:2380: bind: address already in use

3. Capture network state during the failure

docker exec etcd-node-1 tcpdump -i eth0 port 2380 -w /tmp/etcd.pcap
# later analyze with Wireshark:
tshark -r /tmp/etcd.pcap -Y "etcd.raft" -T fields -e frame.time_relative -e etcd.raft.msg_type

4. Review Patroni configuration for etcd interaction

cat /etc/patroni.yml | grep -A3 "etcd"
etcd:
  host: 10.0.0.1:2379,10.0.0.2:2379,10.0.0.3:2379
  ttl: 30
  retry_timeout: 10
  loop_wait: 10

The ttl of 30 seconds is longer than the overlay outage, allowing stale keys to survive.

Solution

1. Adjust etcd election and heartbeat parameters

Configure a shorter election timeout so that a partition triggers a new election before the isolated leader can diverge.

# /etc/etcd/etcd.conf.yml (applied to all three nodes)
name: node-1
data-dir: /etcd-data
listen-peer-urls: http://0.0.0.0:2380
listen-client-urls: http://0.0.0.0:2379
initial-advertise-peer-urls: http://10.0.0.1:2380
advertise-client-urls: http://10.0.0.1:2379
initial-cluster: node-1=http://10.0.0.1:2380,node-2=http://10.0.0.2:2380,node-3=http://10.0.0.3:2380
initial-cluster-state: existing
initial-cluster-token: etcd-cluster-01
# New parameters
heartbeat-interval: 50   # ms (default 100)
election-timeout: 250    # ms (default 1000)
auto-compaction-retention: "1h"
max-snapshots: 5
max-wals: 5

After updating the file, restart each container:

docker restart etcd-node-1
docker restart etcd-node-2
docker restart etcd-node-3

2. Enable etcd snapshot catch‑up on re‑join

Set --snapshot-count to a lower value and increase --max-snapshots so that a node that missed a few entries can receive a full snapshot instead of trying to replay an extensive log.

# In the same etcd.conf.yml
snapshot-count: 5000
max-snapshots: 10
max-wals: 10

3. Harden Patroni’s etcd interaction

  • Reduce ttl to 10 seconds to ensure stale leader keys expire quickly.
  • Enable loop_wait of 5 seconds and retry_timeout of 5 seconds to force faster re‑evaluation.
# /etc/patroni.yml (excerpt)
etcd:
  host: 10.0.0.1:2379,10.0.0.2:2379,10.0.0.3:2379
  ttl: 10
  retry_timeout: 5
  loop_wait: 5

4. Add a health‑check sidecar that validates quorum before allowing failover

Deploy a small script that runs on each node and aborts Patroni’s failover if etcdctl endpoint status reports differing raft term values.

#!/usr/bin/env bash
# /usr/local/bin/etcd-quorum-check.sh
terms=$(etcdctl endpoint status -w json | jq -r '.[].Status.raftTerm' | sort -u | wc -l)
if [ "$terms" -ne 1 ]; then
  echo "Quorum mismatch: $terms different terms"
  exit 1
fi
exit 0

Configure Patroni to call this script via post_failover_script or as a pre‑failover guard.

Verify

1. Confirm cluster health after changes

docker exec etcd-node-1 etcdctl endpoint health --cluster
docker exec etcd-node-2 etcdctl member list -w table

Expected output:

etcdcluster-01: https://10.0.0.1:2379 is healthy: successfully pinged etcd cluster
etcdcluster-01: https://10.0.0.2:2379 is healthy: successfully pinged etcd cluster
etcdcluster-01: https://10.0.0.3:2379 is healthy: successfully pinged etcd cluster

2. Simulate overlay restart and watch election

# Restart overlay (example for Docker swarm)
docker network rm overlay_net
docker network create -d overlay overlay_net
# Wait 5 seconds, then inspect etcd leader
docker exec etcd-node-1 etcdctl endpoint status -w json | jq '.[].Status.leader'

The leader should change within the new election-timeout window, and all nodes should report the same raftTerm and revision.

3. Verify Patroni failover behavior

# Force primary failure
docker exec -it pg-primary pg_ctl -D /var/lib/postgresql/data stop
# Observe Patroni logs
docker logs patroni-node-2 | grep "Failover"

Only one node should promote to primary, and the log should contain “etcd quorum verified, proceeding with failover”.

Prevent

  • Network resilience: Use Docker’s --opt com.docker.network.driver.mtu=1500 and enable iptables health checks to detect overlay failures early.
  • Etcd tuning: Keep heartbeat-interval ≤ 50 ms and election-timeout ≤ 250 ms in HA clusters where network partitions can be sub‑second.
  • Snapshot policy: Set auto-compaction-retention to a reasonable window (e.g., “1h”) and maintain max-snapshots ≥ 5 to guarantee catch‑up capability.
  • Patroni guard scripts: Deploy quorum‑validation scripts as part of the failover pipeline to avoid split‑brain decisions.
  • Monitoring & alerts:
    • Alert on etcd_server_has_leader{job="etcd"} == 0.
    • Alert on etcd_server_leader_changes_seen_total spikes (> 2 per minute).
    • Alert on Patroni role=primary count > 1.

Related Topic Hub: Data Infrastructure Troubleshooting Hub

FAQ

  1. Why does the leader not step down immediately after the overlay goes down?
    Because the default election-timeout (1 s) is longer than the brief (<8 ms) network interruption, so the remaining nodes consider the leader reachable and do not trigger a new election.
  2. Can increasing max-snapshots alone fix the split‑brain?
    It prevents snapshot eviction but does not address the root cause. Without a shorter election timeout, the isolated leader can still diverge, and Patroni may still read stale keys.
  3. Is it safe to set heartbeat-interval to 20 ms in a three‑node cluster?
    Yes, provided the underlying network can sustain the increased traffic. Lower intervals improve failure detection but increase CPU and network load.
  4. How do I know if my Patroni configuration is using the correct etcd TTL?
    Run patronictl list --format json and verify the etcd_ttl field matches the value in patroni.yml. The TTL should be less than the expected maximum network outage duration.
  5. What metric should I monitor to catch divergent etcd revisions early?
    Watch etcd_debugging_mvcc_index_compaction_pause_duration_seconds and compare etcd_server_revision across members. A difference greater than 5 indicates a potential split.