Failure detection and leader election

Heartbeats, timeouts, phi accrual, leases, fencing, and the two leaders that both believed they were alone.

14 min read🌐 Distributed Systems

A node stops answering. Is it dead, or slow, or is the network between you and it broken while it carries on serving other clients? No message can tell those apart, and every design that needs to decide — to fail over, to elect a new leader, to give someone else the lock — is built on a guess made with a timeout. This lesson is how to make the guess well, and, since the guess will sometimes be wrong, how to make sure a wrong guess cannot corrupt anything.

Heartbeats, and what a missed one means

The basic detector: every node sends "I am alive" every T milliseconds, and a node that has not heard from a peer in k × T declares it suspect. T and k trade detection time against false positives. Heartbeats every second with a three-second timeout fail over in three seconds, and fire falsely on every GC pause longer than three seconds. The JVM course measured such pauses in the hundreds of milliseconds to seconds range for a large heap.

Kafka's consumer groups have exactly these three timeouts (session.timeout.ms, heartbeat.interval.ms, max.poll.interval.ms), and the Kafka course's "forty rebalances per deploy" was a detector tuned too tight.

A missed heartbeat is evidence, not a verdict: the sender may be paused, the network may have dropped a packet, the receiver may itself be overloaded and processing heartbeats late. The verdict — and the action — should need more than one.

Suspicion: phi accrual

A fixed timeout treats a heartbeat that is one millisecond late the same as one that is ten seconds late.

The phi accrual failure detector (Hayashibara; used by Cassandra and Akka) works differently. It keeps the recent history of heartbeat arrival intervals and computes, for the current silence, the probability that the node has failed given that history. That is expressed as φ, where each unit is a tenfold increase in confidence. A node whose heartbeats normally arrive every 1,000 ± 50 ms has a low φ after 1,100 ms of silence, and a high one after 3,000 ms.

The application picks a threshold (φ = 8 is Cassandra's default). It gets a detector that adapts to the network's actual behaviour: tolerant on a jittery link, quick on a steady one.

Whatever the detector, the output is suspicion, a level, and different actions want different levels:

  • Stop routing new requests to a suspect node at a low φ. It is cheap to be wrong.
  • Fail over its leadership at a high φ. It is expensive to be wrong.
  • Remove it from the cluster only on an operator's say, or at a very high φ.

Leases: permission with an expiry

A lease is a lock with a deadline: the holder may act as the leader (or own the partition, or hold the row) until time t, and must renew before then or stop. The lock service — ZooKeeper, etcd, a database row with an expiry, the Redis course's SET NX PX — grants it, and if the holder dies the lease simply expires and someone else can take it, with no detector needed beyond the clock.

The clocks lesson is where this gets dangerous. The lease's expiry is measured by the grantor's clock, and the holder measures it by its own. Between "I still hold the lease" on the holder and "the lease has expired" at the grantor lies clock skew, plus a GC pause, plus a network delay.

The scenario that has happened in production many times: the holder checks the lease (valid), pauses for eight seconds in a stop-the-world collection, resumes, and writes. During the pause, the lease expired, and a new holder was granted it and also wrote. Two leaders, both correct by their own clock.

Shortening the lease makes this more frequent. Lengthening it makes failover slower. Neither fixes it.

Fencing tokens: making the stale holder harmless

The fix is not a better clock but a fencing token: every grant of the lease comes with a number that increases monotonically — 33, then 34 — and every write the holder makes to a downstream resource carries it. The resource (the database, the storage service, the queue) remembers the highest token it has seen and rejects any write with a lower one. The paused holder resumes and writes with token 33; the resource has seen 34 from the new holder; the write is refused. The stale leader is not detected; it is made unable to do harm.

java
// on the resource side, the check that makes the lease safe
void write(Write w, long token) {
    if (token < highestSeen) throw new StaleLeaderException(token, highestSeen);   // an old holder
    highestSeen = token;
    apply(w);
}

This is the same mechanism as the JPA course's optimistic lock (@Version is a fencing token on a row), the Kafka course's producer epoch and the idempotent-producer sequence, and ZooKeeper's zxid. The Redis course's lock lesson made this argument against Redlock: a lock whose holder cannot present a fencing token to the resources it protects is a lock that is safe only until the first pause. When the downstream cannot check a token — a third-party API, an email send — the lease protects nothing there, and the idempotency lesson's keys are what stop the double effect instead.

Leader election

Many systems need one node to coordinate: to assign partitions, to run the scheduler, to be the single writer. Election chooses it. The honest way is to not write it yourself. Use a lease in etcd or ZooKeeper (Kubernetes's Lease object and the leaderelection library, Spring Integration's LockRegistryLeaderInitiator), or a database row with SELECT ... FOR UPDATE and an expiry. "Leader" means "holds the lease", and every leader action carries the token.

Underneath the lock service is a consensus protocol, Raft, which the system-design course's consensus lesson explained. It keeps a majority in agreement about who holds what, and that is the part you should not reimplement. The bully algorithm and its cousins from the textbook elect a leader without agreement about when the old one stopped, which is the split brain below.

The behaviours the elected code must have:

  • Renew the lease well before it expires (a third of the lease length is common).
  • On a failed renewal, stop leading immediately: cancel the scheduler and stop accepting the writes, rather than continuing until told otherwise.
  • Treat "I am the leader" as a claim checked at every action (with the token), not a flag set once.

Split brain, and the two leaders

Split brain is two nodes each believing it is the sole leader: a partition separates them, each side's detector declares the other dead, each elects itself. Both serve writes, the partition heals, and the data has diverged in a way no automatic merge can fix. The defences, in order of strength:

  • A majority. Leadership requires a lease from a quorum of the lock service's nodes; in a partition, at most one side has a majority, and the other side's lease requests fail. This is why etcd and ZooKeeper run with three or five nodes and why a two-node cluster cannot be made safe.
  • Fencing tokens at the resources, so that even if both sides believe they lead, only the newer token's writes land.
  • Stopping when unsure: a leader that cannot renew its lease stops leading, and a node that cannot reach the quorum stops serving writes (the CAP lesson's choice of consistency over availability, made explicit per operation). Availability during a partition is bought only by accepting divergence, and that is a product decision, not a default.
  • STONITH ("shoot the other node in the head"), in the physical world: a fencing device that powers off the old leader before the new one starts. It is the same idea as the token, applied to the whole machine.

The thing an operator most needs to know: a split brain that was survived leaves two histories, and the recovery is a human comparing them. Design so that it cannot happen (majority plus tokens) rather than so that it can be repaired.

Under the hood: what φ actually computes, and why a fixed timeout is structurally unable to do the same job

The earlier section named phi accrual and what it is for; this is the mechanism, and the reason a fixed timeout cannot be tuned into doing the same thing no matter how carefully you pick the number.

A fixed timeout has exactly one bit of output. At any instant it says either "not yet suspect" or "suspect". That is the entire vocabulary. So one timeout value has to be short enough to fail over quickly, and long enough not to fire on a slow GC pause or a jittery link, at the same time.

Those two goals trade directly against each other. A single number cannot serve both a use that wants to be cautious (evicting a node from the cluster) and one that wants to be quick (routing a request away from a node that might be struggling). Either the eviction is too trigger-happy or the routing is too slow to react, because both are reading the same one bit.

Phi accrual replaces that one bit with a real number, computed from the detector's own recent history rather than a value someone guessed at design time.

Concretely, the detector records the intervals between successive heartbeats it has actually received from a node, and treats those samples as an estimate of that node's normal arrival pattern. Hayashibara's original formulation approximates the inter-arrival times as normally distributed, tracking a running mean μ and variance σ². Later refinements use the empirical sample distribution directly, since real inter-arrival times tend to be skewed rather than symmetric.

Given how long it has now been since the last heartbeat, t, the detector computes P_later(t), the probability (under that history) that a heartbeat would still arrive after being this late, and reports

plaintext
φ(t) = -log10(P_later(t))

so φ = 1 means "an event this rare happens about one time in ten", φ = 2 means "one time in a hundred", and so on. Each additional unit is a tenfold drop in the probability that the silence is still normal.

Crucially, φ is computed continuously from one running history, and it is the consumer of that number who picks a threshold: a low φ for "stop routing new work here", a high φ for "call an election". Both come from the same detector instance. A fixed timeout cannot offer that, because it only ever has the one bit to give every consumer.

The practical upshot:

  • A network that is normally steady (heartbeats every 1,000 ms ± 20 ms) produces a fast-rising φ the moment it goes quiet, because a 500 ms silence is already many standard deviations outside its history.
  • A network that is normally jittery (1,000 ms ± 400 ms) produces a slow-rising φ for the same 500 ms silence, because that history says 500 ms late is unremarkable.

A single fixed timeout tuned for the jittery link would be dangerously slow on the steady one, and a timeout tuned for the steady link would fire constantly on the jittery one. Phi accrual does not eliminate that underlying trade-off between speed and false positives. But it lets each network's own behaviour set where the trade-off lands, instead of one hand-picked constant doing it for every network at once.

Try it yourself

Reason about two nodes with the same silence and different histories

Node A's heartbeats have arrived every 1,000 ms ± 20 ms for the last hour. Node B's heartbeats have arrived every 1,000 ms ± 400 ms for the same hour — same average, much more jitter. Both have now been silent for 2,200 ms. A fixed 2-second timeout has already fired identically for both. Reason through how a phi-accrual detector would differ, and why that difference is the right call rather than an inconsistency.

Why treating the two nodes identically would be the actual bug

A phi-accrual detector would report a much higher φ for node A than for node B at the same 2,200 ms of silence. For A, 2,200 ms is a huge number of standard deviations past its tight, predictable history: silence this long has essentially never happened. For B, it is a comparatively ordinary late arrival against its wide, jittery history, which has plenty of gaps well over a second.

A fixed timeout cannot make this distinction at all. It only knows "2,200 ms have passed", not "how surprising is 2,200 ms for this node", so it fires identically for both. That is exactly backwards: A's silence is the stronger evidence of a real failure, and B's is comparatively weak evidence that the network is merely doing what it always does.

Treating them the same either makes the detector too slow to catch A's genuine failure (if tuned loose enough not to false-positive on B), or too quick to false-positive on B (if tuned tight enough to catch A fast). That is the exact trade-off a single fixed number cannot escape, and the reason the earlier section calls this a structural limitation rather than a tuning problem.

Misconceptions

  • "Phi accrual eliminates false positives." It does not eliminate the underlying trade-off between fast detection and false positives. It makes the trade-off adaptive per node instead of fixed globally, and lets different consumers of the same detector pick different points on that trade-off. A node whose network genuinely degrades will still, eventually, cross even a well-calibrated threshold while merely being slow.
  • "A longer timeout is always the safer choice." A longer timeout only shifts which mistake you are more likely to make. It makes false suspicion rarer, at the direct cost of making every correct failure detection slower. "Safer" depends entirely on which error costs more for the action in question: evicting a healthy node from a cluster, or leaving a dead leader in place a few seconds longer.

Sources

  • Naohiro Hayashibara, Xavier Défago, Rami Yared and Takuya Katayama, "The φ Accrual Failure Detector" (2004) — the detector this section describes.
  • Apache Cassandra documentation — phi_convict_threshold and its gossip-based failure detection.
  • Martin Kleppmann, Designing Data-Intensive Applications — chapter 8 covers the impossibility of reliably distinguishing a slow node from a dead one over an asynchronous network.
Progress is saved on this device and to your account when signed in.