Every distributed system has to answer two questions continuously: which nodes are alive right now, and how does everyone find out when that changes? Failure detectors answer the first with heartbeats, timeouts and suspicion levels; gossip protocols answer the second by spreading news the way rumors and epidemics spread, reaching thousands of nodes in a handful of rounds with no central coordinator. Cassandra, Consul, Serf, Redis Cluster and the original Dynamo are all built on these ideas.
Think of it like
Office rumors and the colleague who stopped answering
You can't tell whether a colleague who hasn't replied for an hour is sick, in a long meeting, or just ignoring chat. Waiting longer makes you more sure but slower to react; giving up early sometimes means you were wrong. Before telling everyone they're out, you ask two other people to try reaching them. And once you do tell people, you don't email the whole company: you tell a few colleagues, each of them tells a few more, and by lunch the whole floor knows.
Why failure detection is hard
In an asynchronous network a crashed node, a slow node and a node behind a broken link all look exactly the same: silence. There is no message that says "I have crashed". A failure detector can only observe that expected messages haven't arrived and turn that into a guess. This is why a perfect failure detector is impossible in a real network, and why every practical one trades speed against accuracy.
- Completeness
- Every node that really crashes is eventually suspected by every correct node. Easy to get: just suspect anyone who stays silent long enough.
- Accuracy
- Correct nodes are not suspected. Impossible to guarantee in an asynchronous network; the realistic goal is a low mistake rate.
- Detection time
- How long after a crash until the failure is noticed. Shorter is better for availability.
- False positive
- Declaring a healthy node dead, for example during a GC pause or a dropped packet. Triggers needless failovers, data movement and sometimes split brain.
- Membership list
- Each node's local view of the cluster: who exists, at what address, and in which state (alive, suspect, dead, left).
Heartbeats and timeouts
The basic mechanism is a heartbeat: a node sends "I'm alive" every interval (push), or a monitor pings it and waits for a reply (pull). If nothing arrives within a timeout, the node is suspected. The question is who watches whom, because that decides how the cost grows with the cluster.
Central monitor
- Every node heartbeats to one coordinator (or a small replicated group)
- O(N) messages per interval, simple to reason about
- The monitor is a bottleneck and a single point of failure unless replicated
- Examples: Kubernetes node leases, ZooKeeper sessions, a load balancer's health checks
All-to-all heartbeats
- Every node heartbeats to every other node
- Fast, independent detection everywhere
- O(N²) messages per interval: 1,000 nodes means about a million messages per second
- Only practical for small clusters
Gossip-based (SWIM, Cassandra)
- Each node probes or gossips with a few random peers per interval
- O(N) messages in total, constant load per node
- No central component; news spreads in O(log N) rounds
- Membership views are eventually consistent, not instantly identical
Phi accrual failure detectors
A fixed timeout is a binary guess that ignores how the network actually behaves. The phi accrual detector (Hayashibara et al., 2004) instead outputs a continuous suspicion level φ. It records the intervals between recent heartbeats, fits a distribution to them, and asks: given how heartbeats usually arrive, how unlikely is it that we have heard nothing for this long?
- 1
Sample
On every heartbeat, store the time since the previous one in a sliding window (often the last 1,000 intervals).
- 2
Model
Estimate the mean and standard deviation. Akka fits a normal distribution; Cassandra uses an exponential model, so φ grows linearly with the silence divided by the mean interval.
- 3
Evaluate
At any moment, compute φ from the time since the last heartbeat. Right after a heartbeat φ is near 0; it climbs the longer the silence lasts.
- 4
Decide
Compare φ with a threshold. Cassandra's
phi_convict_thresholddefaults to 8; raising it (10 to 12 is common on cloud networks) trades slower detection for fewer false convictions.
The payoff is adaptivity. On a calm LAN with steady 1 s heartbeats, a 3 s silence is shocking and φ shoots up. On a jittery cross-region link where intervals already vary between 0.5 s and 3 s, the same silence is unremarkable and φ stays low. One threshold works across both, and different actions can use different thresholds: stop routing reads at φ = 5, evict from the cluster at φ = 12.
| Silence after steady 1 s heartbeats (σ = 200 ms) | φ (normal model) | Chance the node is actually fine |
|---|---|---|
| 1.0 s | 0.3 | 50% |
| 1.5 s | 2.2 | about 0.6% |
| 2.0 s | 6.5 | about 3 in 10 million |
| 3.0 s | 23 | effectively zero |
SWIM: scalable membership with indirect probes
SWIM (Das, Gupta and Motivala, 2002) is the protocol behind HashiCorp's memberlist library, which powers Serf and Consul's gossip layer. It separates two jobs: failure detection by random probing, and dissemination of membership changes by piggybacking them on the probe traffic. Each member does a constant amount of work per protocol period, however large the cluster.
Without the suspect state, a node that is merely slow for a moment gets evicted, rejoins, gets evicted again, and the cluster churns. Suspicion gives a healthy node a window to refute the accusation before anyone acts on it. HashiCorp later added Lifeguard (2017): a node that notices it is itself missing acks and timers (a sign that it is the slow one) lengthens its own timeouts, and suspicion timeouts shrink as more members independently confirm a suspicion. Together these cut false positives substantially.
Probes per member per period
1
plus k ping-reqs only when a probe fails
Expected time to first detection
≈ 1.58 T
e / (e − 1) protocol periods, independent of N
Total network load
O(N)
versus O(N²) for all-to-all heartbeats
Rounds to spread an update
O(log N)
updates are piggybacked on probes
Gossip dissemination
Detecting a change is half the job; everyone else has to hear about it. Gossip (or epidemic) protocols, introduced by Demers et al. at Xerox PARC in 1987 for replicated databases, spread information the way infections do. In each round, every node that knows an update picks a few random peers (the fan-out) and tells them. The informed population roughly multiplies every round, so the whole cluster hears in O(log N) rounds while each node sends only a few messages.
Push
- Informed nodes send the update to random peers
- Fast while few nodes know: every message reaches someone new
- Slow at the end: most messages hit nodes that already know
- About log₂ N + ln N rounds with fan-out 1
Pull
- Every node asks a random peer "what's new?"
- Slow start: early on, almost every peer asked knows nothing
- Fast finish: the uninformed fraction roughly squares each round
- Good when updates are frequent, so pulls are rarely wasted
Push-pull
- Both sides exchange what they know in one contact
- Combines the fast start of push and the fast finish of pull
- About log₃ N + O(log log N) rounds with fan-out 1
- Cassandra's SYN/ACK/ACK2 and memberlist's periodic full-state sync
| Strategy | 100 nodes | 1,000 nodes | 10,000 nodes |
|---|---|---|---|
| Push, fan-out 1 | ≈ 12 rounds | ≈ 18 rounds | ≈ 24 rounds |
| Pull, fan-out 1 | ≈ 10 rounds | ≈ 14 rounds | ≈ 17 rounds |
| Push-pull, fan-out 1 | ≈ 6 rounds | ≈ 9 rounds | ≈ 12 rounds |
| Push, fan-out 3 | ≈ 6 rounds | ≈ 8 rounds | ≈ 11 rounds |
The simulation above shows this epidemic spread round by round. Notice that there is no single path to break: if a node dies mid-spread, the update still reaches everyone else through other random contacts. That redundancy is the point. The cost is that the same update reaches most nodes several times, so total traffic is O(N log N) messages per update rather than N.
Rumor mongering versus anti-entropy
- Rumor mongering spreads each new update as a "hot rumor" for a limited number of rounds, then stops. It is cheap, but with small probability a node never hears. memberlist retransmits each update
RetransmitMult × ⌈log₁₀(N + 1)⌉times (multiplier 4 by default), so the budget grows slowly with cluster size. - Anti-entropy periodically compares the full state with a random peer and fixes every difference. It is expensive per exchange but guarantees convergence. memberlist does a full push-pull state sync every 30 s on LAN defaults, which catches anything rumor mongering missed.
- Real systems run both: rumors for speed, anti-entropy as the safety net.
A gossip round in Cassandra
Cassandra gossips cluster metadata (status, tokens, schema version, load) rather than data. About once a second, each node's gossiper starts a round with a random live peer, sometimes also with an unreachable node (to notice recovery) and with a seed (to heal partitions and help newcomers). The exchange is a three-message push-pull handshake.
Membership state and incarnation numbers
Gossip delivers messages out of order and more than once, so stale news constantly arrives after fresh news. Every membership record therefore carries a version that only its owner can advance: the incarnation number in SWIM, or the (generation, heartbeat version) pair in Cassandra. Merging is then deterministic: a receiver keeps whichever record wins under fixed precedence rules, and every node converges to the same view regardless of arrival order.
| Incoming gossip | Current: Alive(j) | Current: Suspect(j) | Current: Dead(j) |
|---|---|---|---|
| Alive(i) | Apply if i > j | Apply if i > j (refutation) | Apply if i > j (node rejoined) |
| Suspect(i) | Apply if i ≥ j | Apply if i > j | Ignore |
| Dead(i) | Apply if i ≥ j | Apply if i ≥ j | Ignore (already dead) |
Anti-entropy for data, not just membership
The same epidemic idea keeps replicated data converging. Leaderless stores such as Cassandra and Riak run background anti-entropy in which pairs of replicas compare Merkle trees of their key ranges, descend only into subtrees whose hashes differ, and stream just the differing ranges. Matching roots prove gigabytes identical with a single hash comparison. The details, together with read repair and hinted handoff, are in Quorums & Leaderless Replication.
Gossiping membership
- Small records: status, address, tokens, versions
- Every node needs every record
- Full state fits in one message for thousands of nodes
- Runs every second or faster
Anti-entropy on data
- Gigabytes per replica
- Only the replicas of a range need to agree
- Merkle trees reduce comparison to the differing ranges
- Runs as scheduled repair (hours or days), often throttled
Real systems
| System | Failure detection | Dissemination | Notes |
|---|---|---|---|
| Cassandra / ScyllaDB | Phi accrual on gossip heartbeats, phi_convict_threshold 8 by default | Push-pull gossip, about once a second, with seeds | Generation + version per endpoint; gossip carries metadata, data repair uses Merkle trees |
| Consul / Serf (memberlist) | SWIM probes with indirect ping-req, suspicion, Lifeguard | Piggybacked gossip to 3 nodes every 200 ms (LAN) plus a 30 s full sync | Separate LAN and WAN gossip pools; Consul servers additionally run Raft for the catalog |
| Redis Cluster | Node timeout marks a peer PFAIL (possible failure) | Gossip on the cluster bus | PFAIL becomes FAIL once a majority of primaries report it, then a replica is promoted |
| Akka Cluster | Phi accrual, each node watched by a few others | Gossip until all members have seen the same state | The leader only acts after gossip convergence |
| Dynamo (2007 paper) | Local: a peer that doesn't respond is treated as unreachable | Each node gossips membership with a random peer every second | Seeds prevent logically partitioned rings; hinted handoff covers short failures |
| DynamoDB | Per-partition Multi-Paxos leader that holds a lease | Request routers find partition leaders through an internal metadata service | A follower that loses the leader first asks other replicas whether they can reach it before calling an election (the 2022 DynamoDB paper) |
Implementation
Tracks heartbeat intervals and turns the current silence into a suspicion level. Production versions keep running sums instead of re-scanning the window, and always use a monotonic clock.
import math
from collections import deque
class PhiAccrualDetector:
"""Phi accrual failure detector with a normal model of heartbeat intervals."""
def __init__(self, window: int = 1000, min_std_ms: float = 100.0, acceptable_pause_ms: float = 0.0):
self.intervals: deque[float] = deque(maxlen=window)
self.last: float | None = None
self.min_std_ms = min_std_ms
self.acceptable_pause_ms = acceptable_pause_ms
def heartbeat(self, now_ms: float) -> None:
"""Record a heartbeat; pass a monotonic reading such as time.monotonic() * 1000."""
if self.last is not None:
self.intervals.append(now_ms - self.last)
self.last = now_ms
def phi(self, now_ms: float) -> float:
if self.last is None or not self.intervals:
return 0.0
n = len(self.intervals)
mean = sum(self.intervals) / n
std = max(math.sqrt(sum((x - mean) ** 2 for x in self.intervals) / n), self.min_std_ms)
y = (now_ms - self.last - mean - self.acceptable_pause_ms) / std
p_later = 0.5 * math.erfc(y / math.sqrt(2)) # 1 - normal CDF
return -math.log10(max(p_later, 1e-300))
def is_available(self, now_ms: float, threshold: float = 8.0) -> bool:
return self.phi(now_ms) < threshold
# Steady heartbeats every 1 s, then silence
d = PhiAccrualDetector(min_std_ms=200)
for t in range(0, 10_000, 1000):
d.heartbeat(float(t))
for silence in (1000, 1500, 2000, 3000):
print(silence, round(d.phi(9000 + silence), 2)) # 0.3, 2.21, 6.54, 23.12Key takeaways
- A crashed node and a slow one look identical, so failure detectors only suspect; every timeout trades detection time against false positives.
- All-to-all heartbeats cost O(N²); SWIM-style random probing keeps per-node load constant and total load O(N).
- Indirect probes (ping-req) and a suspect state with refutation stop one bad link or GC pause from evicting a healthy node.
- Phi accrual detectors adapt to observed heartbeat jitter and output a suspicion level instead of a yes/no answer.
- Gossip spreads updates to N nodes in O(log N) rounds; push-pull is fastest, and anti-entropy guarantees eventual convergence.
- Incarnation numbers (or generation + version) let nodes merge out-of-order gossip deterministically and refute stale accusations.
Common pitfalls
- Setting aggressive timeouts on cloud networks, then fighting constant false failovers during GC pauses and noisy-neighbor spikes.
- Measuring heartbeat intervals with the wall clock, so an NTP adjustment makes every node look dead (or alive) at once.
- Treating a gossip failure detector as authoritative for leadership or locks; suspicion is not agreement, so use consensus or fencing tokens.
- Deleting dead members immediately, letting delayed gossip resurrect them as zombies.
- Forgetting that membership views are eventually consistent: two nodes can briefly disagree about who is in the cluster.
Interview tips
- Quantify: all-to-all is O(N²) messages per interval, SWIM is O(N), gossip needs about log N rounds; give a concrete number for 1,000 nodes.
- Explain the indirect probe with a concrete lossy-link scenario, then the suspect state with a GC pause.
- When a design has many stateless nodes plus a coordinator, say which component detects failures and what happens on a false positive.
Real-world applications
- Cassandra and ScyllaDB ring membership, token ownership and schema agreement.
- Consul and Serf cluster membership, plus Nomad's server gossip via memberlist.
- Redis Cluster failure detection and automatic replica promotion.
- Akka Cluster membership, which decides where actors and shards live.
- Bitcoin and other peer-to-peer networks propagating transactions and blocks by gossip.
Test yourself
Why does SWIM ask other members to probe a node (ping-req) before suspecting it?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.