DS·77
Coordination
The building blocks for nodes that must cooperate: heartbeats and failure detection (fixed timeouts, phi accrual, SWIM gossip), membership, service discovery (DNS, registries, Kubernetes, client- versus server-side), leader election, distributed locks and why they need fencing tokens (the Redlock debate), leases, and the coordination services that provide them (etcd, ZooKeeper, Consul), with recipes in Go, Java, Python, Rust and Elixir.
Start here: leaders, locks and leases
Why services need coordination
Some jobs must be done by exactly one instance at a time: the nightly invoice run, the consumer that owns a shard, the primary database. Some resources need exclusive access: editing invoice 42, rotating a key. Running several copies of a service for availability creates the question which one is in charge right now? Answering it with your own heartbeats and timeouts is easy to get subtly wrong; answering it with a consensus store (etcd, ZooKeeper, Consul) gets you a linearizable "who holds it" plus automatic release when the holder dies.
Leader election with a lease
Each candidate creates /election/report-job only if it doesn't exist, attached to a lease with a 2-second TTL, and renews the lease every 0.5 s while it leads:
lid = e.grant(2)
won, _ = e.acquire("/election/report-job", s.name_, lid) # txn: create only if create_revision == 0
while won: e.keepalive(lid); time.sleep(0.5)
1) two workers campaign for the 'report-job' leadership (lease TTL 2 s, renewed every 0.5 s)
leader: worker-a | worker-a leading? True | worker-b leading? False
worker-a crashed; worker-b took over after 2.1 s (the lease had to expire)
The lease is the failure detector: when worker-a stopped renewing, etcd deleted the key after the TTL and worker-b's next attempt won. The TTL is a trade-off: shorter means faster failover, but a leader that's merely slow (a GC pause, a network blip) loses leadership while still running.
The lock that wasn't
A lease-based lock has a famous trap. Client A holds the lock; A then pauses for longer than its lease (a stop-the-world GC, a VM migration, swapping). The lease expires, B gets the lock and writes. A wakes up, still believing it holds the lock, and writes too:
2) without fencing: A holds the lock (lease 2 s), token 16925; A pauses 3.5 s (a long GC pause)
B acquires the lock: True, token 16928; B's write accepted (token 16928)
A wakes up, still believes it holds the lock: A's write accepted (token 16925); final value written by A
2) with fencing: A holds the lock (lease 2 s), token 16930; A pauses 3.5 s (a long GC pause)
B acquires the lock: True, token 16932; B's write accepted (token 16932)
A wakes up, still believes it holds the lock: A's write REJECTED (token 16930 < 16932); final value written by B
No lock service can stop a paused process from acting on stale beliefs: A can't check the lock and write atomically. The fix is a fencing token: a number that increases with every grant (etcd's revision of the lock key is one), sent with every write, and checked by the storage, which rejects any token lower than one it has already seen. Martin Kleppmann's analysis of Redlock (2016) made this point famous: a lock is safe for correctness only if the protected resource checks fencing tokens; otherwise it's an optimisation that usually prevents duplicate work.
How deep to go in coordination
Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.
| Level | What you can do |
|---|---|
| L1 | Explain leader election, locks, leases and why coordination is risky |
| L2 | Use etcd/ZooKeeper/Consul recipes or Kubernetes Leases for election and locks |
| L3 | Explain failure detection trade-offs, fencing, membership and watch semantics |
| L4 | Diagnose split leadership, stale lock holders, lease flapping and herd effects |
| L5 | Decide what needs coordination in a design, and design fencing and ownership |
| L6 | Operate coordination services for a platform with SLOs, quotas and recovery plans |
Why coordination needs special care
Most of the time, distributed components should avoid coordinating, since coordination costs latency and availability (chapter 70). But some decisions must be agreed:
- Which node is the leader that runs the scheduler or owns a partition?
- Which nodes are alive and part of the cluster?
- Where is service X right now?
- Who may exclusively process job 42 or write file F?
- What's the current configuration?
All of these rest on two difficult foundations: detecting failure (which is never certain) and agreeing (consensus, chapter 72). The rule of thumb: use a proven coordination service for the hard part and keep its usage small.
Heartbeats and failure detection
Heartbeats and timeouts
A heartbeat is a periodic "I'm alive" message (push), or a periodic probe (pull, like a health check). If no heartbeat arrives within a timeout, the node is suspected dead.
Failure detectors are characterised by two properties (Chandra and Toueg, 1996):
- Completeness: every crashed node is eventually suspected.
- Accuracy: correct nodes aren't wrongly suspected.
In an asynchronous network you can't have perfect accuracy: a slow node or a slow network is indistinguishable from a dead node. Every timeout is a trade-off:
| Short timeout | Long timeout |
|---|---|
| Fast detection and recovery | Slow detection: longer outages |
| False positives during GC pauses, load spikes, network blips | Fewer false positives |
| False failovers cause churn, split-brain risk and thundering herds of reassignments | Safer, but stuck work waits longer |
Practical guidance:
- Set timeouts from measured heartbeat inter-arrival distributions (e.g. several times p99.9), not guesses.
- Require multiple missed heartbeats (e.g. 3) before suspecting.
- Separate liveness ("process is running") from readiness ("can serve traffic now") as Kubernetes does; failing readiness removes a pod from load balancing without killing it.
- Make heartbeats travel the same path as real work where possible, or a node can heartbeat happily while its request-processing thread is wedged.
Phi accrual failure detector
Instead of a binary alive/dead verdict, the phi (φ) accrual detector (Hayashibara et al., 2004) outputs a suspicion level that grows continuously with time since the last heartbeat, based on the observed distribution of inter-arrival times:
φ = −log₁₀(P(a heartbeat arrives later than now))
With φ = 1 the chance of a wrong suspicion is about 10%; φ = 3, about 0.1%; φ = 8, about 0.000001%. Applications choose their own threshold per decision. It adapts automatically to networks with variable latency. Used by Akka/Pekko Cluster (default threshold 8), Cassandra (phi_convict_threshold, default 8).
Gossip and SWIM
All-to-all heartbeating costs O(n²) messages. Gossip protocols spread information epidemically: each node periodically exchanges state with a few random peers, and information reaches all n nodes in O(log n) rounds.
SWIM (Das, Gupta and Motivala, 2002) is the standard scalable membership protocol:
- Each period, node A pings a random member B.
- If B doesn't ack in time, A asks k other members to ping B indirectly (ping-req). This avoids false suspicion due to a bad link between A and B specifically.
- If still no ack, B is marked suspect (not dead immediately); B can refute by gossiping an incremented incarnation number. After a suspicion timeout, B is declared dead.
- Membership changes are piggybacked on ping/ack messages: no separate broadcast.
Implementations: HashiCorp memberlist (Go; used by Consul, Nomad, Serf), Lifeguard extensions (adjusting timeouts by a node's own health), Cassandra and ScyllaDB gossip, Akka/Pekko Cluster gossip, Uber's Ringpop, Elixir/Erlang libcluster strategies plus :pg, and Kubernetes-native discovery replacing gossip in many deployments.
Membership and service discovery
Membership
A cluster needs a membership view: which nodes exist and are healthy. Two approaches:
- Gossip-based (eventually consistent): SWIM/memberlist, Cassandra ring state. Scales well; views may temporarily differ.
- Consensus-based (strongly consistent): membership stored in etcd/ZooKeeper or a Raft group's configuration. Every node sees the same view in the same order, which matters when membership determines ownership (which node owns which partition).
Service discovery
Clients must find healthy instances of a service whose addresses change constantly (autoscaling, deployments, failures).
| Pattern | How | Examples |
|---|---|---|
| DNS-based | Service name resolves to instance IPs (A/AAAA) or SRV records | Kubernetes Services (ClusterIP DNS), Consul DNS, AWS Cloud Map, CoreDNS |
| Server-side discovery | Client calls a stable virtual address; a load balancer or proxy routes to healthy instances | Kubernetes kube-proxy/ClusterIP, AWS ALB/NLB, service mesh sidecars (Envoy) |
| Client-side discovery | Client queries a registry for instances and load-balances itself | Consul, Eureka (Netflix, Spring Cloud), etcd-based registries, gRPC's xDS client-side balancing |
| Self-registration vs third-party registration | Instance registers itself with heartbeats, or the platform registers it (Kubernetes controllers, Registrator) | Kubernetes EndpointSlices are populated by the control plane |
Concerns:
- Staleness: DNS TTLs and client caches keep routing to dead instances; JVMs historically cached DNS forever (
networkaddress.cache.ttl). Pair discovery with health checks and outlier detection (eject instances that fail). - Registry availability: if the registry is down, clients should keep using the last known instance list (Eureka's self-preservation mode; Envoy keeps its last configuration).
- Graceful shutdown: deregister first (or fail readiness), wait for propagation, drain in-flight requests, then exit, or clients will hit closing instances (Vol. 6).
Leader election
Why and how
Many systems want exactly one node doing something: running a scheduler, compacting data, owning a partition, sending a daily report. Leader election chooses that node and replaces it on failure.
Approaches:
| Approach | How | Notes |
|---|---|---|
| Built into consensus | Raft/Paxos elect a leader for the replicated log | etcd, KRaft, CockroachDB ranges |
| Via a coordination service | Candidates race to create a key/node with a lease; the winner is leader; others watch for its deletion | etcd concurrency.Election, ZooKeeper ephemeral sequential znodes (Curator LeaderLatch/LeaderSelector), Consul sessions and KV locks |
| Kubernetes Lease objects | Candidates update a coordination.k8s.io/v1 Lease with holder identity and renew time; client-go's leaderelection package |
Controllers and operators use this; relies on timing and the API server |
| Database-based | Advisory locks (pg_try_advisory_lock), or a row updated with a lease expiry via compare-and-set |
Good when you already depend on the database; lock bound to the DB session |
| Bully / ring algorithms | Classic textbook algorithms (highest ID wins) | Assume reliable failure detection; rarely used in production |
The ZooKeeper recipe shows the pattern well:
- Each candidate creates an ephemeral sequential znode under
/election(/election/n_0000000007). Ephemeral nodes vanish when the client's session expires. - The candidate with the lowest sequence number is leader.
- Each other candidate watches only its predecessor (not the leader), avoiding a herd effect where everyone wakes when the leader dies.
Leader election isn't enough
Election gives you "at most one leader at a time, according to the coordination service". It doesn't guarantee that the old leader knows it's been replaced. A leader that pauses for a long GC, or is partitioned from the coordination service but not from storage, may keep acting. Hence fencing (below): every action a leader performs on shared resources must carry its epoch/term and be checked.
Distributed locks
What a lock needs
A distributed lock gives mutual exclusion across processes on different machines. Two purposes (Martin Kleppmann's distinction):
- Efficiency: avoid doing the same work twice (two nodes sending the same report). An occasional double execution is tolerable.
- Correctness: two holders would corrupt data (two writers to the same file, double-spending). It must never fail.
Every distributed lock has an expiry (otherwise a crashed holder blocks everyone forever), which makes it a lease. And expiry means a holder can lose the lock without knowing it:
Fencing tokens
The fix: the lock service returns a monotonically increasing token with each grant (etcd's revision or lease-associated revision, ZooKeeper's zxid or znode version, a Postgres sequence). The holder sends the token with every write to the protected resource, and the resource rejects tokens lower than the highest it has seen.
This moves the safety check to the resource, the only place that can enforce it. It requires that the resource can check tokens: databases (conditional writes, WHERE fence_token < $new), object stores with conditional writes, or a service you control. If the resource can't check tokens, the lock can only be used for efficiency, not correctness.
The Redlock debate
Redlock is Redis's proposed algorithm for distributed locks across N independent Redis masters (acquire on a majority within a validity time). In 2016, Martin Kleppmann argued it's unsafe for correctness: it depends on bounded clock drift, network delay and process pauses, and provides no fencing tokens; Antirez (Redis's creator) replied defending its assumptions. The practical consensus:
- A single Redis
SET key value NX PX 30000lock (release only if the value matches, via Lua) is fine for efficiency locks. - For correctness, use a consensus-based service (etcd, ZooKeeper, Consul) and fencing tokens, or avoid locks by designing with conditional writes or single-writer ownership.
// Go: etcd lock with a lease; use the lock key's creation revision as the fencing token
sess, _ := concurrency.NewSession(cli, concurrency.WithTTL(10)) // lease renewed by keepalive
defer sess.Close()
mu := concurrency.NewMutex(sess, "/locks/report-2026-10")
if err := mu.Lock(ctx); err != nil { return err }
defer mu.Unlock(context.Background())
fence := mu.Header().Revision // monotonically increasing across grants
_, err := db.Exec(ctx,
`UPDATE reports SET body = $1, fence = $2 WHERE id = $3 AND fence < $2`,
body, fence, reportID) // resource enforces the fence
select {
case <-sess.Done(): return errors.New("lease lost: stop work") // keepalive failed
default:
}
// Java: Apache Curator, leader election with LeaderSelector over ZooKeeper
LeaderSelector selector = new LeaderSelector(curator, "/election/scheduler",
new LeaderSelectorListenerAdapter() {
@Override public void takeLeadership(CuratorFramework client) throws Exception {
long epoch = client.checkExists().forPath("/election/scheduler").getCversion(); // fence source
runSchedulerUntilInterrupted(epoch); // return = relinquish leadership
}
});
selector.autoRequeue(); // rejoin the election after losing leadership
selector.start();
// Connection loss / session expiry interrupts takeLeadership: the listener must stop work promptly.
# Python: Redis lock for EFFICIENCY only (no fencing): SET NX PX plus safe release via Lua
import uuid, redis
r = redis.Redis()
RELEASE = r.register_script("""
if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) else return 0 end
""")
token = str(uuid.uuid4())
if r.set("lock:nightly-report", token, nx=True, px=60_000):
try:
generate_report() # a rare double run must be harmless
finally:
RELEASE(keys=["lock:nightly-report"], args=[token]) # never delete someone else's lock
// Rust: Postgres advisory lock for single-runner jobs (lock held while the session lives)
let mut conn = pool.acquire().await?;
let got: bool = sqlx::query_scalar("SELECT pg_try_advisory_lock($1)")
.bind(hash_key("billing-reconciler"))
.fetch_one(&mut *conn).await?;
if got {
reconcile(&mut conn).await?; // use the SAME connection; the lock dies with it
sqlx::query("SELECT pg_advisory_unlock($1)").bind(hash_key("billing-reconciler"))
.execute(&mut *conn).await?;
}
# Elixir: global registration as a cluster-wide singleton (efficiency-level; beware net splits)
case GenServer.start_link(Scheduler, [], name: {:global, :scheduler}) do
{:ok, pid} -> {:ok, pid} # we're the singleton
{:error, {:already_started, pid}} -> {:ok, pid}
end
# On netsplit heal, :global resolves name conflicts by killing one process.
# Libraries like Horde (CRDT-based) or Swarm distribute singletons; use fencing for correctness.
Leases
A lease is a lock with a time limit: the holder has rights until expiry and must renew to keep them. Leases are how distributed systems bound the damage of failed holders:
- Leader leases (Raft lease reads, chapter 72; Spanner's Paxos leader leases).
- Lock leases (etcd leases, ZooKeeper sessions, Consul sessions, Kubernetes Lease objects).
- Cache leases (Facebook's memcache leases against thundering herds and stale sets).
- File and object leases (HDFS, GFS chunk leases to a primary replica).
Rules for using leases safely:
- The holder must stop before the lease expires, by a safety margin that covers clock drift and processing time. Check remaining lease time before each action using a monotonic clock.
- Renew well before expiry (e.g. at 1/3 of TTL), but treat a failed renewal as lost leadership.
- A lease is only as safe as the assumption that pauses are shorter than the margin, which GC, VM migration, swapping and SIGSTOP can violate. So: leases for liveness, fencing tokens for safety.
Coordination services
etcd, ZooKeeper and Consul
| etcd | ZooKeeper | Consul | |
|---|---|---|---|
| Consensus | Raft | Zab (primary-backup atomic broadcast) | Raft |
| Data model | Flat key-value with revisions (MVCC), range queries | Hierarchical znodes (tree), small data | KV store + service catalog |
| Ephemeral state | Leases attached to keys | Ephemeral znodes bound to sessions | Sessions with TTL and health checks |
| Notifications | Watches on keys/prefixes from a revision (no missed events if within history) | One-shot watches (persistent watches since 3.6) | Blocking queries |
| Ordering token | Global revision, per-key mod/create revision | zxid, znode versions, sequential nodes | Raft index (ModifyIndex) |
| Reads | Linearizable by default; serializable optional | Sequentially consistent; sync() for latest |
default / consistent / stale |
| Typical users | Kubernetes, CoreDNS, Patroni, M3, Vitess | HBase, Solr, older Kafka, Hadoop, Curator users | Service mesh and discovery, Vault storage, Nomad |
| Client libraries | Go (clientv3, concurrency), jetcd (Java), etcd-client (Rust), python-etcd3 |
Curator (Java, recipes), kazoo (Python), zookeeper-go | Official Go API, many HTTP clients |
Practical guidance:
- Keep data small (etcd's default request limit is 1.5 MB and its recommended database size is a few GB; ZooKeeper znodes ≤ 1 MB). They're for coordination metadata, not application data.
- Run 3 or 5 members across failure domains; put them on fast disks (fsync latency is the write latency).
- Watch for watch storms and large fan-out: thousands of clients watching one key all wake at once.
- Most applications should use higher-level recipes (Curator, etcd
concurrency, client-go leader election) rather than raw primitives.
Coordination-avoiding alternatives
Often you can design coordination away:
- Partition ownership via consistent hashing or a partition assignment from Kafka consumer groups: each key has one owner without a lock.
- Conditional writes (compare-and-set on a version or ETag) instead of locks: optimistic concurrency at the resource.
- Idempotent work so that occasional duplicate execution is harmless (chapter 74).
- Database unique constraints and
SELECT … FOR UPDATE SKIP LOCKEDjob queues instead of distributed locks. - Actors with single activation (Orleans grains, Akka Cluster Sharding, Elixir with Horde): the runtime ensures one active instance per ID (usually with caveats during partitions).
Lab: elections, detectors, locks and watches
The 3-member etcd 3.6 cluster (members on 127.0.0.1–3) through its HTTP gateway, from Python. Experiment 2 is a simulation of a healthy sender with realistic pauses.
Experiment 1: failover time is the lease TTL
The leader stops renewing right after acquiring; a standby campaigns every 50 ms with a fresh lease. Three trials per TTL:
lease TTL 2 s: standby took over after 2.0, 2.5, 2.5 s
lease TTL 5 s: standby took over after 5.5, 5.5, 5.5 s
lease TTL 10 s: standby took over after 10.5, 10.5, 10.4 s
Failover took the TTL plus up to half a second: etcd checks for expired leases periodically, not at the exact instant. (etcd also enforces a minimum TTL derived from its election timeout: asking for 1 s gave 2 s.) A leader that shuts down cleanly should revoke its lease so the standby takes over immediately; only crashes should pay the TTL. Kubernetes' leader election for controllers uses a 15 s lease duration and 10 s renew deadline by default, choosing stability over speed.
Experiment 2: the failure detector's dilemma
A healthy node sends heartbeats every 100 ms for three simulated hours; now and then it stalls (a GC pause, CPU steal, swapping), with stall lengths drawn from a heavy-tailed distribution:
timeout 0.25 s: 42 false 'dead' verdicts; a real crash detected within 0.35 s
timeout 0.50 s: 11 false 'dead' verdicts; a real crash detected within 0.60 s
timeout 1.00 s: 4 false 'dead' verdicts; a real crash detected within 1.10 s
timeout 2.00 s: 1 false 'dead' verdicts; a real crash detected within 2.10 s
No timeout is both fast and never wrong: a slow node and a dead one look identical from outside. Every false verdict triggers a failover (and in a cluster, rebalancing), so too-aggressive detection causes outages of its own. Adaptive detectors such as the φ-accrual detector (used by Akka and Cassandra) learn the distribution of heartbeat intervals and report a suspicion level instead of a yes/no, letting each use choose its own threshold. SWIM-style protocols (Consul's Serf, memberlist) add indirect probes through other members before declaring a node dead.
Experiment 3: locks are not free
One client acquiring and releasing an etcd lock (grant lease, create-if-absent transaction, revoke):
139 per second
Each acquisition is three consensus round trips. That's fine for coarse locks (an hourly job, a shard's ownership) and far too slow for per-request locking. Lock coarse things, keep critical sections short, and prefer designs that partition ownership (each instance owns a set of shards) over locking each operation.
Experiment 4: watches push configuration
Five services watch /config/feature-x, connected to different members; one put changes it:
the change reached them after 4.0–9.2 ms
Watches stream every change in revision order, from any member, without polling; a watcher that reconnects can resume from the last revision it saw and miss nothing (unless that revision has been compacted, which it must then handle by re-reading the current state). This is how Kubernetes controllers learn about every object change, and how feature flags and service discovery propagate in milliseconds. Watch out for herd effects: a thousand watchers all reacting at once (for example, all trying to grab a lock that was just released) can overload the store; etcd's lock recipe has each waiter watch only the key just ahead of it.
Try it yourself
- Add a clean shutdown with
revoketo experiment 1 and measure failover. - Implement a φ-accrual detector over experiment 2's arrivals and choose φ for one false verdict per day.
- Implement fencing in PostgreSQL: a
fencing_tokencolumn withUPDATE … WHERE fencing_token <= $token. - Use etcd's built-in
concurrencypackage (Go) oretcdctl lockand compare its waiting behaviour with the herd of experiment 4.
Revision sheet: coordination
Key ideas
- Why careful: coordination is where partial failure, timing and process pauses meet; mistakes cause split brain and corrupted data.
- Failure detection: heartbeats and timeouts, the completeness/accuracy trade-off, φ-accrual, SWIM gossip with indirect probes.
- Membership and discovery: registries (Consul, etcd, ZooKeeper, Kubernetes Endpoints), health checks, gossip.
- Leader election: create-if-absent with a lease; ZooKeeper ephemeral sequential nodes; Kubernetes Lease objects; clean resignation.
- Distributed locks: for efficiency vs for correctness; fencing tokens checked by the resource; Redlock's timing assumptions.
- Leases: time-bounded ownership; renewal; clock assumptions; minimum TTLs.
- Coordination services: etcd (Raft, revisions, watches, leases, txns), ZooKeeper (Zab, znodes, sessions, watches), Consul (Raft + Serf); keep them small and low-churn.
- Avoiding coordination: partition ownership, idempotent operations, CRDTs, deterministic assignment (consistent hashing).
Numbers to remember
- Kubernetes leader election defaults: lease 15 s, renew deadline 10 s, retry 2 s.
- Lab: failover = TTL + ≤0.5 s; timeouts of 0.25/0.5/1/2 s gave 42/11/4/1 false verdicts in 3 hours; 139 lock cycles per second; watches delivered changes in 4–9 ms.
Pitfalls
- Locks for correctness without fencing.
- Lease TTLs shorter than realistic pauses.
- Fine-grained, per-request distributed locks.
- Leaders that never resign on shutdown.
- Watchers ignoring compaction or reconnect gaps.
- Thundering herds on lock release.
Glossary
- Lease: ownership that expires unless renewed.
- Fencing token: increasing number that lets resources reject stale holders.
- φ-accrual detector: outputs a suspicion level from heartbeat history.
- Ephemeral node: ZooKeeper node deleted when its session ends.
- Watch: subscription to changes on a key or prefix.
- Herd effect: many clients reacting to one event at once.