Skip to content

Gossip Protocols, Convergence & Failure Detection ​

"The algorithms are very simple and require few guarantees from the underlying communication system, yet they ensure that the effect of every update is eventually reflected in all replicas." — Demers, Greene, Hauser, Irish, Larson, Shenker, Sturgis, Swinehart, Terry, Epidemic Algorithms for Replicated Database Maintenance, PODC 1987 (Xerox PARC CSL-89-1)

Summary: Gossip (epidemic) protocols spread information by having every node talk to a few random peers each round; an update reaches N nodes in O(log N) rounds with constant work per node, and the same trick, combined with randomized probing, gives large clusters a membership list and a failure detector without a central server. Focus: Demers et al. anti-entropy and rumour mongering (push, pull, push-pull, counters, residue, death certificates), fan-out, interval and message complexity, heartbeat vs gossip-based failure detection, SWIM (ping, ping-req, indirect probe, suspicion, incarnation numbers, piggybacking, round-robin probing), Lifeguard, the phi accrual failure detector and its threshold, seeds and bootstrap, partial views (HyParView, Cyclon), gossip inside Cassandra, Redis Cluster, Riak, Dynamo, Consul, Serf and memberlist, tuning against false positives, security (gossip encryption, keyring rotation), observability (churn, convergence time), and when gossip is the wrong tool compared with etcd or ZooKeeper. Learning goal: Explain why a gossip protocol converges in O(log N) rounds, compute convergence time and suspicion timeouts for a real cluster from memberlist, Cassandra or Redis Cluster knobs, read a SWIM timeline (who suspected whom, who refuted with which incarnation), pick between gossip, a phi accrual detector and a central registry for a given system, and recognise when a problem needs consensus instead.

This chapter opens the Distributed Systems Primitives group. It builds on Consistency Models (gossip gives convergence, not linearizability) and CAP & PACELC (membership is an AP service). Its neighbours own the pieces it only names: Merkle Trees, Read Repair, Anti-Entropy & Tombstones owns how replicas compare large datasets cheaply, CRDTs owns values that merge without conflicts when gossiped, Vector Clocks owns causality, and Leader Election owns "exactly one". The consistent-hash ring that gossip distributes in Cassandra and Riak is in Consistent Hashing; service discovery as an architecture decision is in Service Discovery. This page owns dissemination, membership, failure detection, the numbers and the choice.

Page map ​

If you are looking forGo to
The whole page in four tablesEverything in one minute
Why not just broadcast, or ask a central serverWhy it exists
Xerox Clearinghouse, SWIM, Lifeguard, phi accrualWhere it comes from
Why log N roundsEpidemic dissemination and convergence
Push, pull, push-pullAnti-entropy
Hot rumours, counters, residueRumour mongering
Fan-out, interval, messages per nodeFan-out and message complexity
All-to-all heartbeats and why they stop scalingHeartbeat vs gossip-based detection
ping, ping-req, indirect probeSWIM probing
Suspect, alive, dead, incarnation numbersSuspicion and incarnation
How updates ride on probesPiggybacking
Slow nodes that accuse healthy onesLifeguard
A suspicion level instead of yes/noPhi accrual failure detector
How a new node finds the clusterSeeds, bootstrap and push/pull sync
Overlays for very large groupsPartial views: HyParView, Cyclon
Gossip in Cassandra, Redis Cluster, Riak, DynamoGossip for cluster state
Consul, Serf, memberlistThe HashiCorp stack
Deleting through gossipDeath certificates and tombstones
Encryption and key rotationSecurity
Churn, convergence time, flappingObservability
Gossip or etcd/ZooKeeperGossip vs centralised coordination
Every knob, every formula, every log lineMechanics
CodeGo, Laravel
Classic incidents and fixesSolving the classic problems
What to pickChoosing
Monolith to multi-regionIn architecture
Simulator runs with numbersLab
Wrong beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

Dissemination styles (Demers et al. 1987).

StyleWhat a node does each roundReliabilityCostWhere you meet it
Direct mailSends each new update to every other node onceLost mail is lostN-1 messages per update, at onceNaive broadcast, webhooks to every peer
Anti-entropyPicks a random peer and reconciles full state (push, pull or push-pull)Always convergesCompares state every round, so it runs rarelymemberlist push/pull every 30 s, Cassandra repair with Merkle trees, Dynamo membership
Rumour mongeringSpreads a "hot" update to random peers until it has hit k peers that already knewSmall residue may miss itAbout k+1 messages per node per updateSWIM piggybacking, Serf user events, Redis Cluster gossip sections

Failure detectors.

DetectorSignalLoad per nodeVerdictProducts
All-to-all heartbeatEvery node hears from every nodeO(N) per period, O(N²) totalFixed timeout, binarySmall clusters, hand-rolled code
Gossiped heartbeat counterHeartbeat version spreads by gossipConstantLocal timeout or phi on counter progressCassandra (generation, version), Akka Cluster
SWIM probingping, then ping-req via k peersConstant (one probe per period)Suspect, then dead after a timeout unless refutedmemberlist, Serf, Consul, Nomad, Uber Ringpop, Habitat Butterfly
Phi accrualInter-arrival time distributionDepends on transportContinuous phi; caller sets threshold (default 8)Cassandra phi_convict_threshold, Akka failure-detector.threshold
Redis Cluster PFAIL/FAILPing/pong on the cluster busA few random pings per second plus anyone silent for NODE_TIMEOUT/2PFAIL locally, FAIL with a majority of mastersRedis Cluster

Numbers to memorise (memberlist DefaultLANConfig, verified in v0.5.4 source).

KnobValueFormula it feeds
ProbeInterval / ProbeTimeout1 s / 500 msOne probe per member per second
IndirectChecks (k)3ping-req fan-out
GossipInterval / GossipNodes200 ms / 3Dedicated gossip fan-out
RetransmitMult4Each update sent 4 × ceil(log10(N+1)) times
SuspicionMult4Suspicion timeout = 4 × max(1, log10(N)) × ProbeInterval: 8 s at N = 100, 12 s at N = 1000
SuspicionMaxTimeoutMult6Lifeguard starts at 6 × that and shrinks with confirmations
PushPullInterval30 sFull state anti-entropy
AwarenessMaxMultiplier8Lifeguard local health backs probing off to 8 s

The verdict ladder everyone reinvents.

ProductLocal doubtGroup verdictWho clears it
SWIM / memberlistsuspectdead (SWIM: confirm) after suspicion timeoutThe suspect, by gossiping alive with a higher incarnation
Redis ClusterPFAIL (fail? in CLUSTER NODES)FAIL after a majority of masters reported it within 2 × NODE_TIMEOUTReachability again (replica, slotless master, or N × NODE_TIMEOUT with no promotion)
Cassandraphi above phi_convict_threshold (8)No group verdict: UP/DOWN is local and not gossipedA successful connection
Akka Clusterunreachable (phi above threshold 8)down only by a downing provider (Split Brain Resolver)REACHABLE again
Laravel registry (this page)suspect after 15 sdead after 60 s, reapedA heartbeat with the current incarnation

Why it exists ​

A cluster of 2000 nodes needs every node to know who else is alive and what each one owns. Three obvious designs fail:

DesignWhat breaks first
Every node heartbeats every node2000 × 1999 ≈ 4 million messages per period; one congested switch makes hundreds of nodes look dead at once
A central registry everyone pollsIt is a bottleneck and a single point of failure for a question ("who is up?") that does not need one agreed answer
Broadcast each change onceMessages get lost; nodes that were down during the broadcast never learn

Gossip trades exactness for scale: each node does a constant amount of work per round, information spreads exponentially (1, 2, 4, 8 … nodes), and random peer choice routes around any one failure. The price is that the view is only eventually consistent membership: two nodes may disagree for a few seconds about whether a third is alive.

Gossip gives youGossip does not give you
Convergence in O(log N) roundsA moment at which everyone agrees
Constant per-node loadA bound on stale reads
No single point of failureExactly one leader, lock holder or owner
Tolerance of loss and crashed peersProtection against a Byzantine (lying) member

Everyday picture used through the page: an office rumour. Nobody sends an all-staff email; each person tells two or three colleagues at the coffee machine. By lunch everyone knows, even though half the office was in meetings. But nobody can say at 10:42 exactly who knows yet, and if someone starts a false rumour ("Dana quit"), it spreads just as fast unless Dana walks in and says "I am still here" (refutation).

Three common misunderstandings, up front ​

  1. "Gossip is slow because it is random." It is logarithmic: 1000 nodes need about 10 push-pull rounds; at memberlist's 200 ms gossip interval that is about 2 seconds.
  2. "Gossip-based failure detection tells me the node is dead." It tells you that someone could not reach it within a timeout. A GC pause, a saturated NIC or a partition looks the same. That is why SWIM suspects before it declares, and why Cassandra never removes a node automatically.
  3. "We have gossip, so we have consensus." Gossip converges on a merge of facts; it cannot choose one winner among competing proposals. Leaders, locks and slot ownership need Raft, Paxos or an epoch vote (Leader Election).

Where it comes from ​

  • 1987, Xerox PARC. Demers, Greene, Hauser, Irish, Larson, Shenker, Sturgis, Swinehart and Terry studied the Clearinghouse name servers on the Xerox Corporate Internet. Their PODC paper (reprinted as CSL-89-1) defines direct mail, anti-entropy and rumour mongering, push/pull/push-pull, death certificates, and spatial distributions. It reports that the push anti-entropy epidemic takes "log2(n) + ln(n) + O(1)" cycles, that "either pull or push-pull is greatly preferable to push" when only a few sites remain susceptible, and that one algorithm solved "long-standing problems of high traffic and database inconsistency".
  • 2002, Cornell. Das, Gupta and Motivala published SWIM (Scalable Weakly-consistent Infection-style Process Group Membership). Its key move: separate failure detection from dissemination. Its abstract states the motivation as "the unscalability of traditional heart-beating protocols, which either impose network loads that grow quadratically with group size, or compromise response times or false positive frequency". It adds the suspicion sub-protocol, incarnation numbers and round-robin target selection.
  • 2004, JAIST. Hayashibara, Défago, Yared and Katayama proposed accrual failure detectors: instead of a boolean, output a suspicion level φ and let each application pick its threshold. Cassandra and Akka adopted it.
  • 2007. Amazon's Dynamo paper describes gossip-based membership with seeds; Leitão, Pereira and Rodrigues publish HyParView (DSN 2007) for reliable broadcast over partial views. Cyclon (Voulgaris, Gavidia, van Steen, 2005) had introduced cheap view shuffling.
  • 2013 onward. HashiCorp releases Serf and memberlist (SWIM with push/pull sync and a separate gossip layer), which power Consul and Nomad. Redis Cluster ships with its own gossip bus.
  • 2017. Dadgar, Phillips and Currey (HashiCorp) publish Lifeguard, which makes SWIM aware of the prober's own local health and cuts false positives drastically. It ships in memberlist and Serf 0.8.

The concept catalogue ​

Epidemic dissemination and convergence Must-know ​

pushpullpush-pullred = has the updatepush 18.6 cyclespull 13.8 cyclespush-pull 9.1 cycleslog2 n + ln n = 16.9Average cycles to infect all 1000 sites, 20 seeded runs of epidemic.AntiEntropy (this chapter's Go module)Rumour mongering, feedback + counter k, 1000 sites (Demers Table 1: residue 0.18 / 0.037 / 0.011 at k = 1 / 2 / 3)simulation: k=1 residue 0.20, m=1.6 | k=2 0.060, m=2.8 | k=3 0.020, m=3.9 | k=4 0.006, m=5.0 | k=5 0.002, m=6.0residue = sites that never heard the rumour; m = messages per site; the law s = e^-m holds for every variant

In plain words: Each round, everyone who knows something tells a random peer. The number who know roughly doubles every round, so N nodes are covered in about log2 N rounds plus a tail for the last few stragglers.

Common misunderstanding: "Convergence time grows with N." It grows with log N. Going from 100 to 10 000 nodes adds about 7 rounds, not 100×. What does grow with N is the total traffic (N nodes × constant), and the tail when you use push only.

Definition: An epidemic protocol models nodes as susceptible (has not heard), infective (has the update and spreads it) or removed (has it, no longer spreads it). In a simple epidemic (anti-entropy) every infected node stays infective, so the whole population is infected in expected time proportional to log N. Convergence is the state in which every live node holds the same version of the information; convergence time is the time from injection until the last node has it (Demers calls it t_last, and also measures the average delay t_ave).

 round  push-pull, n = 16, one update injected at node 0       informed
 0      0                                                         1
 1      0->5                                                      2
 2      0->9   5->12                                              4
 3      0->3   5->1   9->14  12->7                                8
 4      remaining 8 nodes pull from or are pushed by informed     16
        log2(16) = 4 rounds; push alone needs a few more because
        the last uninformed nodes must be chosen by someone

Real scenario: a new Consul agent's join spreads to a 5000-node LAN pool in seconds; a Cassandra schema version change reaches every node so each can schedule a schema pull; a Redis Cluster FAIL message is sent to all reachable nodes so they stop routing to a dead master at about the same time; Serf user events ("deploy v42") fan out across a fleet without a central bus.

Nlog2 NOur push-pull simulation (cycles)At memberlist 200 ms gossip interval
1006.66.5about 1.3 s
100010.09.1about 1.8 s
10 00013.311.5about 2.3 s

How to use it: budget convergence as rounds × interval, with rounds ≈ log2 N + a few, and add the detection time when the fact is a failure. The Go epidemic package reproduces the table; the SWIM simulator measures the same for piggybacked membership facts (4, 7, 10 periods for 16, 128, 1024 members).

Anti-entropy: push, pull, push-pull Must-know ​

In plain words: Two nodes meet and make their copies equal. Push: I send you what I have that you lack. Pull: I ask for what you have that I lack. Push-pull: both at once.

Common misunderstanding: "Push and pull are symmetric." They are not when few nodes are left uninformed. With pull, an uninformed node only needs to pick any informed node, which is almost certain; with push, it must be picked by someone. Demers et al. show the pull probability of staying uninformed shrinks quadratically per cycle and push only by a constant factor e^-1. That is why push gossip is good early and pull gossip finishes the job.

Definition: Anti-entropy is periodic, pairwise reconciliation of full state with a randomly chosen peer. ResolveDifference(s, s') keeps the newer timestamp per item; push copies s to s', pull copies s' to s, push-pull does both. It always converges, but naive anti-entropy compares entire databases, so real systems compare digests first: checksums (Demers), Merkle trees (Dynamo, Cassandra repair, Riak AAE), or version vectors of node state (Cassandra gossip digests).

 1  A -> B  SYN: digests {A: gen 1700, ver 42; C: gen 1650, ver 17}
 2  B       compares: B has C at ver 19 (newer), lacks A ver 40..42
 3  B -> A  ACK: state for C (ver 19) + request for A since ver 39
 4  A -> B  ACK2: state for A (ver 40..42)
 5          both now hold the newest version of A and C: push-pull in three messages

Real scenario: memberlist's push/pull every PushPullInterval (30 s LAN, 60 s WAN) sends the full member list over TCP so any missed rumour is repaired; Dynamo nodes "contact a peer chosen at random every second" to reconcile membership change histories; Cassandra's three-message gossip exchange (its GossipDigestSyn, GossipDigestAck, GossipDigestAck2 message classes) is a digest-based push-pull; Cassandra and Riak run Merkle-tree anti-entropy for data, which Merkle Trees & Anti-Entropy owns.

ProductAnti-entropy unitIntervalTransport
memberlist / Serf / ConsulFull member list (+ delegate LocalState)PushPullInterval 30 s (LAN), 60 s (WAN)TCP
Cassandra gossipEndpoint state digests (generation, version)Every second, one random peerInternode messaging
Cassandra repairMerkle tree per token rangeOperator or scheduler (nodetool repair)Streaming
DynamoMembership change history, token mapEvery second, random peerRPC
RiakRing state; Merkle trees for data (AAE)On ring change plus periodic re-announceErlang distribution

How to use it: use rumour mongering (piggybacking) for speed and a slow anti-entropy loop as the safety net. Never run anti-entropy without a digest step on large state.

Rumour mongering: hot rumours, counters and residue Important ​

In plain words: A node that hears something new keeps telling random peers until it notices that most of them already know, then it goes quiet. Cheap and fast, but a few nodes may never hear.

Common misunderstanding: "Rumour mongering is reliable on its own." It has a residue: the fraction still uninformed when everyone has gone quiet. Demers et al. measured 18% residue at k = 1 and 3.7% at k = 2 on 1000 sites. Every production system pairs it with anti-entropy.

Definition: Rumour mongering (the paper spells it "rumor mongering") is a complex epidemic: an infective node loses interest with probability 1/k (coin) or after k unnecessary contacts (counter), with or without feedback from the recipient (blind vs feedback). All variants share the traffic/residue law s = e^-m, where m is the number of messages per site. Counters and feedback reduce delay. SWIM's version is deterministic: each update is piggybacked a fixed number of times, λ log N (memberlist: RetransmitMult × ceil(log10(N+1))).

 cycle  node 0 holds hot rumour R, counter k = 2
 1      0 -> 17   17 did not know: 17 becomes infective
 2      0 -> 44   new; 17 -> 3 new
 3      0 -> 3    3 already knew: counter(0) = 1
 4      0 -> 17   17 already knew: counter(0) = 2: node 0 stops (removed)
 ...    infective count rises, peaks, falls to 0
 end    residue s ~ 0.04-0.06: about 50 of 1000 nodes never heard R; anti-entropy fixes them later

Real scenario: a Serf user event (serf event deploy) that a few nodes miss because they were restarting; memberlist dropping the oldest broadcasts when the TransmitLimitedQueue is over budget during a mass join; a Redis Cluster node that missed a gossip section learns the same fact from the next ping a moment later.

k (counter, feedback)Demers Table 1 residueOur simulation residueTraffic m
10.180.201.6
20.0370.0602.8
30.0110.0203.9
50.00120.0026.0

How to use it: raise the retransmit multiplier until the residue is negligible for your N, and keep a full-state sync. Our simulation is synchronous (all sites act in lockstep), which explains the slightly higher residue than the paper.

Fan-out, interval and message complexity Must-know ​

In plain words: Fan-out is how many peers you talk to per round; interval is how often. Together they set both speed and bandwidth.

Common misunderstanding: "Raise fan-out to converge faster, it is free." Convergence improves only logarithmically (rounds ≈ log N / log(fan-out+1)), while bandwidth grows linearly with fan-out. Doubling GossipNodes from 3 to 6 saves maybe one round and doubles UDP traffic.

Definition: Fan-out (memberlist GossipNodes, Cassandra one random peer plus optional seed/unreachable peer) is the number of peers contacted per gossip interval. Message complexity is messages per update or per node per second. SWIM's probe load is constant per member: one ping per period plus occasional ping-reqs; total cluster load is O(N), versus O(N²) for all-to-all heartbeating.

 1  N = 1000, GossipInterval = 200 ms, GossipNodes = 3, packet ~1400 bytes (UDP)
 2  per node: 3 packets / 0.2 s = 15 gossip packets/s out, 15 in on average
 3  plus probing: 1 ping/s out, ~1 ack/s in, ~1 ping/s received from others
 4  per node ~ 35 packets/s ~ 50 KB/s; whole cluster ~ 35 000 packets/s, spread evenly
 5  all-to-all heartbeat at 1/s instead: 999 packets/s per node, ~1 000 000 packets/s total

Real scenario: a WAN pool where GossipNodes = 4 and GossipInterval = 500 ms (memberlist DefaultWANConfig) trades speed for fewer cross-region packets; a Redis Cluster of 100 nodes with a 60 s node timeout sends about 330 pings per second in total (the spec's own example); Kubernetes nodes running Consul agents where gossip traffic is negligible next to application traffic.

SystemFan-out per roundIntervalTotal load
memberlist LAN3 gossip + 1 probe (+3 ping-req on failure)200 ms gossip, 1 s probeO(N)
memberlist WAN4 gossip + 1 probe500 ms gossip, 5 s probeO(N)
Cassandra1 random live + maybe 1 unreachable + maybe 1 seed1 sO(N)
Redis ClusterA few random nodes + everyone silent for NODE_TIMEOUT/21 s (plus timeout-driven)Grows as N²/NODE_TIMEOUT
All-to-all heartbeatN-1Heartbeat periodO(N²)

How to use it: keep fan-out small (3 to 4), tune the interval to your convergence target, and measure packet rates in staging at the target N. The Go heartbeat test prints 499 messages per member per period at N = 500 against SWIM's 2.

Heartbeat vs gossip-based failure detection Must-know ​

In plain words: A heartbeat says "I am alive" on a schedule; a failure detector decides when silence means death. Doing it all-to-all is simple and does not scale; gossip-based detection makes each node responsible for checking only a few others per round and shares the results.

Common misunderstanding: "A shorter heartbeat timeout detects failures faster at no cost." It produces false positives: healthy nodes declared dead because of a lost packet or a pause. With a fixed timeout and no second opinion, one slow node is declared dead by everyone simultaneously, and the cluster rebalances data for nothing.

Definition: Failure detection has two properties: completeness (every crash is eventually detected) and accuracy (few false positives), traded against detection time. A heartbeat detector waits a fixed time for messages. Gossip-based detectors either gossip heartbeat counters (each node increments its own counter, others see it advance through gossip and convict when it stops advancing: Cassandra) or probe randomly and gossip verdicts (SWIM).

 t     all-to-all heartbeat, timeout 2 s, node C pauses 2.5 s in GC
 0     A, B, D ... (1999 nodes) each expect a heartbeat from C every 1 s
 2.0   every node independently: "no heartbeat from C for 2 s": C DOWN
 2.0   1999 nodes start rerouting, hinted handoff, rebalancing
 2.5   C resumes, heartbeats: 1999 nodes mark C UP again; flapping in every log

Real scenario: a JVM stop-the-world pause on a Cassandra node; a noisy-neighbour VM whose CPU steal delays packet processing; a top-of-rack switch dropping 3% of UDP; a container hitting its CPU quota so the gossip thread runs late.

ApproachProductAccuracy lever
Fixed-timeout heartbeatHand-rolled, many job systemsLonger timeout only
Gossiped heartbeat counter + phiCassandraphi_convict_threshold
Request/reply heartbeat + phiAkka Clusterthreshold, acceptable-heartbeat-pause
Probing + indirect probes + suspicionmemberlist, Serf, Consulk, suspicion timeout, Lifeguard
Ping/pong + majority reportsRedis Clustercluster-node-timeout, majority of masters

How to use it: never let a single observer's timeout trigger a cluster-wide action. Require a second opinion (indirect probes), a suspicion period, or a majority.

SWIM probing: ping, ping-req and indirect probes Must-know ​

A (prober)B (helper)C (helper)D (target)1. ping(D) + piggybacked updatesno ack within ProbeTimeout (memberlist 500 ms)2. ping-req(D) to k random members3. B and C ping D4. ack (if D is up)5. ack forwarded to A: D stays aliveNo ack, direct or indirect, by the end of the protocol period (memberlist ProbeInterval 1 s):A gossips suspect(D, inc) on the next pings and acks (piggybacking); others start a suspicion timerD hears it and gossips alive(D, inc+1): the higher incarnation number overrides the suspicionno refutation before SuspicionMult x log10(N) x ProbeInterval: dead(D) (SWIM: confirm) spreads

In plain words: Every period each node pings one member. If no ack comes back quickly, it asks k other members to ping that member on its behalf. Only if nobody gets an answer does it start suspecting.

Common misunderstanding: "ping-req is a retry." It is a retry along different network paths. The point is to separate "the target is down" from "the path between me and the target is congested". SWIM sends ping-reqs through k members for exactly that reason, "to avoid the effect of any congestion on the network path".

Definition: SWIM runs a protocol period T' (memberlist ProbeInterval, 1 s). In each period member Mi picks a target Mj, sends ping, waits for an ack until a timeout shorter than the period (memberlist ProbeTimeout, 500 ms; the Serf docs describe it as "typically some multiple of RTT"). On timeout it sends ping-req(Mj) to k random members (memberlist IndirectChecks, 3); each pings Mj and forwards the ack. This is the indirect probe. Targets are chosen round-robin over a shuffled list, so every member is probed within a bounded number of periods (time-bounded strong completeness); a new member is inserted at a random position. memberlist adds a TCP fallback ping and, with Lifeguard, a nack from helpers that could not reach the target.

 period p at member A (memberlist names in brackets)
 1  t=0      A -> D   ping, seq 812 [probeNode]
 2  t=500ms  no ack   [DEBUG] memberlist: Failed UDP ping: D (timeout reached)
 3  t=500ms  A -> B, C, E  ping-req(D)   (IndirectChecks = 3)
 4  t=520ms  B -> D   ping;  C -> D ping;  E -> D ping
 5  t=900ms  E -> A   nack (no reply from D at 80% of the timeout)
 6  t=1000ms no ack from anyone: A gossips suspect(D, inc=4)
            [INFO] memberlist: Suspect D has failed, no acks received

Real scenario: a single flaky link between rack 1 and rack 3: direct pings fail, ping-reqs through rack 2 succeed, nobody is suspected; a crashed Nomad client: all paths fail, suspicion starts within one second; UDP blocked by a firewall but TCP allowed: memberlist logs "Was able to connect to D over TCP but UDP probes failed, network may be misconfigured".

PropertySWIM papermemberlist / Serf
Protocol periodT' (2 s in the prototype)ProbeInterval 1 s (LAN), 5 s (WAN)
Ack timeoutFrom RTT estimate, period at least 3 × RTTProbeTimeout 500 ms (LAN), 3 s (WAN)
Indirect probes kParameterIndirectChecks 3 (LAN), 1 (local)
Target selectionRound-robin over shuffled listSame
TransportUDPUDP probes and gossip, TCP fallback ping and push/pull

How to use it: keep k at 3: the Go test shows that with 5% packet loss, k = 0 produced 542 suspicions in 100 periods across 64 members, k = 3 produced 2.

Suspicion, incarnation numbers and refutation Must-know ​

SWIM / memberlist / Serf / Consul (per member, per observer)alivesuspectdeadping + ping-req failalive(inc+1) refutessuspicion timeoutrejoin with a higher incarnation (left = graceful leave, not dead)Redis Cluster bus (cluster-node-timeout = NODE_TIMEOUT)okPFAILFAILno pong for NODE_TIMEOUTmajority of mastersreported within 2 x NODE_TIMEOUT;FAIL message broadcastlocal only, via gossip sections

In plain words: A failed probe does not kill a member; it makes it a suspect. The suspect hears the rumour about itself and shouts "I am alive" with a higher version number. If nobody hears that before a timeout, the member is declared dead.

Common misunderstanding: "Any node can mark a node alive again." Only the member itself may raise its incarnation number. If others could, an old "alive" message delayed in the network could override a correct "dead" verdict. The number is the member's own logical clock for statements about itself.

Definition: In SWIM, a member that fails a probe round is marked Suspect locally and a Suspect{Mj, inc} message is disseminated. Suspected members still receive probes. If anyone successfully pings it, an Alive message un-marks it. If the suspicion timeout expires first, the member is declared faulty and Confirm{Mj, inc} (memberlist calls it dead) spreads. The incarnation number starts at 0 when a member joins and only that member increments it, when it learns it is suspected. Precedence rules: Alive(i) overrides Suspect(j) and Alive(j) when i > j; Suspect(i) overrides Suspect(j) when i > j and Alive(j) when i ≥ j; Confirm overrides both. memberlist also lets a dead member rejoin with a higher incarnation, and distinguishes left (graceful) from dead.

 1  t=0   A suspects D:  gossip suspect(D, inc=4) piggybacked on A's pings and acks
 2  t=1s  B, C mark D suspect, start their own suspicion timers (memberlist: 4 x log10(N) s)
 3  t=2s  D receives suspect(D, inc=4) about itself: inc 4 >= own 4
          D sets inc = 5, gossips alive(D, inc=5)
          [WARN] memberlist: Refuting a suspect message (from: A)
 4  t=3s  alive(D,5) overrides suspect(D,4) at A, B, C: timers cancelled
 5  if D never refutes: t = timeout: dead(D, inc=4) spreads, overrides everything
          [INFO] memberlist: Marking D as failed, suspect timeout reached (2 peer confirmations)

Real scenario: a 3-second GC pause on a Consul client: suspected, refutes on resume, no service deregistration; a restarted node rejoins with a fresh, higher incarnation and overrides its own old dead state; a stale VM snapshot booting with an old incarnation is ignored because its alive messages are not newer.

MessageOverridesRaised by
alive(inc)suspect and alive with lower inc; dead with lower inc (rejoin, memberlist)Only the member itself (or a join)
suspect(inc)alive with same or lower inc; suspect with lower incAny prober whose probe round failed
dead / confirm(inc)alive and suspect with same or lower incThe member whose suspicion timer expired
left (memberlist, Serf)Treated as dead but intentional; no alarmThe member on graceful Leave

How to use it: set the suspicion timeout long enough for your worst normal pause (GC, VM migration), and rely on refutation rather than ever-shorter timeouts. In the Go simulator a member made deaf for a few periods is suspected, refutes, and is never declared dead.

Dissemination by piggybacking Important ​

In plain words: Instead of sending separate gossip messages, SWIM staples recent membership news to the pings and acks it is sending anyway.

Common misunderstanding: "Piggybacking makes updates arrive slower." It makes them free. Each period every member sends and receives about two messages, each carrying a few updates, which is an infection-style spread with the same log N behaviour. memberlist adds a dedicated gossip layer on top (every 200 ms to 3 nodes) for even faster convergence.

Definition: Dissemination is the job of getting membership changes (join, leave, suspect, dead) to all members. Piggybacking attaches up to a packet's worth of updates to protocol messages. Each member keeps a buffer of recent updates with a send count; updates sent fewer times go first, and each is sent at most λ log N times (memberlist RetransmitMult × ceil(log10(N+1)): 16 at N = 1000). The SWIM prototype piggybacked at most 6 updates per message, for a 135-byte payload.

 1  A's broadcast queue: [suspect(D,4) sent 0x] [join(F,0) sent 5x] [alive(B,2) sent 15x]
 2  A -> C ping   carries suspect(D,4), join(F,0), alive(B,2)   (least-sent first)
 3  alive(B,2) has now been sent 16 = 4 x ceil(log10(1001)) times: dropped from the queue
 4  C -> A ack    carries C's own newest updates back
 5  within ~log N periods every member has seen suspect(D,4)

Real scenario: a mass restart of 300 nodes floods the queue with join messages; memberlist's TransmitLimitedQueue prunes the oldest, and push/pull sync repairs any gap. Serf user events and queries ride on the same queue, so a chatty application event stream can delay membership news; keep events small and rare.

KnobmemberlistSWIM paper
Retransmit limitRetransmitMult (4) × ceil(log10(N+1))λ log N
Updates per messageFill up to UDPBufferSize (1400 bytes)At most 6 in the prototype
PriorityFewer transmits first, newer firstFewer piggybacks first
Extra channelGossip every GossipInterval to GossipNodesNone

How to use it: do not put large payloads in node metadata or events; they compete with failure news for the same packet budget. Watch memberlist.gossip timing and queue depth during deploys.

Lifeguard: local health awareness Important ​

In plain words: Sometimes the accuser is the sick one. A member starved of CPU misses acks and suspects healthy peers. Lifeguard makes members notice their own bad health, slow down, and require more agreement before a suspicion turns into a death.

Common misunderstanding: "False positives come from the suspected node being slow." The Lifeguard paper shows that slow message processing at the probing member is a major cause; SWIM's suspicion mechanism assumes the local member is healthy. It reports that with Lifeguard there were no false positives "until 16 machines are stressed concurrently" in its test.

Definition: Lifeguard (Dadgar, Phillips, Currey 2017) adds three components to SWIM:

  • Local Health Aware Probe: a saturating counter, the Local Health Multiplier (LHM, max S = 8), goes up on failed probes, refutations about itself and missed nacks, and down on successful probes. ProbeInterval = Base × (LHM + 1) and ProbeTimeout = Base × (LHM + 1), so a sick member backs off to 9 s and 4.5 s.
  • Local Health Aware Suspicion: the suspicion timeout starts at Max and falls toward Min as independent confirmations C arrive: max(Min, Max − (Max − Min) × log(C+1) / log(K+1)), with K = 3. memberlist sets Max = SuspicionMaxTimeoutMult (6) × Min.
  • Buddy System: when pinging a suspected member, the suspicion about it is always piggybacked first, so it can refute sooner.
 1  member X is CPU-starved; it drops 70% of incoming packets
 2  X pings Y, ack lost: X suspects Y (inc 3); LHM(X) += 1, X's next probe waits 2 s
 3  Without Lifeguard: timer = Min = 4 s; Y's refutation never reaches deaf X: X gossips dead(Y)
                       everyone marks Y dead, Y refutes with inc 4: flapping
 4  With Lifeguard:   timer = Max = 24 s; no other member confirms the suspicion (C = 0)
                       buddy system puts suspect(Y) first on X's next ping to Y
                       Y refutes alive(Y, 4) many times; one copy gets through to X: no death

Real scenario: a Consul agent on a VM with a CPU quota that throttles during log rotation; a Nomad client during a container image pull saturating disk and network; memberlist exposes memberlist.degraded.probe and memberlist.degraded.timeout counters when probing degrades.

AspectSWIMSWIM + Lifeguard (memberlist, Serf 0.8+, Consul)
Probe intervalFixed× (LHM+1), up to 9 s
Suspicion timeoutFixedMax (6 × Min) shrinking with confirmations
Who learns of suspicion firstWhoever gossip reachesThe suspect, via buddy system
New messageNonenack from ping-req helpers
Configurationn/aNone: "it tunes itself automatically" (Serf docs)

How to use it: use a library that implements it (memberlist does by default). In the Go simulator, four slow members produced 11 121 local false dead declarations without Lifeguard and 215 with it over the same 150 periods and seeds.

Phi accrual failure detector Must-know ​

In plain words: Instead of "dead or alive", the detector says "how surprised should I be by this silence?", using the history of how regularly that peer's heartbeats arrived. The application decides at which surprise level to act.

Common misunderstanding: "phi = 8 means 8 seconds." φ is a logarithmic confidence: φ = 1 means about a 10% chance the heartbeat is merely late, φ = 2 about 1%, φ = 8 about 10^-8 under the fitted distribution. A jittery peer gets more time automatically; a very regular one gets convicted quickly.

Definition: The phi-accrual failure detector (Hayashibara et al. 2004) keeps a sliding window of heartbeat inter-arrival times, fits a distribution, and outputs φ(t_now) = −log10(P_later(t_now − T_last)), the negative log of the probability that a heartbeat arrives later than the time already waited. Akka documents it as phi = -log10(1 - F(timeSinceLastHeartbeat)) with F the normal CDF from the observed mean and standard deviation. The phi threshold is the application's knob: Cassandra phi_convict_threshold (default 8, "most users should never need to adjust this"), Akka failure-detector.threshold (default 8, "could be increased to 12" on Amazon EC2), plus Akka's acceptable-heartbeat-pause margin.

 heartbeats every 1 s, standard deviation 50 ms (Go phi test)
 1  silence 1.0 s   phi  0.31   normal
 2  silence 1.5 s   phi  6.60   worried
 3  silence 2.0 s   phi 23.2    convicted at threshold 8 (or 12)
 same silence for a peer with 400 ms jitter: phi 0.31, 1.01, 2.28: not convicted
 with acceptable-heartbeat-pause = 3 s, a 3 s silence gives phi ~ 0

Real scenario: Cassandra on EC2 where cross-AZ latency spikes trigger DOWN/UP flaps; raising phi_convict_threshold to 10-12 is the documented-folklore fix but should follow GC and network investigation. Akka Cluster logs "Marking node(s) as UNREACHABLE" and warns "heartbeat interval is growing too large" when arrivals exceed 2/3 of the acceptable pause.

ProductWhere phi is appliedThreshold knob (default)Margin knob
CassandraGossip heartbeat version progress per peerphi_convict_threshold (8)None exposed
Akka Cluster / Remote DeathWatchRequest/reply heartbeats, 1 s defaultfailure-detector.threshold (8)acceptable-heartbeat-pause
Go (this page)phi.Detector per peerCaller's choiceacceptablePause

How to use it: use phi when heartbeat timing is noisy and different peers deserve different patience; use SWIM when you also need dissemination of the verdict. They compose: phi decides locally, gossip spreads facts.

Seeds, bootstrap and push/pull sync Must-know ​

In plain words: A new node knows nobody. It is configured with a few addresses (seeds) to call first; one answer gives it the whole member list, and from then on it gossips like everyone else.

Common misunderstanding: "Seed nodes are special masters." They are ordinary members with a well-known address. Cassandra's docs say "the only difference between seed and non-seed nodes is that seed nodes are allowed to bootstrap into the ring without seeing any other seed nodes", and that seeds become gossip hotspots. Making every node a seed, or listing only one, are both mistakes.

Definition: Bootstrap is the join procedure: contact any live member, receive full state (memberlist Join does a TCP push/pull sync; Serf "does a full state sync with the existing member over TCP and begins gossiping its existence"), then spread an alive message. A seed node is a member whose address is configured or discovered externally. Seeds also prevent logical partitions: Dynamo notes that two nodes joined separately could each think they form the ring, and "Because all nodes eventually reconcile their membership with a seed, logical partitions are highly unlikely."

 1  new node N starts with seeds = [192.0.2.11, 198.51.100.11, 203.0.113.11] (one per rack/AZ)
 2  N -> 192.0.2.11  TCP push/pull: sends own alive(N, inc 0), receives 312 members
 3  N gossips alive(N); within ~log2(313) ~ 9 rounds every member knows N
 4  Cassandra only: every round, if the random peer was not a seed, also gossip with a seed
 5  seed 192.0.2.11 dies later: nothing breaks; N already knows everyone

Real scenario: Consul retry_join with cloud auto-join (instances found by cloud tags) instead of hard-coded IPs; Cassandra seed_provider with SimpleSeedProvider listing two seeds per datacenter; Kubernetes headless Service DNS used as the seed list for an Akka or memberlist cluster; Redis Cluster nodes introduced with CLUSTER MEET and then discovering the rest through gossip sections.

ProductSeed mechanismRecommendation from its docs
Cassandraseed_provider (SimpleSeedProvider, seeds list)Multiple seeds, often one per rack or datacenter
memberlist / SerfJoin([]string) / serf join, -retry-joinAt least one existing member
Consulretry_join, cloud auto-joinSeveral, discovered from cloud metadata
DynamoSeeds from static config or a configuration serviceSeeds known to all nodes
Redis ClusterCLUSTER MEET ip portAny one node; the rest via gossip
Akka Clusterseed-nodes or Cluster BootstrapUse Akka Management bootstrap in Kubernetes

How to use it: list 2-3 seeds per failure domain, discover them (DNS, cloud tags) rather than hard-coding, and make sure a partitioned or freshly restored cluster still contacts at least one seed from the other side.

Partial views: HyParView and Cyclon Good to know ​

In plain words: With a million peers nobody can keep the full member list. Each node keeps a small, random, constantly refreshed subset, and gossip still reaches everyone because the random subsets form a well-connected graph.

Common misunderstanding: "memberlist and Cassandra use partial views." They keep full membership (every node knows every node), which is fine up to thousands of nodes. Partial views matter for peer-to-peer overlays, edge devices and very large fleets.

Definition: A partial view is a bounded subset of members a node knows and gossips with. Cyclon (2005) periodically shuffles view entries with a neighbour, replacing the oldest, which keeps the overlay random with low diameter. HyParView (2007) keeps a small symmetric active view (size fan-out + 1) over TCP, used for broadcast by flooding and as a failure detector, and a larger passive view of backups promoted when an active neighbour fails, giving high reliability "even in the presence of high rates of node failure". The same group's Plumtree protocol builds an epidemic broadcast tree on top of such an overlay.

 1  node P: active view {A, B, C, D} (fan-out 3 + 1), passive view {30 random ids}
 2  broadcast: P floods to A, B, C, D over open TCP connections
 3  C's TCP connection drops: P detects it immediately (TCP as failure detector)
 4  P promotes E from the passive view, sends NEIGHBOR(E): active view {A, B, D, E}
 5  periodic shuffle exchanges a few passive entries with a random peer

Real scenario: a sensor or browser peer-to-peer network where nodes come and go every minute; a multi-region control plane with 100 000 agents where full membership would cost too much memory and bandwidth (an inference from the papers' goals, not a published deployment).

ProtocolViewFailure detectionUsed by
Full membership (SWIM)EveryoneProbingmemberlist, Serf, Consul
CyclonSmall random cache, shuffledImplicit (old entries age out)Research overlays, P2P
HyParViewActive (fan-out + 1) + passiveTCP connection lossReliable broadcast overlays, Plumtree trees
Scuttlebutt (van Renesse et al.)Full, reconciled by per-node version digestsSeparate (heartbeat versions)Cassandra's digest exchange is similar (inference)

How to use it: stay with full membership below a few thousand long-lived nodes. Consider HyParView-style overlays only when membership itself is the bottleneck.

Gossip for cluster state: Cassandra, Redis Cluster, Riak, Dynamo Must-know ​

In plain words: Databases use gossip not only to know who is up but to share small cluster facts: which node owns which token range or slot, the schema version, load, and protocol versions.

Common misunderstanding: "If gossip says the node is down, the database will move its data." Cassandra deliberately "will never remove a node from gossip state without explicit instruction from an operator via a decommission operation or a new node bootstrapping with a replace_address_first_boot option", to avoid needless rebalancing. Redis Cluster fails over only after a majority of masters agree and a replica wins an epoch vote.

Definition:

  • Cassandra gossip: every second each node updates its heartbeat version, gossips with one random live peer, probabilistically with an unreachable one, and with a seed if the random peer was not one. State is versioned by (generation, version): generation is a monotonic timestamp set at startup, version a logical clock. Gossip carries endpoint membership, protocol versions, token metadata and schema version; a schema version mismatch schedules a schema pull. UP/DOWN is decided locally by the phi accrual detector and is not gossiped.
  • Redis Cluster bus: each node has a second TCP port (data port + 10000, or cluster-port) using a binary protocol. Ping and pong packets carry a header (node ID, currentEpoch, configEpoch, flags, slot bitmap) and a gossip section about a few random other nodes. A node marks a peer PFAIL after NODE_TIMEOUT without a pong; when it collects failure reports (PFAIL or FAIL flags in gossip sections) from a majority of masters within NODE_TIMEOUT × FAIL_REPORT_VALIDITY_MULT (2), it marks FAIL and broadcasts a FAIL message.
  • Riak ring: "The ring state is shared around the cluster by means of a gossip protocol"; a node announces its claim changes and "periodically re-announce[s] what they know".
  • Dynamo membership: an administrator issues joins and leaves explicitly; "A gossip-based protocol propagates membership changes and maintains an eventually consistent view of membership"; token mappings ride the same exchange, so each node can route a key directly.
 Redis Cluster, cluster-node-timeout 5000 ms, masters M1..M5, M3 dies
 1   t=0     M3 stops answering
 2   t=2.5s  M1, M2, M4, M5 ping M3 again (half NODE_TIMEOUT without pong), reconnect TCP
 3   t=5s    each marks M3 PFAIL locally: CLUSTER NODES shows "fail?"
 4   t=5-6s  gossip sections carry "M3 PFAIL" between masters (failure reports)
 5   t~6s    M1 sees reports from a majority (3 of 5) within 10 s: marks M3 FAIL, broadcasts FAIL
 6   t~6-7s  M3's replica R3 requests votes (FAILOVER_AUTH_REQUEST), wins configEpoch, takes slots

Real scenario: nodetool gossipinfo showing a node with an old schema version after a failed migration; a Redis Cluster minority side refusing writes after NODE_TIMEOUT; Riak ring claim changes during a cluster resize; Dynamo-style systems (DynamoDB's internals are not public; the 2007 paper describes the original Dynamo) learning token ownership through gossip.

ProductWhat is gossipedLiveness decisionRemovalKnob
CassandraEndpoint state, tokens, schema version, load, protocol versionLocal phi accrualOperator only (decommission, replace)phi_convict_threshold 8
Redis ClusterNode flags, slots, epochs, PFAIL/FAIL reportsPFAIL local, FAIL by majority of mastersCLUSTER FORGETcluster-node-timeout (e.g. 5000)
RiakRing claims, cluster metadataErlang node monitoringAdmin cluster leave / force-removeRing settings
Dynamo (2007)Membership change history, token mapLocal, request-drivenExplicit admin leaven/a

How to use it: treat gossip-derived liveness as routing advice, not as permission to move data. The database pages own the details: Cassandra & ScyllaDB, Redis, Wide-Column & Key-Value.

The HashiCorp stack: memberlist, Serf, Consul Must-know ​

In plain words: memberlist is the Go library implementing SWIM plus Lifeguard; Serf adds events, queries and a CLI on top; Consul uses Serf for membership and failure detection and Raft for its catalog.

Common misunderstanding: "Consul's service catalog is gossiped." Membership and node health (serfHealth) come from gossip; the catalog, KV store and sessions live on Consul servers replicated with Raft. Gossip tells servers which agents are alive; consensus stores what is registered.

Definition: memberlist "manages cluster membership and member failure detection using a gossip based protocol"; it "is eventually consistent but converges quickly on average". Its extensions to SWIM: periodic full state sync over TCP (push/pull), a dedicated gossip layer separate from probing, keeping dead node state for GossipToTheDeadTime so full syncs carry it, and Lifeguard. Serf builds on it ("Gossip is done over UDP with a configurable but fixed fanout and interval"). Consul runs two pools: the LAN gossip pool (port 8301) with every agent in a datacenter, and the WAN gossip pool (port 8302) among servers across datacenters.

 1  consul agent starts, retry_join finds a server via cloud auto-join
 2  memberlist Join: TCP push/pull on 8301; LAN pool now includes the agent
 3  agent registers services with the servers over RPC (Raft-replicated catalog)
 4  agent crashes: peers' probes fail, suspicion, dead(agent) gossiped
 5  servers see the member leave the LAN pool: serfHealth check critical
 6  catalog marks the node's services unhealthy; DNS and Connect stop routing to them

Real scenario: Nomad clients joining server pools; Consul ESM monitoring external nodes that cannot run agents; Kubernetes clusters with Consul on every node; custom Go services embedding memberlist to build a ring for sharded caches (the Go memberlistdemo shows the API).

LayerOwnsTransport / port
memberlistSWIM probing, gossip, push/pull, Lifeguard, encryptionUDP + TCP, 7946 by default
SerfTags, user events, queries, keyring commands, reconnect of failed membersSame as memberlist
Consul LAN poolAll agents in a datacenter, node health8301 TCP/UDP
Consul WAN poolServers across datacenters8302 TCP/UDP
Consul serversCatalog, KV, sessions via Raft8300 RPC

How to use it: embed memberlist when your Go service needs peer membership; use Consul when you also need a service catalog. Do not reinvent SWIM.

Death certificates, tombstones and the CRDT link Important ​

In plain words: In a gossip system you cannot delete something by forgetting it; a peer that still has it will gossip it back. You must gossip the deletion itself, and keep that record long enough.

Common misunderstanding: "Removing a node from my list removes it from the cluster." Demers et al.: "the propagation mechanism will spread old copies of the item from elsewhere in the database back to the site where we have deleted it". This is why Cassandra requires nodetool removenode or assassinate for ghost nodes and why memberlist keeps dead state for a while.

Definition: A death certificate (a tombstone in Cassandra terms) is a timestamped deletion that spreads like data and cancels older copies. It must be retained until every replica has seen it, or for a fixed time (Demers used 30 days), with dormant certificates kept at a few sites as insurance. Membership has the same issue: memberlist's GossipToTheDeadTime (30 s LAN) and Serf's reconnect_timeout / tombstone_timeout (24 hours each by default) decide how long failed and left members are remembered. When the gossiped state is a value rather than a fact, a CRDT guarantees that merges in any order converge (CRDTs), and a Merkle tree lets two replicas find differences cheaply (Merkle Trees & Anti-Entropy).

 1  operator removes node Z from A's member list by hand
 2  A gossips with B; B still has Z (alive, inc 7): A re-learns Z     <- resurrection
 3  correct: A gossips dead(Z, inc 7) or left(Z); B applies it (higher precedence)
 4  dead(Z) kept 30 s (GossipToTheDeadTime) so push/pull syncs carry it
 5  after reaping, if Z really returns it must use inc 8: a rejoin, not a resurrection

Real scenario: Cassandra "ghost" nodes reappearing in nodetool gossipinfo after a careless IP reuse; Serf trying to reconnect to a failed member every reconnect_interval (30 s) for reconnect_timeout (24 h) and then reaping it; a gossiped feature-flag map where a deleted flag returns because one node was offline.

SystemDeletion recordRetention knob
Demers (Clearinghouse)Death certificate, dormant copiesFixed threshold (30 days in the paper)
Cassandra dataTombstonegc_grace_seconds (repair must run within it)
Cassandra membershipRemoval only by decommission, removenode, replaceOperator action
memberlistdead / left stateGossipToTheDeadTime
Serffailed / left membersreconnect_timeout, tombstone_timeout

How to use it: always gossip deletions; size retention by the longest time a node may be offline and still rejoin.

Security: gossip encryption and the keyring Important ​

In plain words: Gossip traffic tells an attacker your whole topology and lets them inject "node X is dead" messages. Encrypt and authenticate it with a shared key, and rotate the key without downtime.

Common misunderstanding: "Gossip runs on a private network, so it does not need encryption." Anyone on that network, including a compromised pod, can join the pool or forge suspicions. Gossip encryption also does not replace TLS for RPC; Consul uses both.

Definition: memberlist and Serf use a symmetric key: "either 16, 24, or 32 bytes to select AES-128, AES-192, or AES-256" (memberlist SecretKey). A keyring holds several keys: one primary used to encrypt, all used to try decryption, so keys rotate in three steps: install the new key everywhere, use it as primary, remove the old one (serf keys -install/-use/-remove, consul keyring -install/-use/-remove). GossipVerifyIncoming and GossipVerifyOutgoing (Consul encrypt_verify_incoming / encrypt_verify_outgoing) let you enable encryption on a running cluster in stages. Serf: "All nodes within a Serf cluster must share the same encryption key in order to send and receive cluster information." Key generation is consul keygen / serf keygen (32 random bytes, base64).

 1  consul keygen                      -> new key K2 (base64, 32 bytes)
 2  consul keyring -install K2         every agent now decrypts with K1 or K2, encrypts with K1
 3  consul keyring -list               confirm every member reports K2 installed
 4  consul keyring -use K2             primary switches to K2 cluster-wide
 5  consul keyring -remove K1          K1 gone; a leaked K1 is now useless

Real scenario: a quarterly key rotation required by a compliance audit; enabling encryption on a live Consul datacenter by setting verify-incoming false, rolling the key out, then flipping both verify flags to true; Redis Cluster bus traffic, which has no gossip-level encryption of its own, protected with Redis TLS (tls-cluster yes) and network policy instead. Mutual TLS design belongs to mTLS & Service Security and key management to Cryptography, TLS, PKI & Secrets.

ProductGossip protectionRotation
memberlistAES-GCM with SecretKey / KeyringKeyring.AddKey, UseKey, RemoveKey
Serf-encrypt / encrypt_key, keyring fileserf keys -install/-use/-remove/-list
ConsulGossip key + separate TLS for RPCconsul keyring, /operator/keyring API
CassandraInternode TLS (server_encryption_options)Certificate rotation
Redis ClusterTLS on the bus (tls-cluster)Certificate rotation

How to use it: encrypt gossip from day one, store the key in a secrets manager, rotate with the keyring, and firewall gossip ports to cluster members.

Observability: churn, convergence time and flapping Important ​

In plain words: Watch how often members change state and how long news takes to reach everyone. A healthy cluster is boring: few joins and leaves, almost no suspicions.

Common misunderstanding: "A suspicion is an incident." A few suspicions per day that end in refutation are normal and show the mechanism working. A rising rate of suspicions that end in death of nodes that are actually healthy is the incident.

Definition: Churn is the rate of membership changes (joins, leaves, failures) per unit time. Flapping is a member alternating alive/dead. Convergence time is measured by injecting a known event and timing until all members report it (Serf queries, or comparing consul members output across nodes). memberlist emits memberlist.msg.alive, memberlist.msg.suspect, memberlist.msg.dead, memberlist.degraded.probe, memberlist.degraded.timeout, and timings memberlist.probeNode, memberlist.pushPullNode, memberlist.gossip through go-metrics.

 alert design for a 600-node Consul LAN pool
 1  rate(memberlist.msg.suspect) > 3x its 7-day baseline for 10 min    -> warn: network or CPU trouble
 2  rate(memberlist.msg.dead) where node is later seen alive (flaps)   -> page: false positives
 3  memberlist.degraded.probe rising on a subset of agents             -> those agents are sick (Lifeguard)
 4  p99 memberlist.pushPullNode > 1 s                                  -> large state or slow TCP
 5  members count differs across 3 sampled agents for > 60 s          -> convergence problem / partition

Real scenario: a deploy that restarts 20% of nodes at once and floods the broadcast queue; a firewall change that blocks UDP 8301 between two subnets (suspicions everywhere, TCP fallback pings succeed); a Cassandra node logging repeated DOWN/UP transitions for one peer after a NIC firmware bug.

Signalmemberlist / ConsulCassandraRedis ClusterAkka
Membership viewconsul members, serf membersnodetool status, nodetool gossipinfoCLUSTER NODES, CLUSTER INFOCluster HTTP management
Suspicion / doubtmemberlist.msg.suspectphi convictions in logsfail? flags"Marking node(s) as UNREACHABLE"
Local healthmemberlist.degraded.*GC logs, dropped messagescluster_stats_messages_* in CLUSTER INFO"Scheduled sending of heartbeat was delayed"
Churnalive/dead message ratesDOWN/UP transitions in logsFAIL broadcastsREACHABLE/UNREACHABLE logs

How to use it: chart suspicion rate, flap count, and membership size per node; alert on flaps, not on single suspicions. Metric design is owned by Observability.

Gossip vs centralised coordination Must-know ​

What must the cluster know?one agreed answer, or a fast approximate view?One answer, nowleader, lock, config, slot ownerConsensus (Raft / ZAB)etcd, ZooKeeper, Consul servers3 or 5 voters, not 5000Who is up, at scale100s to 1000s of long-lived peersGossip membership (SWIM)memberlist, Serf, Cassandra,Redis Cluster bus, Riak, AkkaShort-lived app processesPHP workers, jobs, podsCentral heartbeat registryRedis sorted set, DB row + TTL,Kubernetes probes and leasesCommon combination: gossip for membership and failure detection, consensus for decisionsConsul: Serf LAN/WAN gossip pools + Raft among servers. Redis Cluster: gossip PFAIL/FAIL + epoch votes for failover.Cassandra: gossip + phi accrual for liveness; a node leaves gossip state only by decommission or replace (operator action).

In plain words: Gossip answers "roughly who is around, soon". A consensus store (etcd, ZooKeeper, Consul servers) answers "exactly what is true, now", for a small set of voters. Use each for its question.

Common misunderstanding: "Gossip is a cheap replacement for ZooKeeper." Two nodes can both believe they are the leader under gossip, because their views differ for seconds and there is no agreement step. And ZooKeeper is not a replacement for gossip either: 5000 clients holding sessions against 5 servers is a heavy, centralised failure-detection load.

Definition: Centralised coordination means a small replicated service that orders all decisions through a consensus protocol (Raft in etcd and Consul, ZAB in ZooKeeper) and exposes linearizable reads, leases and watches; failure detection is session or lease expiry against that service. Gossip is decentralised, AP, convergent. Many systems combine them: Consul (Serf + Raft), Redis Cluster (gossip for detection + an epoch vote for failover), Kubernetes (etcd for state, node leases for liveness, no gossip).

 1  requirement: "exactly one scheduler runs the nightly billing job"
 2  gossip design: each node sorts the alive members and picks the lowest id
 3  t=0  partition: side 1 {A,B,C} sees D,E dead; side 2 {D,E} sees A,B,C dead
 4  t=10s side 1 picks A, side 2 picks D: billing runs twice                  <- wrong tool
 5  consensus design: lease in etcd (or Consul session); only the side with a quorum renews

Real scenario: service mesh control planes keep config in Kubernetes/etcd but data-plane health is local; a sharded cache ring built on memberlist (fine: a misrouted read is a cache miss) versus a sharded ledger (needs consensus for ownership); the Leader Election and Distributed Locking chapters own the consensus side.

QuestionGossipConsensus store (etcd, ZooKeeper, Consul servers)
Who is up?Yes, scales to thousandsYes via sessions/leases, but every member talks to the core
Who is the leader / lock owner?NoYes
Membership-derived routing (cache ring)Yes, misroutes are tolerablePossible, heavier
Config that must be identical everywhereEventuallyImmediately (linearizable reads)
Scale of participants1000s of peers3-7 voters, many clients
Partition behaviourBoth sides keep working with different viewsMinority side cannot decide

How to use it: for any decision where two answers would be harmful, use consensus; for liveness and discovery at scale, gossip. The SQL alternative for small fleets is a heartbeat table in the database you already have.

sql
-- PostgreSQL: a central heartbeat registry, the right size for tens of workers.
CREATE TABLE worker_heartbeats (
    worker_id    text PRIMARY KEY,
    incarnation  bigint      NOT NULL,
    last_seen    timestamptz NOT NULL DEFAULT now()
);

-- heartbeat: reject a zombie with an older incarnation
INSERT INTO worker_heartbeats (worker_id, incarnation)
VALUES ('web-3:1', 7)
ON CONFLICT (worker_id) DO UPDATE
   SET last_seen = now(), incarnation = EXCLUDED.incarnation
 WHERE worker_heartbeats.incarnation <= EXCLUDED.incarnation;

-- classify: alive < 15 s, suspect < 60 s, dead otherwise
SELECT worker_id,
       CASE WHEN now() - last_seen < interval '15 seconds' THEN 'alive'
            WHEN now() - last_seen < interval '60 seconds' THEN 'suspect'
            ELSE 'dead' END AS state
FROM worker_heartbeats
ORDER BY last_seen;

Mechanics ​

Every knob in one place ​

ProductKnobDefaultEffect
memberlistProbeInterval / ProbeTimeout1 s / 500 ms (LAN); 5 s / 3 s (WAN); 1 s / 200 ms (Local)Detection speed vs false positives
memberlistIndirectChecks3 (LAN), 1 (Local)ping-req helpers
memberlistSuspicionMult4 (LAN), 6 (WAN), 3 (Local)Suspicion = mult × max(1, log10 N) × ProbeInterval
memberlistSuspicionMaxTimeoutMult6Lifeguard upper bound multiplier
memberlistRetransmitMult4 (LAN), 2 (Local)Each broadcast sent mult × ceil(log10(N+1)) times
memberlistGossipInterval / GossipNodes200 ms / 3 (LAN); 500 ms / 4 (WAN); 100 ms (Local)Dedicated gossip fan-out
memberlistPushPullInterval30 s (LAN), 60 s (WAN), 15 s (Local)Anti-entropy
memberlistGossipToTheDeadTime30 s (LAN), 60 s (WAN)How long dead members still get gossip
memberlistAwarenessMaxMultiplier8Lifeguard probe back-off ceiling
memberlistTCPTimeout10 s (LAN), 30 s (WAN)Push/pull and fallback ping
memberlistBindPort7946UDP and TCP
memberlistSecretKey, Keyring, GossipVerifyIncoming/Outgoingnil, nil, true/trueEncryption
ConsulLAN / WAN pool ports8301 / 8302Gossip pools
Consulencrypt, encrypt_verify_incoming, encrypt_verify_outgoingunset, true, trueGossip key and staged rollout
Cassandraphi_convict_threshold8Conviction sensitivity
Cassandraseed_providerSimpleSeedProviderBootstrap contacts
Redis Clustercluster-node-timeoutSet by operator (docs example 5000)PFAIL time, minority stops accepting writes
Redis Clustercluster-portdata port + 10000Cluster bus
Redis Clustercluster-require-full-coverageyesStop writes when slots are uncovered
Akkafailure-detector.threshold8 (12 suggested on EC2)Phi threshold
Akkafailure-detector.acceptable-heartbeat-pauseConfigurable (docs example 7s)Margin for GC pauses
Akkaheartbeat interval1 sRequest/reply heartbeats

Convergence and detection arithmetic ​

QuantityFormulaWorked example
Push-pull dissemination≈ log2 N + small constant roundsN = 1000: about 10 rounds × 200 ms ≈ 2 s
Push anti-entropylog2 N + ln N + O(1) rounds (Demers)N = 1000: about 17 rounds
Rumour residues = e^-mm = 3 messages/site: about 5% residue
SWIM expected first detectionabout T' × e/(e−1) ≈ 1.58 T'T' = 1 s: about 1.6 s to first suspicion
SWIM worst case target selectionRound-robin: within 2N−1 periodsN = 1000, 1 s: under 33 min bound, average far lower
memberlist suspicion timeoutSuspicionMult × max(1, log10 N) × ProbeIntervalN = 1000 LAN: 4 × 3 × 1 s = 12 s
Lifeguard maximumSuspicionMaxTimeoutMult × that72 s at N = 1000, shrinking with confirmations
Retransmits per updateRetransmitMult × ceil(log10(N+1))N = 1000: 16
Time to declare a crash dead (LAN)probe (≈1-2 s) + suspicion (12 s) + dissemination (≈2 s)about 15-16 s at N = 1000
Redis Cluster failoverNODE_TIMEOUT + report gathering + election (usually 1-2 s)5 s timeout: about 6-8 s
Redis ping loadeach node pings peers silent for NODE_TIMEOUT/2100 nodes, 60 s: 330 pings/s total (spec example)

Messages and log lines you will see ​

SourceExact textMeaning
memberlist[DEBUG] memberlist: Failed UDP ping: <node> (timeout reached)Direct probe failed
memberlist[INFO] memberlist: Suspect <node> has failed, no acks receivedProbe round failed; suspicion raised
memberlist[WARN] memberlist: Refuting a suspect message (from: <node>)This member was suspected and refutes
memberlist[WARN] memberlist: Refuting a dead message (from: <node>)Declared dead but alive: rejoin with higher incarnation
memberlist[INFO] memberlist: Marking <node> as failed, suspect timeout reached (<n> peer confirmations)Suspicion timed out
memberlist[WARN] memberlist: Was able to connect to <node> over TCP but UDP probes failed, network may be misconfiguredUDP blocked
memberlist[ERR] memberlist: Push/Pull with <node> failed: <err>Anti-entropy failed
AkkaMarking node(s) as UNREACHABLE / Marking node(s) as REACHABLEPhi crossed the threshold / recovered
Akkaheartbeat interval is growing too largeArrivals exceed 2/3 of the acceptable pause
AkkaScheduled sending of heartbeat was delayedThe local node is starved
Redisfail? / fail flags in CLUSTER NODESPFAIL / FAIL
RedisFAILOVER_AUTH_REQUEST, FAILOVER_AUTH_ACKReplica election messages on the bus
ConsulserfHealth check criticalAgent left the LAN pool or failed

Where gossip state lives ​

ProductPer-member stateVersioning
memberlistname, address, port, meta (≤ 512 bytes), state, incarnation, state change timeIncarnation number
CassandraApplicationState map (STATUS, LOAD, SCHEMA, TOKENS, RELEASE_VERSION …) + heartbeat(generation, version)
Redis ClusterNode ID (160-bit), flags, slots bitmap, configEpoch, ip:port, cluster portcurrentEpoch / configEpoch
RiakRing (partition claims) + metadataVector clocks / version on the ring

Go ​

Before: all-to-all heartbeats with a fixed timeout ​

go
// Package heartbeat is the "before" design: every member sends a heartbeat
// to every other member each period and declares a peer dead after a fixed
// number of silent periods. It works for ten nodes and is what SWIM was
// written to replace: the message load grows with N squared, and one slow
// member is declared dead by everybody at once.
package heartbeat

import "math/rand/v2"

// Group is an all-to-all heartbeating group.
type Group struct {
	n        int
	timeout  int     // silent periods before a peer is declared dead
	loss     float64 // per-message loss probability
	rng      *rand.Rand
	tick     int
	crashed  []bool
	lastSeen [][]int // lastSeen[i][j]: last period i heard from j
	Messages int
	Declared int // dead declarations (i about j)
	False    int // dead declarations about members that were running
}

// New builds a group of n members.
func New(n, timeout int, loss float64, seed uint64) *Group {
	g := &Group{n: n, timeout: timeout, loss: loss, rng: rand.New(rand.NewPCG(seed, 1)),
		crashed: make([]bool, n), lastSeen: make([][]int, n)}
	for i := range g.lastSeen {
		g.lastSeen[i] = make([]int, n)
	}
	return g
}

// Crash stops member i.
func (g *Group) Crash(i int) { g.crashed[i] = true }

// Step runs one heartbeat period.
func (g *Group) Step() {
	g.tick++
	for i := 0; i < g.n; i++ {
		if g.crashed[i] {
			continue
		}
		for j := 0; j < g.n; j++ {
			if j == i {
				continue
			}
			g.Messages++
			if g.crashed[j] || g.rng.Float64() < g.loss {
				continue
			}
			g.lastSeen[j][i] = g.tick
		}
	}
	for i := 0; i < g.n; i++ {
		if g.crashed[i] {
			continue
		}
		for j := 0; j < g.n; j++ {
			if j != i && g.lastSeen[i][j] >= 0 && g.tick-g.lastSeen[i][j] >= g.timeout {
				g.Declared++
				if !g.crashed[j] {
					g.False++
				}
				g.lastSeen[i][j] = -1 << 30 // declared; never counted twice
			}
		}
	}
}
go
package heartbeat

import (
	"testing"

	"academy/gossip-protocols/swim"
)

// The same 10 periods cost N*(N-1) messages per period with all-to-all
// heartbeats and about 2 per member per period with SWIM.
func TestMessageLoadQuadraticVersusConstant(t *testing.T) {
	for _, n := range []int{10, 100, 500} {
		g := New(n, 3, 0, 1)
		c := swim.New(swim.Config{N: n, Seed: 1})
		for i := 0; i < 10; i++ {
			g.Step()
			c.Step()
		}
		perMemberHB := float64(g.Messages) / float64(10*n)
		perMemberSWIM := float64(c.Stats.Messages) / float64(10*n)
		t.Logf("n=%3d all-to-all: %7d msgs (%.0f/member/period)  SWIM: %6d msgs (%.1f/member/period)",
			n, g.Messages, perMemberHB, c.Stats.Messages, perMemberSWIM)
		if g.Messages != 10*n*(n-1) {
			t.Fatalf("all-to-all should send exactly N*(N-1) per period")
		}
		if perMemberSWIM > 3 {
			t.Fatalf("SWIM load per member should be constant, got %.1f", perMemberSWIM)
		}
	}
}

// With 30% loss and a 2-period timeout, all-to-all heartbeating produces
// false declarations; there is no second opinion before a verdict.
func TestFixedTimeoutFalsePositives(t *testing.T) {
	g := New(50, 2, 0.3, 2)
	for i := 0; i < 50; i++ {
		g.Step()
	}
	t.Logf("50 members, 30%% loss, timeout 2 periods: %d false dead declarations", g.False)
	if g.False == 0 {
		t.Fatal("expected false positives with a short fixed timeout on a lossy network")
	}
}

Epidemic dissemination: anti-entropy and rumour mongering ​

go
// Package epidemic simulates the two dissemination styles from Demers et al.
// (1987): anti-entropy (push, pull, push-pull) and rumour mongering with a
// counter and feedback. Time advances in synchronous cycles; in each cycle
// every site contacts one partner chosen uniformly at random.
package epidemic

import "math/rand/v2"

// Mode selects how two sites resolve their difference during anti-entropy.
type Mode int

const (
	Push     Mode = iota // the caller sends what it has
	Pull                 // the caller asks for what the partner has
	PushPull             // both directions in one exchange
)

func (m Mode) String() string {
	switch m {
	case Push:
		return "push"
	case Pull:
		return "pull"
	default:
		return "push-pull"
	}
}

// AntiEntropyResult describes one run of a simple epidemic.
type AntiEntropyResult struct {
	Cycles   int   // cycles until every site has the update
	Messages int   // contacts that carried the update
	Infected []int // infected sites after each cycle (index 0 = after cycle 1)
}

// AntiEntropy spreads one update injected at site 0 through n sites.
// Every site is active every cycle, as in anti-entropy, so the run always
// ends with all sites infected.
func AntiEntropy(n int, mode Mode, rng *rand.Rand) AntiEntropyResult {
	has := make([]bool, n)
	has[0] = true
	count := 1
	var res AntiEntropyResult
	for count < n {
		res.Cycles++
		next := make([]bool, n)
		copy(next, has)
		for s := 0; s < n; s++ {
			p := partner(n, s, rng)
			switch mode {
			case Push:
				if has[s] && !next[p] {
					next[p] = true
					res.Messages++
				}
			case Pull:
				if !has[s] && has[p] {
					next[s] = true
					res.Messages++
				}
			case PushPull:
				if has[s] && !next[p] {
					next[p] = true
					res.Messages++
				}
				if !has[s] && has[p] {
					next[s] = true
					res.Messages++
				}
			}
		}
		has = next
		count = 0
		for _, h := range has {
			if h {
				count++
			}
		}
		res.Infected = append(res.Infected, count)
	}
	return res
}

// RumorResult reports the three criteria Demers et al. use to judge an epidemic.
type RumorResult struct {
	Residue float64 // fraction of sites that never heard the rumour
	Traffic float64 // m: update messages sent per site
	TAve    float64 // average cycle in which a site received the update
	TLast   int     // cycle in which the last site received it
}

// Rumor runs push rumour mongering with feedback and a counter: an infective
// site loses interest after k contacts with sites that already knew.
func Rumor(n, k int, rng *rand.Rand) RumorResult {
	const (
		susceptible = iota
		infective
		removed
	)
	state := make([]int, n)
	counter := make([]int, n)
	got := make([]int, n)
	state[0] = infective
	active := 1
	sent := 0
	cycle := 0
	last := 0
	for active > 0 {
		cycle++
		var newly []int
		for s := 0; s < n; s++ {
			if state[s] != infective {
				continue
			}
			p := partner(n, s, rng)
			sent++
			if state[p] == susceptible {
				newly = append(newly, p)
				state[p] = -1 // marked; becomes infective at end of cycle
				continue
			}
			counter[s]++ // feedback: the partner already knew
			if counter[s] >= k {
				state[s] = removed
				active--
			}
		}
		for _, p := range newly {
			state[p] = infective
			got[p] = cycle
			last = cycle
			active++
		}
	}
	missed := 0
	sum := 0
	for s := 1; s < n; s++ {
		if state[s] == susceptible {
			missed++
			continue
		}
		sum += got[s]
	}
	res := RumorResult{
		Residue: float64(missed) / float64(n),
		Traffic: float64(sent) / float64(n),
		TLast:   last,
	}
	if n-1-missed > 0 {
		res.TAve = float64(sum) / float64(n-1-missed)
	}
	return res
}

func partner(n, self int, rng *rand.Rand) int {
	p := rng.IntN(n - 1)
	if p >= self {
		p++
	}
	return p
}
go
package epidemic

import (
	"math"
	"math/rand/v2"
	"testing"
)

// Push needs about log2(n) + ln(n) cycles (Demers et al.); pull and
// push-pull finish faster because the last few susceptible sites ask.
func TestAntiEntropyCyclesGrowLogarithmically(t *testing.T) {
	for _, n := range []int{100, 1000, 10000} {
		for _, mode := range []Mode{Push, Pull, PushPull} {
			total := 0
			const runs = 20
			for seed := uint64(1); seed <= runs; seed++ {
				total += AntiEntropy(n, mode, rand.New(rand.NewPCG(seed, 7))).Cycles
			}
			avg := float64(total) / runs
			bound := math.Log2(float64(n)) + math.Log(float64(n))
			t.Logf("n=%5d %-9s avg cycles %.1f (log2 n + ln n = %.1f)", n, mode, avg, bound)
			if avg > bound+3 {
				t.Fatalf("%s on %d sites took %.1f cycles, want about %.1f", mode, n, avg, bound)
			}
			if mode == PushPull && avg > math.Log2(float64(n))+4 {
				t.Fatalf("push-pull on %d sites took %.1f cycles", n, avg)
			}
		}
	}
}

// Table 1 in Demers et al. (1000 sites, feedback + counter): residue 0.18
// at k=1, 0.037 at k=2, 0.011 at k=3. Raising k trades traffic for coverage.
func TestRumorResidueFallsWithCounter(t *testing.T) {
	want := map[int]float64{1: 0.18, 2: 0.037, 3: 0.011}
	prev := 1.0
	for k := 1; k <= 5; k++ {
		var r RumorResult
		const runs = 50
		for seed := uint64(1); seed <= runs; seed++ {
			x := Rumor(1000, k, rand.New(rand.NewPCG(seed, 11)))
			r.Residue += x.Residue / runs
			r.Traffic += x.Traffic / runs
			r.TAve += x.TAve / runs
			r.TLast += x.TLast
		}
		t.Logf("k=%d residue %.4f traffic m=%.2f t_ave %.1f t_last %.1f",
			k, r.Residue, r.Traffic, r.TAve, float64(r.TLast)/runs)
		if r.Residue >= prev {
			t.Fatalf("residue did not fall at k=%d: %.4f >= %.4f", k, r.Residue, prev)
		}
		if w, ok := want[k]; ok && math.Abs(r.Residue-w) > w*0.5+0.005 {
			t.Fatalf("k=%d residue %.4f, paper reports %.3f", k, r.Residue, w)
		}
		// Demers: s = e^-m, the same traffic/residue law for every variant.
		if got := math.Exp(-r.Traffic); math.Abs(got-r.Residue) > 0.05 {
			t.Fatalf("k=%d e^-m = %.3f but residue %.3f", k, got, r.Residue)
		}
		prev = r.Residue
	}
}

After: a SWIM membership simulator ​

go
// Package swim is a deterministic, single-process simulator of the SWIM
// membership protocol (Das, Gupta, Motivala 2002) with the memberlist and
// Lifeguard refinements that matter for tuning:
//
//   - one probe per protocol period, round-robin over a shuffled member list
//   - ping, then ping-req through k random members (indirect probe)
//   - suspicion before death, refuted by the suspect with a higher incarnation
//   - membership updates piggybacked on ping/ack, each sent at most
//     RetransmitMult * ceil(log10(N+1)) times (the memberlist formula)
//   - optional Lifeguard suspicion: a long timeout that shrinks as
//     independent suspicions arrive, plus the buddy system
//   - message loss, slow ("deaf") members, crashes, partitions and a
//     reconnect step that lets partitioned sides find each other again
//
// Time is counted in protocol periods (ticks). Nothing here touches the network.
package swim

import (
	"math"
	"math/rand/v2"
	"sort"
)

// State of a member as seen by one node.
type State int

const (
	Alive State = iota
	Suspect
	Dead
)

func (s State) String() string {
	return [...]string{"alive", "suspect", "dead"}[s]
}

// Update is one membership fact carried by gossip.
type Update struct {
	Node  int
	State State
	Inc   uint64 // incarnation number of Node
	From  int    // who raised it (used for independent suspicions)
}

// Config holds the knobs. Zero values fall back to memberlist's LAN defaults
// where a default exists.
type Config struct {
	N              int
	IndirectChecks int // k, memberlist IndirectChecks (default 3)
	RetransmitMult int // lambda, memberlist RetransmitMult (default 4)
	MaxPiggyback   int // updates per message (SWIM prototype used 6)
	// SuspicionMult sets the fixed suspicion timeout in periods:
	// SuspicionMult * max(1, log10(N)), as memberlist computes it.
	SuspicionMult int
	// Lifeguard enables dynamic suspicion (Max = SuspicionMaxMult * Min,
	// shrinking with log(C+1)/log(K+1)) and the buddy system.
	Lifeguard        bool
	SuspicionMaxMult int // memberlist SuspicionMaxTimeoutMult (default 6)
	LifeguardK       int // independent suspicions to reach Min (default 3)
	LossRate         float64
	ReconnectProb    float64 // chance per period of a full sync with a dead member
	Seed             uint64
}

type entry struct {
	state      State
	inc        uint64
	since      int          // tick the current suspicion started
	suspectors map[int]bool // independent suspicions seen (Lifeguard)
}

type queued struct {
	u    Update
	sent int
}

type node struct {
	id     int
	inc    uint64
	view   map[int]*entry
	queue  []*queued
	order  []int
	cursor int
}

// Stats are counters a test or an operator dashboard would watch.
type Stats struct {
	Messages        int // every ping, ping-req, ack sent
	Suspicions      int // Suspect updates raised by a prober
	Refutations     int // Alive updates a member issued about itself
	DeadDeclared    int // local Suspect -> Dead transitions
	FalseDeclared   int // Dead declarations about members that were running
	PiggybackedFact int // updates carried on messages
}

// Cluster is the simulated group.
type Cluster struct {
	cfg     Config
	rng     *rand.Rand
	tick    int
	nodes   []*node
	crashed []bool
	deaf    []float64 // probability a member drops an incoming message
	group   []int     // partition id per member
	Stats   Stats
}

// New builds a cluster in which every member already knows every other
// member as alive at incarnation 0 (the state right after bootstrap).
func New(cfg Config) *Cluster {
	if cfg.IndirectChecks == 0 {
		cfg.IndirectChecks = 3
	}
	if cfg.IndirectChecks < 0 {
		cfg.IndirectChecks = 0
	}
	if cfg.RetransmitMult == 0 {
		cfg.RetransmitMult = 4
	}
	if cfg.MaxPiggyback == 0 {
		cfg.MaxPiggyback = 6
	}
	if cfg.SuspicionMult == 0 {
		cfg.SuspicionMult = 4
	}
	if cfg.SuspicionMaxMult == 0 {
		cfg.SuspicionMaxMult = 6
	}
	if cfg.LifeguardK == 0 {
		cfg.LifeguardK = 3
	}
	c := &Cluster{
		cfg:     cfg,
		rng:     rand.New(rand.NewPCG(cfg.Seed, 0x5157)),
		crashed: make([]bool, cfg.N),
		deaf:    make([]float64, cfg.N),
		group:   make([]int, cfg.N),
	}
	for i := 0; i < cfg.N; i++ {
		n := &node{id: i, view: map[int]*entry{}}
		for j := 0; j < cfg.N; j++ {
			if j != i {
				n.view[j] = &entry{state: Alive}
			}
		}
		c.nodes = append(c.nodes, n)
	}
	return c
}

// RetransmitLimit is memberlist's retransmitLimit: mult * ceil(log10(n+1)).
func RetransmitLimit(mult, n int) int {
	return mult * int(math.Ceil(math.Log10(float64(n+1))))
}

// SuspicionPeriods is memberlist's suspicionTimeout expressed in periods.
func SuspicionPeriods(mult, n int) float64 {
	return float64(mult) * math.Max(1, math.Log10(math.Max(1, float64(n))))
}

// Tick is the current protocol period.
func (c *Cluster) Tick() int { return c.tick }

// Crash stops a member: it sends nothing and receives nothing.
func (c *Cluster) Crash(i int) { c.crashed[i] = true }

// SetDeaf makes a member drop a fraction of incoming messages, the way a
// member behaves under CPU starvation or a long GC pause.
func (c *Cluster) SetDeaf(i int, p float64) { c.deaf[i] = p }

// Partition assigns members to sides; messages cross sides never.
func (c *Cluster) Partition(groups []int) { copy(c.group, groups) }

// Heal removes every partition.
func (c *Cluster) Heal() {
	for i := range c.group {
		c.group[i] = 0
	}
}

// Inject queues an update at one member as if it had just learned it.
func (c *Cluster) Inject(at int, u Update) {
	c.apply(c.nodes[at], u)
}

// View returns what member i believes about member m.
func (c *Cluster) View(i, m int) (State, uint64) {
	if i == m {
		return Alive, c.nodes[i].inc
	}
	e := c.nodes[i].view[m]
	return e.state, e.inc
}

// AllSee reports whether every running member other than m sees m in state s.
func (c *Cluster) AllSee(m int, s State) bool {
	for i, n := range c.nodes {
		if i == m || c.crashed[i] {
			continue
		}
		if n.view[m].state != s {
			return false
		}
	}
	return true
}

// AllAgreeAlive reports whether every running member sees every other
// running member as alive: the membership has converged.
func (c *Cluster) AllAgreeAlive() bool {
	for i := range c.nodes {
		if c.crashed[i] {
			continue
		}
		if !c.AllSee(i, Alive) {
			return false
		}
	}
	return true
}

// Step runs one protocol period at every running member.
func (c *Cluster) Step() {
	c.tick++
	for _, i := range c.rng.Perm(c.cfg.N) {
		if c.crashed[i] {
			continue
		}
		n := c.nodes[i]
		c.expireSuspicions(n)
		c.probe(n)
		if c.cfg.ReconnectProb > 0 && c.rng.Float64() < c.cfg.ReconnectProb {
			c.reconnect(n)
		}
	}
}

// Run steps until cond is true or max periods pass; it returns the periods used.
func (c *Cluster) Run(max int, cond func() bool) (int, bool) {
	start := c.tick
	for c.tick-start < max {
		c.Step()
		if cond() {
			return c.tick - start, true
		}
	}
	return c.tick - start, false
}

func (c *Cluster) nextTarget(n *node) (int, bool) {
	for attempts := 0; attempts < 2; attempts++ {
		for n.cursor < len(n.order) {
			t := n.order[n.cursor]
			n.cursor++
			if e := n.view[t]; e != nil && e.state != Dead {
				return t, true
			}
		}
		// Traversal finished: reshuffle, as SWIM section 4.3 prescribes.
		n.order = n.order[:0]
		for m := range n.view {
			n.order = append(n.order, m)
		}
		sort.Ints(n.order)
		c.rng.Shuffle(len(n.order), func(a, b int) { n.order[a], n.order[b] = n.order[b], n.order[a] })
		n.cursor = 0
	}
	return 0, false
}

func (c *Cluster) probe(n *node) {
	t, ok := c.nextTarget(n)
	if !ok {
		return
	}
	// Direct ping and ack.
	if c.send(n.id, t) && c.send(t, n.id) {
		return
	}
	// Indirect probe: ping-req through k random members.
	helpers := c.pickHelpers(n, t)
	for _, h := range helpers {
		if c.send(n.id, h) && c.send(h, t) && c.send(t, h) && c.send(h, n.id) {
			return
		}
	}
	e := n.view[t]
	if e.state == Alive {
		c.Stats.Suspicions++
		c.apply(n, Update{Node: t, State: Suspect, Inc: e.inc, From: n.id})
	}
}

func (c *Cluster) pickHelpers(n *node, target int) []int {
	var cand []int
	for m, e := range n.view {
		if m != target && e.state == Alive {
			cand = append(cand, m)
		}
	}
	sort.Ints(cand)
	c.rng.Shuffle(len(cand), func(a, b int) { cand[a], cand[b] = cand[b], cand[a] })
	if len(cand) > c.cfg.IndirectChecks {
		cand = cand[:c.cfg.IndirectChecks]
	}
	return cand
}

// send delivers one message from a to b, piggybacking gossip both ways of
// the exchange's first leg; it returns false when the message is lost.
func (c *Cluster) send(a, b int) bool {
	c.Stats.Messages++
	if c.crashed[a] || c.crashed[b] || c.group[a] != c.group[b] {
		return false
	}
	if c.cfg.LossRate > 0 && c.rng.Float64() < c.cfg.LossRate {
		return false
	}
	if c.deaf[b] > 0 && c.rng.Float64() < c.deaf[b] {
		return false
	}
	for _, u := range c.piggyback(c.nodes[a], b) {
		c.Stats.PiggybackedFact++
		c.receive(c.nodes[b], u)
	}
	return true
}

// piggyback picks the least-sent updates; with Lifeguard's buddy system an
// update that suspects the recipient goes first.
func (c *Cluster) piggyback(n *node, to int) []Update {
	if len(n.queue) == 0 {
		return nil
	}
	sort.SliceStable(n.queue, func(i, j int) bool {
		if c.cfg.Lifeguard {
			bi := n.queue[i].u.Node == to && n.queue[i].u.State == Suspect
			bj := n.queue[j].u.Node == to && n.queue[j].u.State == Suspect
			if bi != bj {
				return bi
			}
		}
		return n.queue[i].sent < n.queue[j].sent
	})
	limit := RetransmitLimit(c.cfg.RetransmitMult, c.cfg.N)
	var out []Update
	keep := n.queue[:0]
	for i, q := range n.queue {
		if i < c.cfg.MaxPiggyback {
			out = append(out, q.u)
			q.sent++
		}
		if q.sent < limit {
			keep = append(keep, q)
		}
	}
	n.queue = keep
	return out
}

func (c *Cluster) enqueue(n *node, u Update) {
	// A newer fact about the same member replaces the older one.
	for _, q := range n.queue {
		if q.u.Node == u.Node {
			q.u = u
			q.sent = 0
			return
		}
	}
	n.queue = append(n.queue, &queued{u: u})
}

func (c *Cluster) receive(n *node, u Update) {
	if u.Node == n.id {
		// Refutation: only the member itself may raise its incarnation.
		if u.State != Alive && u.Inc >= n.inc {
			n.inc = u.Inc + 1
			c.Stats.Refutations++
			c.enqueue(n, Update{Node: n.id, State: Alive, Inc: n.inc, From: n.id})
		}
		return
	}
	c.apply(n, u)
}

// apply implements SWIM's precedence rules (memberlist names Confirm "dead"):
//
//	Alive(i)   overrides Suspect(j) and Alive(j) when i > j (and Dead(j), a rejoin)
//	Suspect(i) overrides Suspect(j) when i > j, Alive(j) when i >= j
//	Dead(i)    overrides Alive(j) and Suspect(j) when i >= j
func (c *Cluster) apply(n *node, u Update) {
	if u.Node == n.id {
		c.receive(n, u)
		return
	}
	e := n.view[u.Node]
	switch u.State {
	case Alive:
		if u.Inc <= e.inc {
			return
		}
		e.state, e.inc, e.suspectors = Alive, u.Inc, nil
	case Suspect:
		if e.state == Dead {
			return
		}
		if e.state == Suspect && u.Inc == e.inc {
			// Same suspicion from another member: an independent confirmation.
			if !e.suspectors[u.From] {
				e.suspectors[u.From] = true
				if c.cfg.Lifeguard && len(e.suspectors) <= c.cfg.LifeguardK+1 {
					c.enqueue(n, u)
				}
			}
			return
		}
		if u.Inc < e.inc || (e.state == Suspect && u.Inc <= e.inc) {
			return
		}
		e.state, e.inc, e.since = Suspect, u.Inc, c.tick
		e.suspectors = map[int]bool{u.From: true}
	case Dead:
		if e.state == Dead || u.Inc < e.inc {
			return
		}
		e.state, e.inc, e.suspectors = Dead, u.Inc, nil
	}
	c.enqueue(n, u)
}

func (c *Cluster) suspicionTimeout(e *entry) float64 {
	min := SuspicionPeriods(c.cfg.SuspicionMult, c.cfg.N)
	if !c.cfg.Lifeguard {
		return min
	}
	max := float64(c.cfg.SuspicionMaxMult) * min
	confirmations := float64(len(e.suspectors) - 1)
	frac := math.Log(confirmations+1) / math.Log(float64(c.cfg.LifeguardK)+1)
	return math.Max(min, max-(max-min)*frac)
}

func (c *Cluster) expireSuspicions(n *node) {
	for m, e := range n.view {
		if e.state != Suspect {
			continue
		}
		if float64(c.tick-e.since) >= c.suspicionTimeout(e) {
			c.Stats.DeadDeclared++
			if !c.crashed[m] {
				c.Stats.FalseDeclared++
			}
			c.apply(n, Update{Node: m, State: Dead, Inc: e.inc, From: n.id})
		}
	}
}

// reconnect is a full state exchange (memberlist push/pull, Serf reconnect,
// Cassandra's "gossip with an unreachable node") with a member this node
// believes dead. It is what lets two healed partition sides find each other.
func (c *Cluster) reconnect(n *node) {
	var dead []int
	for m, e := range n.view {
		if e.state == Dead {
			dead = append(dead, m)
		}
	}
	if len(dead) == 0 {
		return
	}
	sort.Ints(dead)
	p := dead[c.rng.IntN(len(dead))]
	if !c.send(n.id, p) || !c.send(p, n.id) {
		return
	}
	c.pushPull(n, c.nodes[p])
	c.pushPull(c.nodes[p], n)
}

func (c *Cluster) pushPull(from, to *node) {
	c.receive(to, Update{Node: from.id, State: Alive, Inc: from.inc, From: from.id})
	for m, e := range from.view {
		c.receive(to, Update{Node: m, State: e.state, Inc: e.inc, From: from.id})
	}
}
go
package swim

import (
	"math"
	"testing"
)

func TestMemberlistFormulas(t *testing.T) {
	// memberlist DefaultLANConfig: RetransmitMult 4, SuspicionMult 4, ProbeInterval 1s.
	cases := []struct {
		n          int
		retransmit int
		suspicion  float64
	}{
		{10, 8, 4}, {100, 12, 8}, {1000, 16, 12}, {5000, 16, 4 * math.Log10(5000)},
	}
	for _, tc := range cases {
		if got := RetransmitLimit(4, tc.n); got != tc.retransmit {
			t.Fatalf("RetransmitLimit(4,%d) = %d, want %d", tc.n, got, tc.retransmit)
		}
		if got := SuspicionPeriods(4, tc.n); math.Abs(got-tc.suspicion) > 1e-9 {
			t.Fatalf("SuspicionPeriods(4,%d) = %.2f, want %.2f", tc.n, got, tc.suspicion)
		}
	}
}

// A crashed member is suspected after one failed probe round, declared dead
// after the suspicion timeout and the verdict reaches everyone.
func TestCrashIsDetectedAndDisseminated(t *testing.T) {
	for _, n := range []int{16, 64, 256} {
		c := New(Config{N: n, Seed: 1})
		c.Crash(7)
		periods, ok := c.Run(200, func() bool { return c.AllSee(7, Dead) })
		if !ok {
			t.Fatalf("n=%d: crash never fully disseminated", n)
		}
		// Worst case: one full round-robin traversal (n-1 periods) to be
		// probed at all, plus the suspicion timeout, plus dissemination.
		bound := float64(n) + SuspicionPeriods(4, n) + 20
		t.Logf("n=%3d crash -> all see dead in %3d periods, %6d messages, %.1f msg/member/period",
			n, periods, c.Stats.Messages, float64(c.Stats.Messages)/float64(n*periods))
		if float64(periods) > bound {
			t.Fatalf("n=%d took %d periods, bound %.0f", n, periods, bound)
		}
		if c.Stats.FalseDeclared != 0 {
			t.Fatalf("n=%d: %d false positives on a clean network", n, c.Stats.FalseDeclared)
		}
	}
}

// Dissemination of one fact by piggybacking grows with log N, not N.
func TestPiggybackDisseminationIsLogarithmic(t *testing.T) {
	rounds := map[int]int{}
	for _, n := range []int{16, 128, 1024} {
		total := 0
		const runs = 5
		for seed := uint64(1); seed <= runs; seed++ {
			c := New(Config{N: n, Seed: seed})
			c.Inject(0, Update{Node: 1, State: Suspect, Inc: 0, From: 0})
			p, ok := c.Run(100, func() bool { return c.AllSee(1, Alive) && c.nodes[1].inc == 1 })
			if !ok {
				t.Fatalf("n=%d seed=%d: refutation did not converge", n, seed)
			}
			total += p
		}
		rounds[n] = total / runs
		t.Logf("n=%4d suspicion+refutation converged in %d periods (log2 n = %.0f)", n, rounds[n], math.Log2(float64(n)))
	}
	if rounds[1024] > 3*rounds[16]+4 {
		t.Fatalf("1024 members took %d periods vs %d for 16: not logarithmic", rounds[1024], rounds[16])
	}
}

// A member that misses pings for a moment is suspected, hears about it,
// raises its incarnation number and stays in the group.
func TestSuspicionIsRefutedWithIncarnation(t *testing.T) {
	c := New(Config{N: 32, SuspicionMult: 8, Seed: 3})
	c.SetDeaf(5, 1.0)
	_, ok := c.Run(60, func() bool {
		for i := 0; i < 32; i++ {
			if s, _ := c.View(i, 5); i != 5 && s == Suspect {
				return true
			}
		}
		return false
	})
	if !ok {
		t.Fatal("member 5 was never suspected")
	}
	c.SetDeaf(5, 0)
	_, ok = c.Run(60, func() bool { return c.AllSee(5, Alive) && c.nodes[5].inc >= 1 })
	if !ok {
		t.Fatal("refutation did not reach the group")
	}
	if c.Stats.FalseDeclared != 0 {
		t.Fatalf("member 5 was declared dead %d times", c.Stats.FalseDeclared)
	}
	_, inc := c.View(0, 5)
	t.Logf("member 5 refuted %d time(s); member 0 now sees incarnation %d", c.Stats.Refutations, inc)
}

// Indirect probes (ping-req) absorb packet loss on the direct path.
func TestIndirectProbesCutFalseSuspicions(t *testing.T) {
	suspicions := func(k int) int {
		c := New(Config{N: 64, IndirectChecks: k, LossRate: 0.05, Seed: 9})
		c.Run(100, func() bool { return false })
		return c.Stats.Suspicions
	}
	without, with := suspicions(-1), suspicions(3)
	t.Logf("5%% loss, 100 periods, 64 members: suspicions k=0: %d, k=3: %d", without, with)
	if with*5 > without {
		t.Fatalf("k=3 should cut suspicions by far more than 5x: %d vs %d", with, without)
	}
}

// A slow member that drops most incoming messages keeps suspecting healthy
// peers (it misses their acks) and cannot hear refutations. Lifeguard's
// longer, confirmation-driven timeout and buddy system reduce the damage.
func TestLifeguardReducesFalsePositives(t *testing.T) {
	falsePositives := func(lifeguard bool) int {
		total := 0
		for seed := uint64(1); seed <= 5; seed++ {
			c := New(Config{N: 64, SuspicionMult: 1, Lifeguard: lifeguard, Seed: seed})
			for _, slow := range []int{3, 4, 5, 6} {
				c.SetDeaf(slow, 0.7)
			}
			c.Run(150, func() bool { return false })
			total += c.Stats.FalseDeclared
		}
		return total
	}
	plain, lg := falsePositives(false), falsePositives(true)
	t.Logf("4 slow members, 150 periods x 5 seeds: local false dead declarations SWIM=%d Lifeguard=%d", plain, lg)
	if lg >= plain {
		t.Fatalf("Lifeguard did not reduce false positives: %d vs %d", lg, plain)
	}
}

// During a partition each side declares the other dead; after healing, the
// reconnect step (a push/pull with a dead member) merges the views and
// refutations with higher incarnations bring everyone back.
func TestPartitionAndHeal(t *testing.T) {
	const n = 40
	c := New(Config{N: n, ReconnectProb: 0.05, Seed: 4})
	groups := make([]int, n)
	for i := n / 2; i < n; i++ {
		groups[i] = 1
	}
	c.Partition(groups)
	p, ok := c.Run(300, func() bool { return sideSeesOtherDead(c, n) })
	if !ok {
		t.Fatal("sides never declared each other dead")
	}
	t.Logf("partition: both sides see the other as dead after %d periods", p)
	c.Heal()
	p, ok = c.Run(300, c.AllAgreeAlive)
	if !ok {
		t.Fatal("membership did not converge after heal")
	}
	t.Logf("heal: full membership converged after %d periods, %d refutations", p, c.Stats.Refutations)
}

func sideSeesOtherDead(c *Cluster, n int) bool {
	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			if (i < n/2) == (j < n/2) {
				continue
			}
			if s, _ := c.View(i, j); s != Dead {
				return false
			}
		}
	}
	return true
}

Phi accrual failure detector ​

go
// Package phi implements the phi accrual failure detector (Hayashibara et
// al. 2004) the way Akka and Cassandra use it: a sliding window of heartbeat
// inter-arrival times, a normal distribution fitted to it, and
//
//	phi = -log10(1 - F(timeSinceLastHeartbeat))
//
// The detector does not answer "up or down"; it outputs a suspicion level
// and the caller compares it with a threshold (Akka and Cassandra default 8).
package phi

import (
	"math"
	"time"
)

// Detector tracks one peer. It is not safe for concurrent use.
type Detector struct {
	window          []float64 // inter-arrival times in milliseconds
	max             int
	last            time.Time
	minStdDev       float64 // ms; keeps phi finite when heartbeats are very regular
	acceptablePause float64 // ms added to the mean (Akka acceptable-heartbeat-pause)
}

// New creates a detector with a window of size samples.
func New(size int, minStdDev, acceptablePause time.Duration) *Detector {
	return &Detector{
		max:             size,
		minStdDev:       float64(minStdDev.Milliseconds()),
		acceptablePause: float64(acceptablePause.Milliseconds()),
	}
}

// Heartbeat records an arrival.
func (d *Detector) Heartbeat(at time.Time) {
	if !d.last.IsZero() {
		d.window = append(d.window, float64(at.Sub(d.last).Milliseconds()))
		if len(d.window) > d.max {
			d.window = d.window[1:]
		}
	}
	d.last = at
}

// Phi returns the suspicion level at time now. It returns 0 until two
// heartbeats have been seen.
func (d *Detector) Phi(now time.Time) float64 {
	if len(d.window) == 0 {
		return 0
	}
	mean, std := d.stats()
	mean += d.acceptablePause
	elapsed := float64(now.Sub(d.last).Milliseconds())
	// 1 - F(t) for a normal distribution, computed with erfc for precision.
	pLater := 0.5 * math.Erfc((elapsed-mean)/(std*math.Sqrt2))
	if pLater < 1e-300 {
		return math.Inf(1)
	}
	if pLater >= 1 {
		return 0
	}
	return -math.Log10(pLater)
}

// Available compares phi with a threshold, as Cassandra's
// phi_convict_threshold and Akka's failure-detector.threshold do.
func (d *Detector) Available(now time.Time, threshold float64) bool {
	return d.Phi(now) < threshold
}

func (d *Detector) stats() (mean, std float64) {
	for _, x := range d.window {
		mean += x
	}
	mean /= float64(len(d.window))
	var v float64
	for _, x := range d.window {
		v += (x - mean) * (x - mean)
	}
	std = math.Sqrt(v / float64(len(d.window)))
	if std < d.minStdDev {
		std = d.minStdDev
	}
	return mean, std
}
go
package phi

import (
	"math/rand/v2"
	"testing"
	"time"
)

func feed(d *Detector, start time.Time, n int, every, jitter time.Duration, seed uint64) time.Time {
	rng := rand.New(rand.NewPCG(seed, 3))
	at := start
	for i := 0; i < n; i++ {
		j := time.Duration(rng.NormFloat64() * float64(jitter))
		at = at.Add(every + j)
		d.Heartbeat(at)
	}
	return at
}

// Phi rises with silence; how fast depends on the observed jitter.
func TestPhiRisesWithSilence(t *testing.T) {
	start := time.Unix(0, 0)
	steady := New(1000, 100*time.Millisecond, 0)
	last := feed(steady, start, 200, time.Second, 50*time.Millisecond, 1)
	jittery := New(1000, 100*time.Millisecond, 0)
	lastJ := feed(jittery, start, 200, time.Second, 400*time.Millisecond, 1)

	for _, s := range []time.Duration{time.Second, 1500 * time.Millisecond, 2 * time.Second, 3 * time.Second} {
		t.Logf("silence %-5v phi steady=%6.2f jittery=%6.2f", s, steady.Phi(last.Add(s)), jittery.Phi(lastJ.Add(s)))
	}
	if p := steady.Phi(last.Add(time.Second)); p > 1 {
		t.Fatalf("phi right on schedule should be low, got %.2f", p)
	}
	if steady.Available(last.Add(2*time.Second), 8) {
		t.Fatal("a steady peer silent for 2 s should be convicted at threshold 8")
	}
	if !jittery.Available(lastJ.Add(2*time.Second), 8) {
		t.Fatal("a jittery peer silent for 2 s should not be convicted yet")
	}
}

// acceptable-heartbeat-pause shifts the curve to the right: a GC pause of
// that length does not convict.
func TestAcceptablePause(t *testing.T) {
	start := time.Unix(0, 0)
	plain := New(1000, 100*time.Millisecond, 0)
	paused := New(1000, 100*time.Millisecond, 3*time.Second)
	last := feed(plain, start, 100, time.Second, 50*time.Millisecond, 2)
	feed(paused, start, 100, time.Second, 50*time.Millisecond, 2)
	at := last.Add(3 * time.Second)
	t.Logf("3 s silence: phi without pause %.1f, with 3 s acceptable pause %.2f", plain.Phi(at), paused.Phi(at))
	if plain.Available(at, 8) || !paused.Available(at, 8) {
		t.Fatal("acceptable pause should keep the peer available")
	}
}

// Raising the threshold from 8 to 12 (Akka's advice for EC2) buys time.
func TestThresholdTradeOff(t *testing.T) {
	start := time.Unix(0, 0)
	d := New(1000, 100*time.Millisecond, 0)
	last := feed(d, start, 200, time.Second, 200*time.Millisecond, 4)
	convict := func(threshold float64) time.Duration {
		for s := time.Duration(0); s < time.Minute; s += 10 * time.Millisecond {
			if !d.Available(last.Add(s), threshold) {
				return s
			}
		}
		return time.Minute
	}
	t8, t12 := convict(8), convict(12)
	t.Logf("time to conviction: threshold 8 -> %v, threshold 12 -> %v", t8, t12)
	if t12 <= t8 {
		t.Fatal("a higher threshold must take longer to convict")
	}
}

The real thing: hashicorp/memberlist ​

go
// Command memberlistdemo shows the hashicorp/memberlist API that Consul,
// Serf and Nomad build on. It compiles without a cluster; it only joins one
// when GOSSIP_NAME and GOSSIP_SEEDS are set, for example:
//
//	GOSSIP_NAME=node-a GOSSIP_PORT=7946 GOSSIP_SEEDS=192.0.2.10:7946 \
//	GOSSIP_KEY=$(head -c 32 /dev/urandom | base64) go run ./memberlistdemo
package main

import (
	"encoding/base64"
	"fmt"
	"log"
	"os"
	"strconv"
	"strings"
	"time"

	"github.com/hashicorp/memberlist"
)

func main() {
	name, seeds := os.Getenv("GOSSIP_NAME"), os.Getenv("GOSSIP_SEEDS")
	if name == "" || seeds == "" {
		fmt.Println("set GOSSIP_NAME and GOSSIP_SEEDS to join a cluster; printing LAN defaults instead")
		printDefaults(memberlist.DefaultLANConfig())
		return
	}

	// DefaultLANConfig: ProbeInterval 1s, ProbeTimeout 500ms, IndirectChecks 3,
	// SuspicionMult 4, GossipInterval 200ms, GossipNodes 3, PushPullInterval 30s.
	// DefaultWANConfig and DefaultLocalConfig exist for the other two cases.
	conf := memberlist.DefaultLANConfig()
	conf.Name = name
	if p, err := strconv.Atoi(os.Getenv("GOSSIP_PORT")); err == nil {
		conf.BindPort, conf.AdvertisePort = p, p
	}

	// Gossip encryption: a 16, 24 or 32 byte key selects AES-128/192/256.
	// A Keyring holds several keys so they can be rotated without downtime
	// (install new key everywhere, switch primary, then remove the old one).
	if k := os.Getenv("GOSSIP_KEY"); k != "" {
		key, err := base64.StdEncoding.DecodeString(k)
		if err != nil {
			log.Fatalf("GOSSIP_KEY: %v", err)
		}
		ring, err := memberlist.NewKeyring(nil, key)
		if err != nil {
			log.Fatalf("keyring: %v", err)
		}
		conf.Keyring = ring
		conf.GossipVerifyIncoming, conf.GossipVerifyOutgoing = true, true
	}

	events := make(chan memberlist.NodeEvent, 64)
	conf.Events = &memberlist.ChannelEventDelegate{Ch: events}

	list, err := memberlist.Create(conf)
	if err != nil {
		log.Fatalf("create: %v", err)
	}
	defer func() { _ = list.Shutdown() }()

	// Join contacts the seeds over TCP, does a full push/pull state sync and
	// returns how many it reached. One reachable seed is enough.
	n, err := list.Join(strings.Split(seeds, ","))
	if err != nil {
		log.Fatalf("join: reached %d seeds: %v", n, err)
	}
	log.Printf("joined via %d seed(s); %d alive members", n, list.NumMembers())

	deadline := time.After(30 * time.Second)
	for {
		select {
		case ev := <-events:
			kind := map[memberlist.NodeEventType]string{
				memberlist.NodeJoin: "join", memberlist.NodeLeave: "leave", memberlist.NodeUpdate: "update",
			}[ev.Event]
			log.Printf("%s %s %s", kind, ev.Node.Name, ev.Node.Address())
		case <-deadline:
			for _, m := range list.Members() {
				log.Printf("member %s %s", m.Name, m.Address())
			}
			// Leave broadcasts an intent to leave so peers mark us "left",
			// not "dead"; it waits up to the timeout for the broadcast.
			if err := list.Leave(5 * time.Second); err != nil {
				log.Printf("leave: %v", err)
			}
			return
		}
	}
}

func printDefaults(c *memberlist.Config) {
	fmt.Printf("BindPort=%d ProbeInterval=%v ProbeTimeout=%v IndirectChecks=%d\n",
		c.BindPort, c.ProbeInterval, c.ProbeTimeout, c.IndirectChecks)
	fmt.Printf("SuspicionMult=%d SuspicionMaxTimeoutMult=%d RetransmitMult=%d AwarenessMaxMultiplier=%d\n",
		c.SuspicionMult, c.SuspicionMaxTimeoutMult, c.RetransmitMult, c.AwarenessMaxMultiplier)
	fmt.Printf("GossipInterval=%v GossipNodes=%d PushPullInterval=%v GossipToTheDeadTime=%v\n",
		c.GossipInterval, c.GossipNodes, c.PushPullInterval, c.GossipToTheDeadTime)
}
mod
module academy/gossip-protocols

go 1.24.0

require github.com/hashicorp/memberlist v0.5.4

require (
	github.com/armon/go-metrics v0.4.1 // indirect
	github.com/google/btree v1.1.3 // indirect
	github.com/hashicorp/errwrap v1.1.0 // indirect
	github.com/hashicorp/go-immutable-radix v1.0.0 // indirect
	github.com/hashicorp/go-metrics v0.5.4 // indirect
	github.com/hashicorp/go-msgpack/v2 v2.1.5 // indirect
	github.com/hashicorp/go-multierror v1.1.1 // indirect
	github.com/hashicorp/go-sockaddr v1.0.7 // indirect
	github.com/hashicorp/golang-lru v0.5.0 // indirect
	github.com/miekg/dns v1.1.68 // indirect
	github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529 // indirect
	golang.org/x/mod v0.28.0 // indirect
	golang.org/x/net v0.47.0 // indirect
	golang.org/x/sync v0.17.0 // indirect
	golang.org/x/sys v0.38.0 // indirect
	golang.org/x/tools v0.37.0 // indirect
)

The Go angle ​

  • The simulator is deterministic: math/rand/v2 with a seeded rand.NewPCG, and every map iteration that affects randomness is sorted first. That is what makes go test reproduce the numbers on this page; a gossip test that depends on wall-clock time and real UDP is flaky by construction.
  • hashicorp/memberlist is pinned at v0.5.4 here because it is the newest release whose go.mod says go 1.24.0; v0.6.0 requires Go 1.25. go mod tidy rewrote this module's directive to go 1.24.0 for the same reason.
  • memberlist's API surface you use daily: DefaultLANConfig() / DefaultWANConfig() / DefaultLocalConfig(), Create(conf), Join(seeds) (int, error), Members(), NumMembers(), LocalNode(), Leave(timeout), Shutdown(), NewKeyring(keys, primary). Hooks: Delegate (NodeMeta, NotifyMsg, GetBroadcasts, LocalState, MergeRemoteState) to piggyback your own state, EventDelegate / ChannelEventDelegate for join/leave/update, TransmitLimitedQueue for your own retransmit-limited broadcasts.
  • Use LocalState/MergeRemoteState for anti-entropy of application state and keep it small: it travels on every push/pull. Combine it with a CRDT if several nodes write the same key.
  • hashicorp/serf (the library behind serf agent) adds tags, user events and queries if you need more than membership. For a sharded service, pair memberlist with rendezvous or consistent hashing (Consistent Hashing); a misrouted request during convergence must be safe.
  • Metrics come from github.com/hashicorp/go-metrics; register a Prometheus sink to get the memberlist.* series listed above.
  • Outside HashiCorp: Uber's Ringpop (Node.js, SWIM) and Habitat's Butterfly (Rust) are the other mature SWIM implementations the Lifeguard paper names.

Laravel ​

Gossip is not a PHP application-level tool. A PHP-FPM request lives for milliseconds and a queue worker is one of hundreds of short-lived processes; neither can run a SWIM member, hold UDP sockets, or keep a membership list between requests. The Laravel-sized problem is "which of my workers are alive?", and the right answer is a central registry in Redis (or the database) that borrows gossip's ideas: suspicion before death, incarnation numbers against zombies, and atomic reaping.

Before: one cache key per worker ​

php
<?php

namespace App\Services\Before;

use Illuminate\Support\Facades\Cache;

/**
 * Before: one cache key per worker with a TTL, plus an index array kept in
 * the cache. It looks fine on one server and goes wrong at scale:
 *  - the index is read-modify-write, so two workers registering at once
 *    lose one entry (lost update);
 *  - TTL expiry is the only verdict: one late heartbeat (GC, deploy, a slow
 *    Redis round trip) is instant death, there is no suspect step;
 *  - a restarted worker with the same id is indistinguishable from the
 *    old process that is still running somewhere (no incarnation).
 */
class CacheHeartbeatRegistry
{
    public function heartbeat(string $workerId): void
    {
        Cache::put("worker:{$workerId}", now()->getTimestamp(), 30);

        $index = Cache::get('workers:index', []);
        $index[$workerId] = true;
        Cache::forever('workers:index', $index);
    }

    /** @return list<string> */
    public function alive(): array
    {
        $alive = [];
        foreach (array_keys(Cache::get('workers:index', [])) as $workerId) {
            if (Cache::has("worker:{$workerId}")) {
                $alive[] = $workerId;
            }
        }

        return $alive;
    }
}

After: a Redis presence registry with suspicion and incarnations ​

php
<?php

namespace App\Services;

use App\Events\WorkerDeclaredDead;
use Illuminate\Support\Facades\Redis;

/**
 * A central presence registry for queue workers, backed by Redis.
 *
 * This is NOT gossip. A PHP request or a queue worker is too short-lived and
 * too numerous to run a SWIM member; the Laravel-sized problem is "which
 * workers are up?", and one Redis (or a Redis replica set with Sentinel) is
 * the coordinator. The registry borrows the ideas that make gossip failure
 * detectors robust:
 *  - a sorted set scored by last heartbeat time, so one ZRANGE classifies all;
 *  - two thresholds: alive -> suspect -> dead, instead of one TTL;
 *  - an incarnation number per worker process, so a heartbeat from an old
 *    process that was already replaced is rejected;
 *  - reaping in one Lua script, so two schedulers never double-reap.
 */
class WorkerRegistry
{
    // One hash tag keeps all keys in one Redis Cluster slot, so the Lua
    // scripts below never touch keys in two slots (CROSSSLOT).
    private const BEATS = '{workers}:heartbeats';
    private const INCARNATIONS = '{workers}:incarnations';
    private const META = '{workers}:meta';

    public function __construct(
        private readonly int $suspectAfter = 15,
        private readonly int $deadAfter = 60,
    ) {}

    /** Called once when a worker process boots; returns its incarnation. */
    public function register(string $workerId, array $meta = []): int
    {
        $incarnation = (int) Redis::hincrby(self::INCARNATIONS, $workerId, 1);

        Redis::hset(self::META, $workerId, json_encode([
            'incarnation' => $incarnation,
            'host' => $meta['host'] ?? gethostname(),
            'queues' => $meta['queues'] ?? ['default'],
        ]));
        $this->heartbeat($workerId, $incarnation);

        return $incarnation;
    }

    /**
     * Record a heartbeat. Returns false when a newer incarnation of the same
     * worker exists: the caller is a zombie and should exit.
     */
    public function heartbeat(string $workerId, int $incarnation): bool
    {
        $accepted = Redis::eval(<<<'LUA'
            local current = tonumber(redis.call('HGET', KEYS[2], ARGV[1]) or '0')
            if tonumber(ARGV[2]) < current then
                return 0
            end
            redis.call('ZADD', KEYS[1], ARGV[3], ARGV[1])
            return 1
            LUA, 2, self::BEATS, self::INCARNATIONS, $workerId, $incarnation, $this->now());

        return (int) $accepted === 1;
    }

    /**
     * Classify every known worker.
     *
     * @return array{alive: list<string>, suspect: list<string>, dead: list<string>}
     */
    public function snapshot(): array
    {
        $now = $this->now();
        $out = ['alive' => [], 'suspect' => [], 'dead' => []];

        foreach (Redis::zrange(self::BEATS, 0, -1, ['withscores' => true]) as $workerId => $lastSeen) {
            $age = $now - (int) $lastSeen;
            $state = match (true) {
                $age < $this->suspectAfter => 'alive',
                $age < $this->deadAfter => 'suspect',
                default => 'dead',
            };
            $out[$state][] = (string) $workerId;
        }

        return $out;
    }

    /**
     * Remove workers silent for longer than deadAfter. Atomic, so running it
     * from two servers at once reaps each worker once.
     *
     * @return list<string>
     */
    public function reap(): array
    {
        $reaped = Redis::eval(<<<'LUA'
            local dead = redis.call('ZRANGEBYSCORE', KEYS[1], '-inf', ARGV[1])
            for _, id in ipairs(dead) do
                redis.call('ZREM', KEYS[1], id)
                redis.call('HDEL', KEYS[2], id)
            end
            return dead
            LUA, 2, self::BEATS, self::META, $this->now() - $this->deadAfter);

        $reaped = array_map('strval', (array) $reaped);
        foreach ($reaped as $workerId) {
            WorkerDeclaredDead::dispatch($workerId);
        }

        return $reaped;
    }

    /** Graceful leave: a worker that stops on purpose is not "dead". */
    public function leave(string $workerId): void
    {
        Redis::zrem(self::BEATS, $workerId);
        Redis::hdel(self::META, $workerId);
    }

    private function now(): int
    {
        return now()->getTimestamp();
    }
}
php
<?php

namespace App\Events;

use Illuminate\Foundation\Events\Dispatchable;

class WorkerDeclaredDead
{
    use Dispatchable;

    public function __construct(public readonly string $workerId) {}
}
php
<?php

namespace App\Providers;

use App\Services\WorkerRegistry;
use Illuminate\Queue\Events\WorkerStopping;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\ServiceProvider;

/**
 * Heartbeats from inside `php artisan queue:work`: Queue::looping runs before
 * the worker fetches each job, so a heartbeat at most every 5 seconds costs
 * one Redis round trip per 5 seconds, not one per job.
 */
class WorkerPresenceServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->singleton(WorkerRegistry::class, fn () => new WorkerRegistry(
            suspectAfter: (int) config('workers.suspect_after', 15),
            deadAfter: (int) config('workers.dead_after', 60),
        ));
    }

    public function boot(): void
    {
        if (! $this->app->runningInConsole()) {
            return;
        }

        $registry = $this->app->make(WorkerRegistry::class);
        // A stable id per Supervisor slot (process_num), so a restarted
        // worker reuses its id and its incarnation number fences the old one.
        $workerId = gethostname().':'.(config('workers.slot') ?? getmypid());
        $incarnation = null;
        $lastBeat = 0;

        Queue::looping(function () use ($registry, $workerId, &$incarnation, &$lastBeat) {
            $incarnation ??= $registry->register($workerId, ['queues' => ['default']]);

            if (time() - $lastBeat < 5) {
                return;
            }
            $lastBeat = time();

            if (! $registry->heartbeat($workerId, $incarnation)) {
                // A newer incarnation owns this id. Returning false from a
                // looping listener makes Worker::daemonShouldRun() false, so
                // this process pauses instead of taking more jobs.
                return false;
            }
        });

        Event::listen(WorkerStopping::class, fn () => $registry->leave($workerId));
    }
}
php
<?php

namespace App\Console\Commands;

use App\Services\WorkerRegistry;
use Illuminate\Console\Command;

class ReapWorkers extends Command
{
    protected $signature = 'workers:reap';

    protected $description = 'Report suspect workers and remove dead ones from the presence registry';

    public function handle(WorkerRegistry $registry): int
    {
        $snapshot = $registry->snapshot();
        $this->info(sprintf('alive=%d suspect=%d dead=%d',
            count($snapshot['alive']), count($snapshot['suspect']), count($snapshot['dead'])));

        foreach ($snapshot['suspect'] as $workerId) {
            $this->warn("suspect: {$workerId}");
        }
        foreach ($registry->reap() as $workerId) {
            $this->error("reaped: {$workerId}");
        }

        return self::SUCCESS;
    }
}
php
<?php

use Illuminate\Support\Facades\Schedule;

// One reaper for the whole fleet: onOneServer takes an atomic cache lock,
// so the default cache store must be redis, database, memcached or dynamodb.
Schedule::command('workers:reap')
    ->everyMinute()
    ->onOneServer()
    ->withoutOverlapping();
php
<?php

namespace Tests\Feature;

use App\Events\WorkerDeclaredDead;
use App\Services\WorkerRegistry;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Redis;
use Tests\TestCase;

/** Requires a Redis server (REDIS_HOST); uses a dedicated database index. */
class WorkerRegistryTest extends TestCase
{
    protected function setUp(): void
    {
        parent::setUp();
        Redis::flushdb();
    }

    public function test_alive_then_suspect_then_dead(): void
    {
        Event::fake([WorkerDeclaredDead::class]);
        $registry = new WorkerRegistry(suspectAfter: 15, deadAfter: 60);

        $this->travelTo(now()->startOfMinute());
        $registry->register('w1');
        $this->assertSame(['w1'], $registry->snapshot()['alive']);

        $this->travel(20)->seconds();
        $this->assertSame(['w1'], $registry->snapshot()['suspect']);
        $this->assertSame([], $registry->reap());

        $this->travel(45)->seconds();
        $this->assertSame(['w1'], $registry->snapshot()['dead']);
        $this->assertSame(['w1'], $registry->reap());
        Event::assertDispatched(WorkerDeclaredDead::class, fn ($e) => $e->workerId === 'w1');
    }

    public function test_old_incarnation_is_rejected(): void
    {
        $registry = new WorkerRegistry;

        $old = $registry->register('w1');
        $new = $registry->register('w1');

        $this->assertSame($old + 1, $new);
        $this->assertFalse($registry->heartbeat('w1', $old));
        $this->assertTrue($registry->heartbeat('w1', $new));
    }
}

The Laravel angle ​

  • The Redis facade "supports dynamic methods, meaning you may call any Redis command on the facade", so Redis::zrange, Redis::hincrby and Redis::zrem map straight to Redis commands. Redis::eval($script, $numberOfKeys, ...$arguments) runs Lua atomically; the registry uses it so the incarnation check and the ZADD, and the reap's ZRANGEBYSCORE + ZREM + HDEL, cannot interleave with another process.
  • Keys carry the hash tag {workers} so all three live in one Redis Cluster slot; a Lua script that touched keys in two slots would fail with CROSSSLOT. Laravel's Redis key prefix is applied to KEYS[] by phpredis but not to ARGV[], which is why the scripts never build key names from arguments.
  • Queue::looping registers a callback "that execute[s] before the worker attempts to fetch a job from a queue". In the Laravel 13 Worker, daemonShouldRun() returns false when a Looping listener returns false, so a zombie with an old incarnation pauses instead of taking jobs. The provider throttles heartbeats to one per 5 seconds.
  • Illuminate\Queue\Events\WorkerStopping lets a worker leave gracefully (the registry's leave()), the equivalent of memberlist's left state: a planned stop is not a failure.
  • The reaper is scheduled with Schedule::command('workers:reap')->everyMinute()->onOneServer(). onOneServer needs the default cache driver to be database, memcached, dynamodb or redis, and "all servers must be communicating with the same central cache server". The Lua reap is atomic anyway, so a double run is harmless.
  • Cache::lock is the tool for "exactly one" inside Laravel; do not derive leadership from the registry snapshot, for the same reason gossip cannot elect a leader.
  • Laravel Horizon already tracks its own supervisors and worker processes for its dashboard; use this registry when you need your own liveness semantics (suspect vs dead, incarnations) or run plain queue:work under Supervisor.
  • If Laravel talks to a gossip-based system (Cassandra, Redis Cluster, Consul), the client library handles membership: Redis Cluster clients follow MOVED/ASK redirects; Consul is queried through its HTTP API or DNS, which reflect gossip-derived health.

Solving the classic problems ​

Healthy nodes keep getting declared dead ​

SolutionHowAdvantageCost / limitation
Find the local cause firstGC logs, CPU steal, cgroup throttling, NIC drops on the accuserFixes the rootNeeds host metrics
LifeguardUse memberlist / Serf 0.8+ / Consul (on by default)Self-tuning, big reduction in false positivesSlower detection when the accuser is unhealthy
Longer suspicionRaise SuspicionMult (memberlist)More time to refuteSlower true detection
Higher phi thresholdphi_convict_threshold 10-12 (Cassandra), threshold 12 (Akka on EC2)Tolerates noisy networksSlower conviction
Acceptable pauseAkka acceptable-heartbeat-pauseAbsorbs known GC pausesHides real stalls of that length

A deploy restarts many nodes and membership goes wild ​

SolutionHowAdvantageCost / limitation
Graceful leaveLeave(timeout) before shutdown; Laravel WorkerStoppingPeers mark left, no suspicion stormNeeds SIGTERM handling
Rolling restartsRestart at most a few percent at a timeBroadcast queue stays smallSlower deploys
Stable identity + incarnationSame node name, higher incarnation on restartRejoin overrides old stateName collisions must be prevented
Push/pull syncKeep PushPullInterval enabledRepairs dropped broadcastsTCP cost proportional to N

A partition heals but the sides do not see each other ​

SolutionHowAdvantageCost / limitation
Reconnect to failed membersSerf reconnects to failed nodes; Cassandra gossips with unreachable nodes probabilisticallyAutomatic healExtra traffic during long outages
Seeds on both sidesOne seed per AZ/regionRejoin always has a contactSeed list maintenance
Refutation on learning "dead"Higher incarnation alive messageOverrides stale dead stateRequires the member to hear about it
Operator checkconsul members, nodetool status, CLUSTER NODES on both sidesConfirms convergenceManual

The Go TestPartitionAndHeal shows the full cycle: both halves of a 40-member cluster declare each other dead in 15 periods; after healing, the reconnect step plus refutations converge in 60 periods.

Two nodes both act as leader ​

SolutionHowAdvantageCost / limitation
Consensus leaseetcd lease, ZooKeeper ephemeral node, Consul sessionOnly a quorum side can hold itExtra system
Fencing tokenMonotonic epoch checked by the resourceStops a stale leader's writesResource must check it (Distributed Locking)
Majority + epoch voteRedis Cluster style configEpochNo external storeComplex to implement correctly
Akka Split Brain Resolverkeep-majority, static-quorum, lease-majority strategiesDecides downing consistentlyMust be configured

Gossip traffic is too high ​

SolutionHowAdvantageCost / limitation
Smaller metadataKeep node meta and events smallFewer packetsLess information per node
Longer intervalsWAN-style config on slow linksLess bandwidthSlower convergence
Separate poolsConsul LAN per datacenter, WAN for servers onlyCross-region traffic stays smallMore pools to operate
Partial viewsHyParView-style overlayScales past full membershipNew library, harder to debug

Choosing ​

SituationRecommendationExtra techniqueReason
Go service fleet needs peer discovery and livenessmemberlist (or Serf)Encryption keyring, metrics sinkProven SWIM + Lifeguard
Service catalog, health checks, DNSConsulACLs, gossip key, TLS for RPCGossip for membership, Raft for catalog
Leader, lock, unique scheduleretcd / ZooKeeper / Consul sessionsFencing tokensNeeds agreement, not convergence
Cassandra or ScyllaDB clusterBuilt-in gossipSeeds per DC, leave phi_convict_threshold at 8 unless provenThe database owns it
Redis ClusterBuilt-in busTune cluster-node-timeout against failover speedPFAIL/FAIL + votes
Laravel queue workersRedis heartbeat registrySuspect/dead thresholds, incarnation, onOneServer reaperProcesses are short-lived
Kubernetes podsLiveness/readiness probes, node leasesPodDisruptionBudgetsThe orchestrator is the coordinator (Containers & Kubernetes)
Tens of nodes, simple opsCentral heartbeat table or RedisTTL + suspicionGossip's complexity buys nothing
10 000+ peers, high churnPartial views (HyParView, Plumtree)Separate failure detectionFull membership too expensive
Replicated config that may diverge brieflyGossip + CRDTMerkle or digest anti-entropyMerge order does not matter
Config that must be identical before useConsensus store with watchesVersioned keysLinearizable reads

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

There is nothing to gossip about: one process knows it is alive. Liveness is the load balancer's health check and a process supervisor (systemd, Supervisor). The first gossip-shaped need is a few background workers; a row per worker in the existing database (the SQL above) or a Redis sorted set is the simplest correct design, with suspect and dead thresholds instead of a single TTL.

Modular monolith: boundaries without the network ​

Several deployable units (web, workers, scheduler) share a database or Redis. Each module that needs "who is running?" should use one registry with an owner (the infrastructure module), not ad-hoc cache keys per feature. Exactly-one jobs use Cache::lock or onOneServer, never "the oldest worker in the registry".

Microservices: every arrow is a decision ​

Service instances come and go with deploys and autoscaling. Discovery is usually Kubernetes Services/Endpoints or Consul; with Consul, every node's agent is in the LAN gossip pool and services register with the Raft-backed catalog. Example flow: orders scales from 6 to 9 pods; three new Consul agents join via retry_join (gossip, seconds), register orders instances (Raft), health checks pass, and payments resolves orders.service.consul to nine addresses. If a node dies, gossip marks it failed, serfHealth goes critical and its instances leave DNS within about the suspicion timeout. Design for that window: retries with timeouts (Timeouts, Retries & Jitter) and idempotent handlers. The architecture decision is in Service Discovery.

Distributed data: replicas, caches, regions ​

Databases embed gossip: Cassandra shares tokens and schema versions and uses phi for routing; Redis Cluster gossips slots and failure reports and fails over by majority; Riak gossips the ring. Membership is AP, but data correctness relies on other layers: quorums and hinted handoff (Replication Topologies), Merkle-tree repair, tombstones within gc_grace_seconds. Across regions, keep gossip pools per region (Consul WAN pool only among servers; Cassandra per-DC seeds) and expect WAN suspicion timeouts of tens of seconds. A region partition makes each side see the other as dead; anything that must stay unique across regions needs consensus or a single home region (CAP & PACELC).

Scaling path: 1x, 10x, 100x ​

ScaleMembership designWhat to watch
1x: 10 nodesCentral registry or Kubernetes probes; a Consul cluster if you already run itNothing exotic
10x: 100-1000 nodesmemberlist/Serf/Consul LAN defaults; database-native gossipSuspicion rate, flaps, push/pull time
100x: 10 000 nodes, multi-regionPer-region pools, WAN config between regions, small metadata, LifeguardBroadcast queue depth, convergence time, packet rates
Beyond: 100 000 peers or high churnPartial views (HyParView + Plumtree), hierarchical membershipView health, overlay diameter

Lab: measuring gossip in a single process ​

All experiments use the Go module above; they are single-process simulations and were run on the author's machine (go test -v ./..., Go 1.27, darwin/arm64). Numbers depend on the seeds in the tests.

  1. Anti-entropy cycles grow with log N.
cd docs/snippets/system-design/gossip-protocols/go
go test -v -run TestAntiEntropyCyclesGrowLogarithmically ./epidemic/
# n= 1000 push      avg cycles 18.6 (log2 n + ln n = 16.9)
# n= 1000 pull      avg cycles 13.8 (log2 n + ln n = 16.9)
# n= 1000 push-pull avg cycles 9.1 (log2 n + ln n = 16.9)
# n=10000 push-pull avg cycles 11.5 (log2 n + ln n = 22.5)
  1. Rumour residue against Demers Table 1.
go test -v -run TestRumorResidueFallsWithCounter ./epidemic/
# k=1 residue 0.2020 traffic m=1.59 t_ave 9.9 t_last 17.4
# k=2 residue 0.0598 traffic m=2.82 ...
# k=5 residue 0.0023 traffic m=5.98 ...
  1. Crash detection, constant load.
go test -v -run 'TestCrash|TestMessageLoad' ./swim/ ./heartbeat/
# n=256 crash -> all see dead in  17 periods,   8745 messages, 2.0 msg/member/period
# n=500 all-to-all: 2495000 msgs (499/member/period)  SWIM:  10000 msgs (2.0/member/period)
  1. Indirect probes and Lifeguard.
go test -v -run 'TestIndirect|TestLifeguard' ./swim/
# 5% loss, 100 periods, 64 members: suspicions k=0: 542, k=3: 2
# 4 slow members, 150 periods x 5 seeds: local false dead declarations SWIM=11121 Lifeguard=215
  1. Partition and heal.
go test -v -run TestPartitionAndHeal ./swim/
# partition: both sides see the other as dead after 15 periods
# heal: full membership converged after 60 periods, 40 refutations
  1. Phi curves and thresholds.
go test -v ./phi/
# silence 2s    phi steady= 23.22 jittery=  2.28
# time to conviction: threshold 8 -> 2.11s, threshold 12 -> 2.38s
  1. A real memberlist cluster (expected, not run). Two terminals on two hosts in a documentation range:
# host 192.0.2.10
GOSSIP_NAME=a GOSSIP_PORT=7946 GOSSIP_SEEDS=192.0.2.10:7946 GOSSIP_KEY=<base64-32> go run ./memberlistdemo
# host 192.0.2.11
GOSSIP_NAME=b GOSSIP_PORT=7946 GOSSIP_SEEDS=192.0.2.10:7946 GOSSIP_KEY=<base64-32> go run ./memberlistdemo
# expected on a: join b 192.0.2.11:7946
# kill -STOP b's process for 20 s: a logs "Suspect b has failed, no acks received",
#   then "Marking b as failed, suspect timeout reached" if it stays stopped past ~4 s (N=2)
# kill -CONT: b logs "Refuting a dead message", a logs join b again
  1. Laravel registry (expected, not run). With Redis running and the provider registered:
php artisan queue:work &            # registers web-1:<pid>, heartbeats every 5 s
php artisan workers:reap            # alive=1 suspect=0 dead=0
kill -STOP %1; sleep 20; php artisan workers:reap   # alive=0 suspect=1 dead=0  "suspect: web-1:..."
sleep 45; php artisan workers:reap                  # "reaped: web-1:..."

Common misconceptions ​

BeliefReality
Gossip is slow because it is randomO(log N) rounds: 1000 nodes in about 10 push-pull rounds
More fan-out is always betterRounds fall only logarithmically, bandwidth grows linearly
Gossip guarantees everyone agrees at some instantIt converges when updates stop; views differ in between
A suspected node is deadIt failed one probe round; it can refute with a higher incarnation
Anyone can revive a suspected nodeOnly the member raises its incarnation; others only spread its alive message
False positives come from the slow targetOften from the slow prober; Lifeguard exists for that
phi 8 means 8 secondsφ is −log10 of a probability; 8 means about 10^-8
Seed nodes are mastersOrdinary members with known addresses; multiple per failure domain
Rumour mongering alone is reliableIt leaves a residue; pair it with anti-entropy
Deleting a node from the list removes itPeers gossip it back; gossip a dead/left state or use the product's removal command
Cassandra removes dead nodes automaticallyOnly decommission or replace removes a node from gossip
Gossip can elect a leaderViews diverge under partition; use consensus
Gossip on a private network needs no encryptionAnyone inside can forge suspicions or read topology
PHP apps should embed a gossip libraryProcesses are short-lived; use a central registry

Cheat sheet ​

TopicRemember
ConvergenceAbout log2 N rounds push-pull; × gossip interval
Anti-entropyFull-state reconciliation, always converges, run with digests
Rumour mongeringFast, cheap, residue s = e^-m
Push vs pullPush good early, pull finishes; push-pull best
SWIMping, ping-req via k = 3, suspect, dead; constant load
IncarnationOnly the member increments it; alive(i) beats suspect(j) when i > j
PiggybackingUpdates ride on pings/acks, sent λ log N times
memberlist LAN1 s probe, 500 ms timeout, 200 ms gossip to 3, 30 s push/pull
Suspicion timeout4 × log10(N) × 1 s: 12 s at N = 1000
LifeguardLHM back-off, dynamic suspicion (6× max), buddy system, nack
Phi accrualφ = −log10(P_later); threshold 8 in Cassandra and Akka
Redis ClusterPFAIL after NODE_TIMEOUT, FAIL with majority of masters within 2 × NODE_TIMEOUT
CassandraGossip every second, (generation, version), UP/DOWN local, no auto removal
SeedsOrdinary members, 2-3 per failure domain, discovered not hard-coded
SecurityAES keyring, install-use-remove rotation, firewall gossip ports
Gossip vs consensusLiveness at scale vs one agreed answer

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — Why does push-pull anti-entropy finish faster than push when only a few nodes are still uninformed? Important ​

Answer

Answer: With pull, an uninformed node only needs to pick any informed partner, which is nearly certain once most nodes are informed, so the uninformed fraction shrinks quadratically per round. With push it must be chosen by some informed node, so the fraction shrinks only by about a factor e per round. Push-pull gets the pull behaviour at the end and the push behaviour at the start.

2 — A memberlist LAN cluster has 1000 members. How long, roughly, from a crash until every member considers it dead? Good to know ​

Answer

Answer: First probe of the dead node within about 1-2 s (one probe per second, random round-robin), then the suspicion timeout 4 × log10(1000) × 1 s = 12 s, then dissemination of the dead message in about log N gossip rounds at 200 ms, about 2 s. Total about 15-16 s. Lifeguard may make the first suspicion's timer longer until other members confirm it.

3 — Why does SWIM use ping-req through k members instead of retrying the direct ping? Important ​

Answer

Answer: A retry uses the same network path, so congestion or a bad link between prober and target fails again. Indirect probes use k different paths; if any helper reaches the target, the problem was the path, not the target, and no suspicion is raised.

4 — Member D receives suspect(D, inc 4) while its own incarnation is 4. What does it do, and why can no other member do the same? Good to know ​

Answer

Answer: It sets its incarnation to 5 and gossips alive(D, 5), which overrides suspect(D, 4) everywhere. If other members could raise D's incarnation, a delayed or forged alive message could override a correct dead verdict; the incarnation is D's own clock for statements about itself.

5 — What is a rumour mongering residue, and how do production systems deal with it? Good to know ​

Answer

Answer: The fraction of nodes still uninformed when all spreaders have lost interest (Demers: 18% at k = 1, 3.7% at k = 2 on 1000 sites). Systems raise the retransmit count (memberlist RetransmitMult × ceil(log10(N+1))) and run periodic anti-entropy (memberlist push/pull every 30 s) to repair the residue.

6 — Which member does Lifeguard assume might be at fault, and what are its three mechanisms? Good to know ​

Answer

Answer: The local (probing) member. Local Health Aware Probe slows probing with a Local Health Multiplier that rises on failed probes, missed nacks and self-refutations; Local Health Aware Suspicion starts with a long timeout that shrinks as independent confirmations arrive; the Buddy System piggybacks the suspicion to the suspect first so it can refute sooner.

7 — Cassandra's phi detector convicts a node. Will Cassandra rebalance its data? Important ​

Answer

Answer: No. Conviction stops routing reads to it (writes typically become hints), and UP/DOWN is a local decision that is not gossiped. Cassandra removes a node from gossip state only through decommission or a replacement bootstrap with replace_address_first_boot, to avoid needless rebalancing.

8 — Describe the PFAIL to FAIL transition in Redis Cluster. Important ​

Answer

Answer: A node flags a peer PFAIL (shown as fail? in CLUSTER NODES) when an active ping has been pending longer than NODE_TIMEOUT. PFAIL flags travel in gossip sections as failure reports. When a node has reports from a majority of masters within NODE_TIMEOUT × 2, it marks the peer FAIL and broadcasts a FAIL message, which forces every receiver to mark FAIL; replicas can then run an election.

9 — Why can you not elect a leader by "the alive member with the lowest id" over gossip? Important ​

Answer

Answer: Views differ during convergence and especially during partitions; each side computes its own lowest id, and both act as leader. Leader election needs an agreement step with a quorum (Raft, ZooKeeper, an etcd lease) plus fencing.

10 — How do you rotate a gossip encryption key in Consul without downtime? Good to know ​

Answer

Answer: Generate a key with consul keygen, install it everywhere with consul keyring -install (agents now accept both keys), verify with -list, switch the primary with -use, then remove the old key with -remove. The keyring lets old and new keys coexist during the change.

11 — Why is a Laravel queue worker registry not built with a gossip protocol, and which gossip ideas does it keep? Good to know ​

Answer

Answer: PHP processes are short-lived and numerous and cannot hold a membership list or UDP sockets between requests, so a central Redis or database registry is simpler and correct at that scale. It keeps two thresholds (suspect before dead), incarnation numbers to reject zombies, a graceful leave distinct from death, and atomic reaping.

Glossary ​

TermMeaning
Gossip / epidemic protocolDissemination by repeated exchanges with random peers
Anti-entropyPeriodic pairwise full-state reconciliation; always converges
Rumour mongeringSpreading a hot update until k contacts already knew it; leaves a residue
Push gossipThe informed node sends to its partner
Pull gossipThe node asks its partner for newer data
Push-pullBoth directions in one exchange
ResidueFraction of nodes that never received an update
Fan-outPeers contacted per gossip round
ConvergenceAll live nodes hold the same version of the state
Convergence timeTime from injection until the last node has the update
O(log N) roundsGossip's dissemination time as a function of cluster size
MembershipEach node's list of other members and their states
Eventually consistent membershipViews agree after changes stop; may differ meanwhile
Failure detectionDeciding that a member has crashed; trades speed for accuracy
HeartbeatPeriodic "I am alive" message
False positiveA healthy member declared failed
SWIMScalable Weakly-consistent Infection-style Membership protocol (2002)
Ping / ackDirect probe and its reply
Ping-reqRequest to k members to probe a target on the requester's behalf
Indirect probeThe probe sent through ping-req helpers
NackLifeguard reply from a helper that got no ack from the target
SuspicionIntermediate state before a member is declared dead
Suspicion timeoutTime a suspect has to refute before being declared dead
Incarnation numberPer-member counter only that member increments to refute suspicion
Confirm / dead / leftSWIM's final failure verdict / memberlist's name for it / graceful leave
DisseminationSpreading membership updates to all members
PiggybackingCarrying updates on protocol messages already being sent
Retransmit limitHow many times one update is sent (memberlist mult × ceil(log10(N+1)))
LifeguardSWIM extensions for local health: LHM, dynamic suspicion, buddy system
Local Health MultiplierLifeguard counter that scales probe interval and timeout
Buddy systemLifeguard rule: tell the suspect about its suspicion first
Phi-accrual failure detectorOutputs φ = −log10(P_later) from heartbeat inter-arrival history
Phi thresholdφ level at which a peer is convicted (Cassandra and Akka default 8)
Acceptable heartbeat pauseAkka margin added to the expected interval
Seed nodeWell-known member contacted to bootstrap
BootstrapJoining: contact a seed, sync state, announce yourself
Push/pull syncmemberlist full-state exchange over TCP (anti-entropy)
Partial viewBounded random subset of members a node gossips with
HyParViewPartial-view protocol with active and passive views
CyclonPartial-view protocol based on periodic view shuffling
PlumtreeEpidemic broadcast tree over HyParView
memberlistHashiCorp Go library implementing SWIM + Lifeguard
SerfHashiCorp membership/event tool built on memberlist
ConsulService discovery with Serf gossip pools and a Raft catalog
LAN / WAN gossip poolConsul pools inside a datacenter (8301) / among servers across datacenters (8302)
Cassandra gossipPer-second exchange of versioned endpoint state
Generation / versionCassandra gossip versioning: startup timestamp / logical clock
Redis Cluster busBinary node-to-node TCP protocol on data port + 10000
PFAIL / FAILRedis Cluster possible failure (local) / failure confirmed by majority
Failure reportPFAIL/FAIL flag about a node carried in gossip sections
NODE_TIMEOUTRedis cluster-node-timeout; base for PFAIL and failover timings
Riak ringRiak's partition ownership, shared by gossip
Dynamo membershipExplicit join/leave history reconciled by gossip every second
Death certificate / tombstoneGossiped deletion record that cancels older copies
KeyringSet of gossip keys: one primary, all accepted, for rotation
Gossip encryptionSymmetric AES encryption of gossip packets
ChurnRate of membership changes
FlappingA member alternating alive and dead
CRDTData type whose replicas merge in any order to the same value
Merkle treeHash tree for finding differences between replicas cheaply
Centralised coordinationSmall consensus-replicated service (etcd, ZooKeeper, Consul servers) for decisions
Split brainTwo sides of a partition acting independently as if they were the whole

References ​

Built by Morteza Negahi