Gossip and Failure Detection

How nodes in a large cluster figure out who is alive and spread information without a central coordinator.

What is it?

In a cluster of hundreds or thousands of nodes, everyone needs a rough answer to two questions: who is in the cluster (membership) and who is alive (failure detection). A central server answering these becomes a bottleneck and a single point of failure, and having every node ping every other node costs O(N²) messages.

Failure detection is fundamentally uncertain. Over a network you can't distinguish a crashed node from a slow one or a lost message. A failure detector is therefore a guess that trades two errors:

  • Detection time: how long a dead node goes unnoticed.
  • False positives: how often a healthy but slow node is declared dead.

Gossip (or epidemic) protocols spread information the way rumours spread: every node periodically shares what it knows with a few random peers, who pass it on. Information reaches the whole cluster in about O(log N) rounds with no central coordinator, and keeps working as nodes come and go.

Explain like I'm 10

Gossip is office news: you tell two coworkers at the coffee machine, they each tell two more, and by lunch everybody knows, without a company-wide email. Failure detection is noticing a coworker hasn't replied: after five minutes you wonder, after a day you assume they're out, and asking a colleague to check helps you avoid a false alarm.

Examples

Simple heartbeat timeout detector

const lastHeartbeatAt = new Map<string, number>(); // nodeId -> ms timestamp
const FAILURE_TIMEOUT_MS = 5_000;

function onHeartbeat(nodeId: string): void {
  lastHeartbeatAt.set(nodeId, Date.now());
}

function suspectedNodes(now = Date.now()): string[] {
  return [...lastHeartbeatAt]
    .filter(([, lastSeen]) => now - lastSeen > FAILURE_TIMEOUT_MS)
    .map(([nodeId]) => nodeId);
}

A fixed timeout is easy, but it's tuned for one network condition: too short gives false alarms during GC pauses or congestion, too long delays failover.

Phi-accrual detector (idea)

// Track recent inter-arrival times of heartbeats from one node,
// model them (e.g. as a normal distribution), and compute how surprising
// the current silence is.
function phi(millisSinceLastHeartbeat: number, history: number[]): number {
  const mean = average(history);
  const stdDev = Math.max(standardDeviation(history), MIN_STD_DEV_MS);
  // Probability a heartbeat would arrive even later than this.
  const probabilityLater = 1 - normalCdf(millisSinceLastHeartbeat, mean, stdDev);
  return -Math.log10(probabilityLater);
}

// phi = 1 → ~10% chance we're wrong to suspect it
// phi = 2 → ~1%;  phi = 8 → ~0.000001%
// Cassandra's default conviction threshold (phi_convict_threshold) is 8.
const isSuspected = phi(elapsed, history) > 8;

Instead of a yes/no timeout, the detector outputs a suspicion level that adapts to how jittery that particular link normally is.

How it works

Heartbeats and timeouts. Each node sends periodic "I'm alive" messages (push) or is polled (pull). If nothing arrives within a timeout, it's suspected. Choosing the timeout is the whole game; the right value depends on network jitter, GC pauses and load.

Phi-accrual failure detector (Hayashibara et al., 2004). Rather than a boolean, it outputs phi, a continuously rising suspicion level computed from the history of heartbeat inter-arrival times: phi = -log10(probability that the next heartbeat arrives later than now). Applications pick a threshold. Because it learns the normal distribution of arrivals, a link that's usually jittery needs a longer silence before phi gets high. Cassandra and Akka use it.

Gossip / epidemic dissemination. Every gossip interval (say, 1 s), each node picks one or a few random peers and exchanges state:

- Push: send my updates. Pull: ask for theirs. Push-pull does both and converges fastest. - Each piece of state carries a version (e.g. a heartbeat counter plus a generation number that changes on restart), so newer state replaces older and duplicates are harmless. - Because the number of informed nodes roughly doubles each round, an update reaches all N nodes in about O(log N) rounds with high probability, and per-node load stays constant as the cluster grows.

Cassandra gossips endpoint state (heartbeat version, status, tokens, load) this way, feeding the phi detector with the observed heartbeat version updates.

SWIM (Das, Gupta and Motivala, 2002) separates failure detection from dissemination:

1. Every protocol period, node M pings one random member J. 2. If J doesn't ack in time, M asks k other members to ping J indirectly (ping-req). If any of them gets an ack, J is fine and the problem was likely the path between M and J. 3. Otherwise J is marked suspect, not dead. J can refute the suspicion by gossiping a higher incarnation number. If it doesn't within a timeout, J is declared dead. 4. Membership changes (join, suspect, alive, dead) are piggybacked on the ping and ack messages, so dissemination costs no extra messages.

Load per node is constant, and detection time doesn't grow with cluster size. HashiCorp's memberlist library (used by Consul and Serf) implements SWIM plus "Lifeguard" extensions that reduce false positives when the detecting node is the one that's slow.

Membership. Gossip-based membership is eventually consistent: nodes can briefly disagree about who's in the cluster. That's fine for routing hints, but decisions that must be unique (who owns a lease, who is leader) belong in a consensus system.

Gossip spreading (each node tells 1 random peer per round)

  round 0:  ●○○○○○○○○○○○○○○○      1 knows
  round 1:  ●●○○○○○○○○○○○○○○      2
  round 2:  ●●●●○○○○○○○○○○○○      4
  round 3:  ●●●●●●●●○○○○○○○○      8
  round 4:  ●●●●●●●●●●●●●●●○     ~all   (≈ log2 N rounds, plus a tail)

SWIM probe

  M ── ping ──► J          (no ack within timeout)
  M ── ping-req(J) ──► K1 ── ping ──► J
  M ── ping-req(J) ──► K2 ── ping ──► J
     any ack relayed back to M → J alive
     none → J "suspect" → (no refutation) → J "dead", gossiped to all

Why does it exist?

Large clusters can't afford a central membership server or all-to-all heartbeats. Gossip scales to thousands of nodes, has no single point of failure, and tolerates message loss by repetition. Adaptive detectors like phi-accrual and SWIM's indirect probing cut false positives, which matter because declaring a healthy node dead triggers expensive rebalancing, failovers and data streaming.

When to use it

- Peer-to-peer databases and caches (Cassandra, ScyllaDB, Riak) for membership, ring/token ownership and load info. - Service meshes and discovery agents (Consul, Serf) to track node health across many hosts. - Spreading low-stakes, eventually consistent metadata: config hints, load stats, schema versions. - Any failure detector that must adapt to variable latency: prefer phi-accrual or SWIM-style probing over a fixed timeout.

When not to use it

- Small clusters (a handful of nodes) where simple heartbeats to a coordinator or a load balancer's health checks are enough. - Decisions requiring agreement: leader election, lock ownership, exactly-one assignment. Gossip disseminates; it doesn't agree. Use consensus (etcd, ZooKeeper). - Latency-critical propagation with strict deadlines; gossip converges probabilistically, with a tail.

Common mistakes

  • Treating a timeout as proof of death. It only means 'not heard from yet', so anything acting on it (failover, lock release) must handle the node coming back.

  • Using an aggressive fixed timeout, so GC pauses or brief congestion trigger false failovers and rebalancing storms.

  • Using gossip-based membership to pick a unique leader or owner, then getting two owners while views disagree.

  • Not versioning gossiped state (heartbeat counters, generation numbers on restart), so stale information overwrites fresh information.

  • Having every node health-check every other node directly, which is O(N²) traffic and collapses at scale.

Practice exercises

  1. Easy:

    Explain why a node that stops sending heartbeats might still be alive. List three real causes.

  2. Medium:

    In a 1,000-node cluster where each node gossips to 2 random peers per second, roughly how many rounds until a new fact reaches everyone? Explain why per-node load doesn't grow with cluster size.

  3. Hard:

    Compare a fixed-timeout detector, phi-accrual and SWIM on detection time, false-positive rate and network cost. Which would you pick for a 2,000-node cache cluster in a noisy cloud network, and why?

Interview questions

What does a failure detector do?

It decides which nodes to suspect have failed, usually from missing heartbeats or probe responses. Because networks are asynchronous, it can only suspect, never know for sure.

What is the core trade-off in choosing a heartbeat timeout?

Short timeouts detect failures fast but declare healthy, momentarily slow nodes dead (false positives). Long timeouts avoid false alarms but leave real failures unnoticed longer.

What is gossip in distributed systems?

A protocol where each node periodically exchanges state with a few randomly chosen peers. Information spreads like an epidemic, reaching all nodes in about O(log N) rounds with constant per-node load and no coordinator.

Push vs pull vs push-pull gossip?

Push sends my state to a peer; pull asks a peer for theirs; push-pull exchanges both ways. Push spreads fast early, pull finishes the last uninformed nodes faster, and push-pull combines both for the quickest convergence.

How does a phi-accrual detector work?

It records heartbeat inter-arrival times, models their distribution, and computes phi = -log10(probability the next heartbeat arrives later than the current silence). The application suspects a node once phi crosses a threshold, so detection adapts to each link's normal jitter.

What does SWIM add over plain heartbeating?

Randomized probing with constant per-node load, indirect pings through k other members to rule out a bad link, a suspect state that nodes can refute with incarnation numbers, and membership updates piggybacked on probe messages instead of separate broadcasts.

Why does SWIM use indirect probes?

A missed ack might be caused by the path between the prober and target, not the target itself. Asking several other members to probe it reduces false positives caused by a single bad link or an overloaded prober.

Why do gossiped records carry version or generation numbers?

Messages arrive out of order and get repeated. Versions let nodes keep only the newest state; a generation number that changes on restart lets a rebooted node's state supersede its pre-crash entries.

Can you use gossip-based membership to elect a leader?

Not safely. Gossip views are eventually consistent, so two nodes can simultaneously believe they're the lowest-id live node. Use a consensus system for leader election, and gossip for disseminating hints.

A cluster keeps flapping: nodes are declared dead and rejoin every few minutes during peak load. How do you debug and fix it?

Correlate flaps with GC pauses, CPU saturation and network drops on both the suspected and the detecting nodes. Fixes: raise the conviction threshold or timeout, use adaptive detection (phi-accrual, SWIM with Lifeguard), send heartbeats on a dedicated, prioritized thread, and add hysteresis so rejoin and rebalancing aren't triggered by a single blip.