Skip to content

Heartbeats, Failure Detection and Gossip

Advanced 51 min read Part 9 of 18

How systems decide a node is dead: heartbeats, fixed vs phi-accrual timeouts, cluster membership, gossip, SWIM, and avoiding false positives and split brain.

Summary#

A distributed system must constantly answer "which nodes are alive?", so it can route requests away from dead ones, re-replicate their data and elect replacements. The basic tool is the heartbeat: a small periodic message that says "I am still here". If heartbeats stop for longer than a timeout, the node is suspected dead. But silence is ambiguous: the node may have crashed, or it may be slow, paused, or cut off by the network. So every failure detector trades detection speed against false positives. A fixed timeout is simple, but it is either too slow or too jumpy. A phi-accrual detector learns the normal rhythm of each node's heartbeats and reports a suspicion level, so the threshold adapts to real network conditions. Large clusters also need membership: an agreed list of nodes. Small clusters can keep it in a consensus store such as etcd or ZooKeeper, while large ones spread it with gossip, where each node periodically exchanges state with a few random peers and news reaches every node in a number of rounds that grows only logarithmically with cluster size. SWIM combines gossip with a smarter probe: if a direct ping fails, ask a few other nodes to ping the target too, and mark it suspect before declaring it dead, which keeps false positives low with constant load per node. Cassandra uses gossip with phi-accrual detection, and Consul, Nomad and Serf use SWIM through HashiCorp's memberlist library. Whatever the detector, a node declared dead may still be alive, so actions taken on a failure verdict, such as promoting a new leader, must be protected by quorums and fencing, or the system can end up with two leaders, a split brain.

Why It Exists#

On one machine, a crashed component is obvious: the process exits, and the operating system knows. Across a network, a crashed node simply goes quiet, and so does a node behind a broken switch, a node paused for garbage collection, and a node whose disk has stalled. From the outside they look the same. Yet the system must react:

  • Load balancers must stop sending traffic to a dead server within seconds, or users see errors.
  • Databases must promote a replica when the primary dies, or writes stop.
  • Replicated stores such as Cassandra or HDFS must notice that a node is gone, so reads go elsewhere and lost replicas are rebuilt.
  • Leader-based systems such as Raft clusters must detect a dead leader and elect a new one.
  • Service discovery must remove dead instances from the list that clients use.

Reacting too slowly means long outages. Reacting too quickly means treating healthy-but-slow nodes as dead, which triggers failovers, data movement and retries, adding load at the worst possible moment, and, if the "dead" node is still running, it can lead to two nodes each believing they are the leader.

And all of this has to work at scale. In a cluster of 5 nodes, every node can ping every other node. In a cluster of 5,000, all-to-all pinging means 25 million heartbeat messages per interval, so failure detection itself has to be distributed and cheap.

How It Works#

A failure detector is a module on each node that, when asked about another node, answers "trusted" or "suspected". It is built from three pieces:

  1. Evidence: messages that show a node is alive. Heartbeats it sends, replies to probes, or normal traffic.
  2. A decision rule: when the absence of evidence becomes suspicion. A fixed timeout, an adaptive one, or a statistical score.
  3. Dissemination: how a verdict, or the raw evidence, reaches the rest of the cluster. Direct messages, a central monitor, a consensus store, or gossip.

Heartbeats#

A heartbeat is a small message sent at a regular interval, saying "I am alive", often with a counter or timestamp, and sometimes with load information. If the receiver hears nothing for longer than a timeout, typically a few intervals, it suspects the sender.

There are two directions:

  • Push: the monitored node sends heartbeats to a monitor. Raft leaders send heartbeats to followers, and HDFS DataNodes send heartbeats to the NameNode every 3 seconds by default.
  • Pull: the monitor probes the node and expects a reply. Load balancer health checks work this way: every few seconds, the load balancer requests /health from each backend, and removes a backend after several consecutive failures. SWIM's pings are also pull.

Typical settings, to give a sense of scale:

SystemIntervalDeclared failed afterNotes
Load balancer health check (for example AWS ALB)5 to 30 seconds2 to 10 consecutive failuresConfigurable; also has a healthy threshold for return
Raft (as suggested in the Raft paper)Leader heartbeats well under the election timeoutElection timeout randomly chosen in 150 to 300 msetcd defaults are a 100 ms heartbeat and a 1,000 ms election timeout
Kafka consumer group3 seconds45 seconds of session timeout in recent versionsThe broker coordinator removes the consumer and rebalances
HDFS DataNode3 secondsAbout 10.5 minutesLong on purpose: declaring death triggers costly re-replication
Kubernetes nodeNode lease renewals every 10 secondsTens of seconds of grace periodPods are evicted only after a further delay
Redis ClusterPings over the cluster buscluster-node-timeout, 15 seconds by defaultRequires agreement from a majority of primaries to mark FAIL

The variety is not an accident. Each system sets its timeout according to what happens when it declares a node dead. Raft can afford a short timeout, because a needless election costs little. HDFS uses a long one, because declaring a DataNode dead starts copying terabytes of data to restore its replicas.

Heartbeats in active-passive failover. The oldest use of heartbeats is a pair of servers in active-passive mode. The active server handles all traffic, and the passive one stands by, exchanging heartbeats with it over the network and often over a second, independent link. If heartbeats stop, the passive server takes over the active server's virtual IP address, so clients, which only know that address, reconnect to the new active server. On Linux, keepalived does this with the VRRP protocol, and Pacemaker with Corosync manages larger clusters. How long the outage lasts depends on the standby's readiness:

  • Hot standby: the passive server is running, with data replicated continuously. Takeover takes seconds.
  • Warm standby: the server is running, but must load data or warm caches before serving. Takeover takes minutes.
  • Cold standby: the server must be started and restored from a backup. Takeover takes much longer.

Failover adds hardware and complexity, and if replication is asynchronous, writes accepted by the active server just before it died may never have reached the passive one, and are lost. In active-active mode, both servers serve traffic, so there is no takeover delay, but clients or DNS must know about both, and any shared data must be kept consistent between them.

Heartbeats, in depth#

What a heartbeat proves, and what it does not. A received heartbeat proves that the sender's heartbeat code ran recently and that the network path from sender to receiver worked. It does not prove that the node is doing useful work. A process whose heartbeat thread is healthy, while its request threads are deadlocked, or its disk is failing, sends perfect heartbeats while every real request fails. This is the gray failure problem (see Distributed Systems Fundamentals). Two design choices push in opposite directions:

  • Heartbeats from a dedicated thread are reliable and on time, even under heavy load, which avoids false positives when the node is merely busy. But they hide gray failures.
  • Heartbeats from the main work path, or health checks that exercise real dependencies, detect gray failures. But a busy node may miss heartbeats and be wrongly declared dead, which moves its load onto other busy nodes and can cascade.

A common compromise is to separate the questions: a cheap liveness signal ("the process is running") on a dedicated path, plus readiness or quality signals ("the node is serving requests well") measured from real traffic, such as error rates and latency, used to drain traffic rather than to declare death.

Kubernetes probes are a good example of the distinction. A liveness probe failing makes Kubernetes restart the container. A readiness probe failing removes the pod from service endpoints, but leaves it running. A startup probe holds off the other probes while a slow application boots. A classic mistake is a liveness probe that checks the database: when the database has a brief problem, every pod fails liveness at once and is restarted, turning a short database blip into a full outage, with all pods cold-starting together. Liveness should check only the process itself, and dependency checks belong in readiness, if anywhere.

Shallow versus deep health checks. A shallow check returns 200 if the process can answer HTTP at all. A deep check tests the database connection, the cache, disk space and the downstream services. Deep checks catch more failures, but they couple the health of every instance to shared dependencies, so a failing dependency makes the load balancer remove all instances at once, leaving nothing to serve even cached or degraded responses. Load balancers such as AWS ALB defend against this with "fail open" behaviour: if every target is unhealthy, they send traffic to all of them anyway.

Who monitors whom. With N nodes:

  • All-to-all: every node heartbeats every other node. Detection is fast and needs no special node, but the cost is N squared messages per interval. Fine for 5 nodes, impossible for 5,000.
  • Central monitor: every node heartbeats one monitor, which decides. Cheap, but the monitor is a single point of failure and a bottleneck, and its view of the network is just one vantage point. Usually the monitor is itself a replicated, consensus-based service, such as ZooKeeper or etcd.
  • Ring or neighbours: each node monitors a few neighbours. Cheap, but if neighbours fail together, as in a rack failure, nobody notices.
  • Randomised and gossip-based: each node probes random others and gossips the results. Constant cost per node and robust to correlated failures. This is the approach of SWIM and Cassandra, described below.

Heartbeat cost in numbers. A heartbeat is tiny, perhaps 100 bytes including headers. All-to-all among 1,000 nodes at 1 per second is a million messages per second, about 100 MB per second across the cluster, and every node processes 1,000 incoming heartbeats per second. With SWIM, each node sends about one probe per second regardless of cluster size, so the whole cluster sends roughly 1,000 to 3,000 small messages per second.

Fixed timeouts vs phi-accrual detection#

Fixed timeouts. The simplest rule is "suspect a node if no heartbeat has arrived for T seconds". It is easy to understand and to configure, and most systems start here. Its weakness is that one number must suit every condition:

  • Set T short, say 2 heartbeat intervals, and a brief network hiccup, a garbage-collection pause, or a busy moment on the receiver produces a false suspicion.
  • Set T long, say 30 seconds, and a real crash goes unnoticed for 30 seconds, during which requests keep going to a dead node.
  • Networks are not uniform. Heartbeats between two machines in one rack arrive like clockwork, while heartbeats across regions or through a congested link arrive with a lot of jitter. A single T is too slow for the first and too jumpy for the second.
  • Conditions change. During a traffic peak or a backup job, delays grow, and a timeout that was fine at night now fires all the time.

Phi-accrual detection. Naohiro Hayashibara, Xavier Défago, Rami Yared and Takuya Katayama proposed a different output in "The φ Accrual Failure Detector" (IEEE SRDS, 2004). Instead of a binary alive or dead verdict, the detector outputs a continuously rising suspicion level, called φ (phi). Each application then chooses its own threshold for acting.

The detector keeps a sliding window of recent heartbeat inter-arrival times for each monitored node, for example the last 1,000 gaps, and estimates their distribution, classically as a normal distribution with the window's mean and standard deviation. When asked about the node, it measures the time since the last heartbeat, t, and computes the probability that a heartbeat would arrive later than t if the node were healthy. Then:

φ = -log10( P(next heartbeat arrives later than t) )

So φ = 1 means there is a 10% chance that a healthy node would be this late, φ = 2 means 1%, φ = 3 means 0.1%, and φ = 8 means one chance in 100 million. As silence lengthens, φ rises smoothly. An application that wants fast reaction can act at φ = 3, accepting about one false suspicion per thousand checks of that kind, while one that must avoid false positives can wait for φ = 8 or more.

A worked example. Suppose heartbeats are sent every second, and the detector has learned a mean gap of 1,000 ms with a standard deviation of 200 ms.

Time since last heartbeatStandard deviations above meanChance a healthy node is this lateφ
1.0 s050%0.3
1.2 s116%0.8
1.5 s2.50.6%2.2
1.8 s40.003%4.5
2.0 s50.00003%6.5
2.2 s60.0000001%9.0

With a threshold of 8, this node is suspected about 2.1 seconds after its last heartbeat. Now suppose it sits behind a jittery link, and the detector has learned a standard deviation of 500 ms instead. The same threshold of 8 is reached only after about 3.8 seconds. The threshold has not changed, but the timeout adapted to how the network actually behaves. A fixed 2-second timeout would have flagged the jittery node many times a day for nothing.

Fixed timeouts vs phi-accrual, in depth#

What a failure detector can promise. Tushar Chandra and Sam Toueg gave the classic framework in "Unreliable Failure Detectors for Reliable Distributed Systems" (Journal of the ACM, 1996). They describe a detector by two properties:

  • Completeness: every node that crashes is eventually suspected by every correct node. This is the liveness side: real failures are eventually noticed.
  • Accuracy: correct nodes are not suspected. Strong accuracy, never suspecting a correct node, is impossible in an asynchronous network, because a slow node looks crashed. The useful version is eventual accuracy: after some unknown time, correct nodes stop being suspected, which holds when the network eventually behaves.

A detector with strong completeness and eventual strong accuracy is called eventually perfect, written ◇P. A remarkable result, by Chandra, Vassos Hadzilacos and Toueg, also in 1996, is that a much weaker detector, ◇W, which only needs some correct node to eventually stop being suspected by everyone, is the weakest failure detector with which consensus can be solved when a majority of nodes is correct. This is the theoretical reason why practical consensus protocols are built around timeouts: the timeouts implement an eventually accurate detector, and the protocol stays safe even while the detector is wrong. See Consensus.

Measuring a detector's quality. Wei Chen, Sam Toueg and Marcos Aguilera defined quality-of-service metrics for failure detectors in "On the Quality of Service of Failure Detectors" (IEEE Transactions on Computers, 2002). The useful ones in practice:

  • Detection time: from a crash to permanent suspicion. Lower is better.
  • Mistake rate: how often a correct node is wrongly suspected, per hour. Lower is better.
  • Mistake duration: how long a wrong suspicion lasts before it is corrected.

For a fixed heartbeat interval and network, detection time and mistake rate trade against each other. A phi-accrual detector does not escape the trade-off, but it lets you choose the point on the curve with one parameter, in terms that remain meaningful when the network changes.

Practical details of phi-accrual implementations.

  • Distribution choice. The paper used a normal distribution. Akka's cluster failure detector also uses a normal distribution, with a configured minimum standard deviation, so that a perfectly regular network does not make the detector hypersensitive, and an "acceptable heartbeat pause" added to the mean, to tolerate occasional garbage-collection pauses. Cassandra's implementation uses a simpler exponential model, in which φ grows linearly with the time since the last heartbeat divided by the mean gap, roughly 0.43 times that ratio. With Cassandra's default phi_convict_threshold of 8, a node is convicted after about 18 mean intervals of silence.
  • Bootstrapping. A new detector has no history. Implementations seed the window with a few assumed values, such as a gap equal to the heartbeat interval, until real samples arrive.
  • Window size. A large window gives stable estimates but adapts slowly to change, and a small one adapts quickly but is noisy. Windows of hundreds to a thousand samples are common.
  • Pauses on the monitor. If the monitoring node itself pauses, all its peers' heartbeats appear late together. Good implementations notice that everything looks dead at once, which suggests the problem is local, and hold off on verdicts. SWIM's Lifeguard extension, described below, makes this explicit.

Adaptive timeouts without phi. Other systems adapt in simpler ways: TCP's retransmission timeout is computed from a smoothed round-trip time plus four times its mean deviation (Van Jacobson's algorithm, standardised in RFC 6298), which is the same idea of learning the distribution and setting the timeout some deviations above the mean. Raft randomises election timeouts, not to adapt, but to stop all followers from timing out at the same moment.

Cluster membership#

Detecting one failure is half the problem. The other half is membership: the list of nodes that currently belong to the cluster, and what state each is in. Every node uses this list to route requests, place data and choose peers. A membership service handles three kinds of change:

  • Join: a new node announces itself, usually by contacting one or more seed nodes whose addresses are configured in advance, and learns the current list from them.
  • Leave: a node shuts down gracefully, announcing that it is leaving, so others can remove it immediately and hand over its work cleanly.
  • Fail: a node disappears without warning, and the failure detector must notice.

There are two broad ways to keep the list.

Strongly consistent membership. The list lives in a consensus-backed store such as ZooKeeper or etcd. Each node registers itself with an ephemeral entry tied to a session or lease. In ZooKeeper, an ephemeral znode disappears when the client's session expires because heartbeats stopped. In etcd, a key attached to a lease disappears when the lease is not renewed with keep-alives. Every client sees the same list, in the same order of changes, and can watch for changes. This is ideal for small groups where agreement matters: which brokers are in a Kafka cluster, which node holds a partition, who the current leader is. The limits are scale and availability: the consensus store must handle every node's heartbeat traffic, and if it is unavailable or partitioned away from some nodes, membership changes stop. See ZooKeeper and etcd.

Eventually consistent membership. Each node keeps its own copy of the list and exchanges updates with peers, usually by gossip. There is no central service, so it scales to thousands of nodes and keeps working during partitions. The cost is that, for a short time, different nodes may disagree about who is alive. Cassandra, Consul's agents, Akka Cluster and Redis Cluster work this way.

Cluster membership, in depth#

Incarnation numbers. In gossip-based membership, stale news is a constant risk. Node A hears "B is suspect" from C, but B has since recovered and said "I am alive". Which message is newer? Each node keeps an incarnation number (also called a generation or version) that only it can increase. When B learns that others suspect it, B increments its incarnation and broadcasts "B is alive, incarnation 8". A rule then orders updates: an "alive" message with a higher incarnation overrides a "suspect" message with a lower one, and a "dead" or "confirm" message overrides both. Cassandra stores a generation, set from the time the node started, plus a version that increases with every change in its state, so a restarted node's information always beats information from its previous life.

Graceful leave matters more than it seems. A node that leaves without announcing itself is indistinguishable from a crash: the cluster waits out the detection timeout, during which requests to it fail, and then perhaps rebuilds its data. A node that announces "leaving" can be removed in one gossip round. Production deployments wire graceful leave into shutdown hooks and rolling restarts. Many systems also distinguish down from removed: a node that is down is expected to return, so its data is not moved immediately, while a node that is removed (decommissioned) has its data moved elsewhere for good.

Seed nodes and bootstrapping. A joining node needs at least one address to start from. Seeds are just ordinary members whose addresses are well known, through configuration, DNS or a cloud provider's API. If the configured seeds are all down, new nodes cannot join, so production clusters list several seeds across failure domains, and gossip-based systems often gossip with seeds a little more often than with other nodes, to speed up convergence and to help heal clusters that split.

Membership and data placement. Membership changes are expensive when data placement depends on them. In a system using consistent hashing, a node that is removed from the ring causes its key ranges to be reassigned, and replicas to be rebuilt. This is why such systems keep two separate notions: liveness ("can I send it a request right now?"), which changes quickly with the failure detector, and ring membership ("does it own data?"), which changes only through an explicit, often operator-driven step. A node can be down for an hour, with requests routed around it and writes buffered as hints for it, without any data being moved. See Partitioning and Sharding.

Membership through the orchestrator. In container platforms, membership is often maintained by the orchestrator rather than by the application. Kubernetes tracks node health through lease objects that each kubelet renews, and tracks the pods behind a service as endpoint lists that it updates when readiness changes. Clients find healthy instances through DNS or a service mesh, which takes this list as its membership. See Leader Election and Coordination.

Gossip protocol: spread and convergence#

A gossip protocol, also called an epidemic protocol, spreads information the way rumours or infections spread. Periodically, for example every second, each node picks one or a few other nodes at random and exchanges information with them. A node that has learned something new passes it on in its next rounds. No node talks to everyone, yet the information reaches everyone quickly.

The idea was developed for replicated databases by Alan Demers and colleagues at Xerox PARC in "Epidemic Algorithms for Replicated Database Maintenance" (ACM PODC, 1987). They described two styles that are still the basis of every gossip system:

  • Anti-entropy: each node periodically picks a random peer and the two compare their whole state, reconciling every difference. It is guaranteed to converge eventually, because every difference is eventually found. Comparing full state is expensive, so it runs infrequently, or uses compact summaries such as hashes.
  • Rumour mongering: a node with a new update, a "hot rumour", pushes it to random peers each round. When it has contacted enough peers who already knew it, it loses interest and stops spreading. This is fast and cheap, but a small fraction of nodes may miss a rumour, so it is usually combined with occasional anti-entropy to catch them.

There are three exchange directions:

  • Push: the caller sends its updates to the peer. Fast early, when few nodes know, but slow at the end, because most pushes go to nodes that already know.
  • Pull: the caller asks the peer for updates. Slow early, but fast at the end, because the few remaining uninformed nodes are likely to pull from someone who knows.
  • Push-pull: both, in one exchange. The best of both, and what most systems use.

How fast does it converge? In the push model with one random target per round, the number of informed nodes roughly doubles each round while few nodes know, because each informed node informs about one new node. So spreading to everyone takes about log2 N rounds, plus a tail to reach the last stragglers. Boris Pittel showed in 1987 that push gossip reaches all N nodes in about log2 N + ln N rounds. With a fan-out of f peers per round, the informed count multiplies by up to f + 1 per round early on, so it takes about log base (f + 1) of N rounds.

A worked example. A cluster of 1,000 nodes gossips every second with a fan-out of 3. The informed count can grow up to four times per round: 1, 4, 16, 64, 256, then nearly 1,000 by round five. Collisions, where nodes pick peers who already know, slow the end slightly, so seven or eight rounds is a realistic figure, about 7 to 8 seconds. Doubling the cluster to 2,000 nodes adds only about half a round. Ten times as many nodes adds fewer than two rounds. That logarithmic growth is the whole appeal.

Load stays constant per node. Each node sends f messages per round, whatever the cluster size. The total traffic grows only linearly with N, and no node is a hotspot.

Robustness. Gossip tolerates failures naturally: if a node crashes mid-spread, others still carry the information, and if messages are lost, the redundancy of random exchanges routes around it. There is no leader, no tree to repair, and no single point of failure.

Gossip, in depth#

The epidemic model. Gossip spreading follows the mathematics of epidemics. Call the fraction of nodes that know a rumour x. In push gossip, during one round, each informed node contacts one random node, and the contact is new with probability 1 - x. So x grows by roughly x(1 - x) per round, the logistic curve: slow at first, very fast in the middle, then slow at the end, when most contacts are wasted on nodes that already know. Pull gossip has the opposite profile at the end: an uninformed node pulls from a random peer, which is informed with probability x, so the uninformed fraction shrinks from u to about u squared per round. Once most nodes know, the stragglers disappear extremely fast. Push-pull combines the fast start of push with the fast finish of pull.

Rumour mongering leaves a residue. In rumour mongering, a node stops spreading after a few contacts with nodes that already knew. Demers and colleagues analysed variants and found that some nodes are never reached, the residue. In the basic model, where a node loses interest with probability 1/k after each contact with a node that already knew, the residue s satisfies s = exp(-(k + 1)(1 - s)). That gives about 20% of nodes missed for k = 1, 6% for k = 2, 2% for k = 3 and under 1% for k = 4: the residue shrinks roughly exponentially as k grows, but never reaches zero. That residue is why rumour mongering is backed by periodic anti-entropy, which eventually finds every difference.

Anti-entropy with Merkle trees. Comparing two replicas' full state by sending everything is too expensive for large data. Dynamo-style databases build a Merkle tree over each key range: leaves are hashes of small groups of keys, and each parent is the hash of its children. Two replicas compare root hashes. If equal, the whole range matches. If not, they descend only into the subtrees whose hashes differ, and exchange just the keys under the mismatched leaves. Cassandra's repair process and the original Dynamo used this approach, so replicas that missed writes, for example while they were down, are eventually brought back in sync. See Replication.

What gets gossiped. In membership protocols, the gossiped state is small: for each node, its address, its incarnation or generation, a heartbeat counter or version that it increments, its status (joining, normal, leaving), and often metadata such as its data centre, rack, load and the key ranges it owns. Cassandra's gossiper runs every second. Each round, a node sends a digest, a compact list of (node, generation, highest version) entries, to a random live peer, and possibly also to an unreachable node and to a seed. The exchange is a three-message handshake:

Because only digests are sent first, and full state only for entries that differ, a round between two nodes that already agree costs one small message each way.

Gossiped heartbeats as failure evidence. In Cassandra, each node increments its own heartbeat version every gossip round. Node A never needs to hear from B directly: if B's heartbeat version, as seen through anyone's gossip, keeps increasing, B is alive. The phi-accrual detector on A is fed with the arrival times of new versions of B's heartbeat. This makes detection robust to a single bad link, since news of B arrives via many paths, but it also means detection is slower than direct pinging, because news takes a few gossip rounds to arrive.

Bandwidth sizing. Suppose a 1,000-node cluster, where each node's state is about 200 bytes, and each node gossips once per second with one peer. Digests are about 1,000 entries of 20 bytes, so 20 KB per exchange, and each node takes part in about two exchanges per second (one it starts and one started by someone else), so about 40 KB per second per node, plus state deltas. That is modest, but digests grow linearly with N, so in very large clusters digest size, not message count, becomes the limit, which is one reason SWIM-style protocols piggyback a bounded number of recent updates instead of full digests.

When gossip goes wrong. Gossip spreads bad information as efficiently as good. On 20 July 2008, Amazon S3 suffered an outage of several hours in which, according to Amazon's post-incident summary, a single bit of corruption in gossip messages about server state spread through the system and the servers ended up spending most of their time gossiping, unable to serve requests. Amazon's fixes included checksums on the gossip messages and the ability to clear the gossiped state. The lessons apply to any gossip system: checksum and validate every gossiped message, bound how much gossip state and work a node will accept, and have a way to reset the cluster's gossiped state.

SWIM#

Classic heartbeat gossip has two problems at scale: detection is slow, because evidence travels through several gossip rounds, and the per-node digest grows with cluster size. Abhinandan Das, Indranil Gupta and Ashish Motivala addressed both in "SWIM: Scalable Weakly-consistent Infection-style Process Group Membership Protocol" (IEEE DSN, 2002). SWIM separates failure detection from dissemination, and makes both cost a constant amount per node.

Failure detection by probing. Every protocol period, for example 1 second, each node M does the following:

  1. Pick one member B and send it a ping.
  2. If B replies with an ack within a short timeout, B is alive.
  3. If not, pick k other members, for example 3, and send each a ping-req for B. Each of them pings B and, if it gets an ack, forwards it to M.
  4. If no ack arrives, directly or indirectly, by the end of the period, M marks B as suspect.

The indirect probe is the key idea. If M's own link to B is congested, or M's network card is dropping packets, a direct ping alone would wrongly accuse B. Asking k other nodes to try separate network paths makes a false accusation require all of them to fail too.

Suspicion before death. Instead of declaring B dead at once, M marks B suspect and spreads that news. A suspect node is still treated as a member, but if it is not refuted within a suspicion timeout, it is declared dead (in the paper, "confirmed" failed) and removed. If B hears that it is suspected, it refutes by incrementing its incarnation number and spreading "alive" with the new incarnation, which overrides the suspicion everywhere. This catches the common case of a node that was briefly slow, paused or overloaded, and stops it from being thrown out of the cluster.

Dissemination by piggybacking. SWIM sends no separate gossip messages. Membership updates (joined, suspect, alive, dead) are piggybacked on the pings, ping-reqs and acks that the failure detector sends anyway. Each update is attached to a bounded number of outgoing messages, about λ log N for a small constant λ, and then dropped. Since every node sends a constant number of probes per period, updates spread epidemically through the cluster in O(log N) periods, at no extra message cost.

Why the cost stays constant. Each node sends about one ping per period, plus occasional ping-reqs, and receives on average one ping per period. The expected time until some node first probes a crashed node does not grow with cluster size, since every period, every other node independently has a chance of picking it, and with N - 1 nodes picking, the crashed node is almost certain to be probed within one or two periods. False positive rates also do not grow with N. Compare that with all-to-all heartbeating, whose per-node load grows linearly with N.

Round-robin probe order. If targets are chosen purely at random, a node could, by bad luck, go unprobed for many periods. SWIM's improvement is for each node to walk through a randomly shuffled list of members, probing each in turn, and to re-shuffle after every pass. This bounds the worst-case time until a failed node is probed by any given node to about two passes through the membership list, while keeping the randomness that spreads load.

SWIM, in depth#

Tuning in practice: memberlist. HashiCorp's open-source Go library memberlist implements SWIM with extensions, and is the membership layer of Consul, Nomad and Serf. Its default LAN configuration probes one member every second, waits 500 ms for a direct ack, uses 3 indirect probers, gossips piggybacked updates to 3 random nodes every 200 ms, and every 30 seconds does a full state push-pull sync with one random node over TCP, a form of anti-entropy that repairs anything piggybacking missed. The suspicion timeout scales with cluster size: it is a multiplier (4 by default) times log10 of the number of nodes, times the probe interval. For a 1,000-node cluster, that is 4 × 3 × 1 second, so 12 seconds of suspicion before a node is declared dead. The logarithm reflects how long it takes for the suspicion to reach the suspected node through gossip, so it has a fair chance to refute.

A worked timeline for a crashed node. In a 1,000-node cluster with those settings:

  • 0 s: node B crashes.
  • Within about 1 to 2 s: some node probes B, gets no direct ack in 500 ms, sends ping-reqs to 3 others, gets nothing by the end of the period, and marks B suspect.
  • About 1 to 2 s more: the suspicion spreads to most of the cluster through piggybacked gossip.
  • About 12 s after the suspicion: with no refutation, B is declared dead, and that news spreads in another second or two.

So a crash is acted on after roughly 15 seconds, while a node that was paused for 5 seconds is suspected, then refutes itself on waking, and is never removed. Clusters that need faster detection lower the multiplier, accepting more false positives, while large WAN clusters raise all the timeouts, as memberlist's WAN profile does.

Lifeguard: when the detector itself is the problem. HashiCorp engineers found that most false positives in production came not from the suspected node, but from the detecting node being slow: overloaded, starved of CPU, or with a backed-up network queue, so it missed acks that had arrived and then accused healthy nodes. They described three extensions in "Lifeguard: Local Health Awareness for More Accurate Failure Detection" (Armon Dadgar, James Phillips and Jon Currey, 2017):

  • Local health awareness: each node keeps a local health multiplier, a score that rises when it sees signs that it is itself unhealthy, such as probes it sent that got no ack, or having to refute suspicions about itself. A higher score lengthens its own probe timeouts and intervals, so a struggling node becomes slower to accuse others.
  • Dynamic suspicion timeouts: a suspicion starts with a long timeout, which shrinks as more independent nodes confirm the same suspicion. One possibly unhealthy accuser is not enough to remove a node quickly, but many accusers are.
  • Buddy system: when a node probes a member it already suspects, it tells the member so in the ping itself, so the member can refute immediately instead of waiting for the gossip to reach it.

The authors reported that these changes cut false positives dramatically, with little effect on detection time for real failures. The general lesson is that a failure detector should account for its own health before judging others.

Consistency of SWIM membership. SWIM is "weakly consistent": different members can briefly disagree about who is alive, and a node may be removed by some members slightly before others. For routing requests and choosing replicas, that is fine. For decisions that require agreement, such as electing a single leader, SWIM membership is not enough on its own, and systems pair it with a consensus protocol. Consul does exactly this: gossip tracks which agents are alive, while a small set of Consul servers runs Raft to keep the catalog and key-value store consistent.

Where used: Cassandra, Consul and others#

Apache Cassandra. Every node runs a gossiper that, once per second, exchanges digests with a random live peer, and sometimes with an unreachable node and with a seed, using the SYN, ACK, ACK2 handshake described above. The gossiped state for each node includes its generation, heartbeat version, status (bootstrapping, normal, leaving, removed), the tokens it owns, its schema version, data centre and rack. Failure detection is phi-accrual on gossiped heartbeat arrivals, with phi_convict_threshold defaulting to 8, and often raised to 10 or 12 in cloud environments with noisier networks. A node marked down is skipped by coordinators, and writes meant for it are stored as hints on other nodes for a limited window, by default 3 hours, and replayed when it returns. Ring membership does not change when a node is merely down: an operator decommissions or replaces a node explicitly. This separation, fast liveness and slow ownership changes, is what keeps a flapping node from triggering data movement.

Consul (and Serf and Nomad). Consul runs an agent on every machine. All agents in one data centre form a LAN gossip pool using memberlist's SWIM. This gives every agent a membership list, a failure detector that scales to thousands of machines, and a fast way to broadcast events. Consul's servers, usually 3 or 5 per data centre, also join a WAN gossip pool that links data centres, with timeouts tuned for higher latency. Gossip results feed the catalog: when gossip declares a node failed, Consul marks the node's built-in "Serf Health Status" check critical, which marks every service on that node unhealthy, and service discovery queries stop returning it. Application-level health checks (HTTP, TCP, script or TTL checks run by the local agent) are separate, and catch failures that gossip cannot see, such as a running node whose web server is broken. Serf is the stand-alone gossip and membership tool, and Nomad uses the same library for its servers.

Other well-known users:

  • Amazon Dynamo used gossip to spread membership changes and the partitioning map, with seed nodes to avoid logically partitioned rings, and treated permanent membership changes as explicit administrative actions, while temporary failures were handled by local failure detection and hinted handoff (DeCandia and colleagues, SOSP 2007).
  • Redis Cluster nodes exchange pings and pongs over a separate cluster bus port, and each ping carries gossip about a few other nodes. A node that does not answer within cluster-node-timeout is flagged PFAIL (possible failure) locally. When a majority of primaries report PFAIL or FAIL for the same node within a validity window, the node is marked FAIL, the verdict is broadcast, and a replica of the failed primary can start an election for its slots. The majority requirement is what stops one isolated node from triggering failovers on its own.
  • Akka Cluster gossips cluster membership state, using vector clocks to merge it, and runs phi-accrual detectors on a limited set of neighbours per node. The cluster leader performs membership changes only when gossip has converged, meaning every reachable node has seen the current state, and unreachable nodes are removed only by a downing decision, typically from Akka's Split Brain Resolver, which offers strategies such as keep-majority and static-quorum.
  • Uber's Ringpop, an open-source library used for application-level sharding, combined SWIM membership with consistent hashing, so services could route requests for a key to the instance owning it.
  • ScyllaDB, being Cassandra-compatible, uses the same gossip model.

False positives and split brain#

Every practical failure detector makes mistakes, because a slow node and a dead node look alike. A false positive is a healthy node declared failed. What it costs depends entirely on what the system does with the verdict:

  • Routing around the node (load balancer removal, Cassandra marking it down): a false positive costs a little capacity for a short time. Cheap.
  • Restarting the node (Kubernetes liveness): a false positive kills a working process and loses its in-memory state and in-flight requests. Moderate cost, and dangerous if many nodes are hit at once.
  • Moving data (HDFS re-replication, rebalancing a ring): a false positive starts copying terabytes, loading the network and disks of healthy nodes, which makes them slower, which can cause more false positives. Expensive, and potentially self-reinforcing.
  • Promoting a replacement leader (database failover, Raft election, active-passive takeover): a false positive creates a new leader while the old one is still alive. If the old leader keeps acting, the system has two leaders: split brain.

Split brain is the worst outcome, because it corrupts data rather than just slowing things down. Both leaders accept writes, the histories diverge, and when the network heals, someone has to decide which writes to keep, often by hand. Failure detection cannot prevent it, because the detector cannot know that the old leader is alive. The protection must come from the way leadership itself works:

  • Majority quorums. A leader must be able to reach a majority of nodes to act, and a new leader needs a majority of votes. Two majorities always overlap, so two leaders cannot both commit in the same term. An old leader cut off from the majority can no longer commit anything. This is how Raft, ZooKeeper and etcd stay safe despite timeouts that are wrong. See Consensus.
  • Terms, epochs and fencing tokens. Every new leader gets a higher number, and storage or followers reject requests carrying an older one. A paused old leader that wakes up and writes is rejected, however confident it is. See Distributed Locks.
  • Fencing the old node physically. In classic high-availability clusters, the survivor powers off or isolates the failed node before taking over, a practice called STONITH ("shoot the other node in the head"), done through power controllers, out-of-band management interfaces, or cloud APIs that stop an instance or detach its disk. Only after fencing succeeds does takeover proceed.
  • Witnesses and tie-breakers. In a two-node setup, neither side can form a majority alone, so a third, lightweight witness node, or a cloud-hosted quorum device, votes to break ties. The node that can reach the witness continues, and the other stops.

False positives and split brain, in depth#

Hysteresis stops flapping. A node near the threshold can bounce between healthy and failed many times a minute, and each transition triggers routing changes, alerts and sometimes recovery work. Hysteresis means using different conditions to enter and leave a state: for example, mark a backend unhealthy after 3 consecutive failed checks, but healthy again only after 5 consecutive successes, as load balancers commonly allow. Suspicion states, as in SWIM, play the same role, absorbing short problems before any drastic action.

Correlated verdicts are a warning sign. If one node out of 100 fails, it is probably that node. If 40 out of 100 appear to fail at the same moment, it is much more likely to be the network, the monitor, or a shared dependency. Mature systems treat mass failure verdicts with suspicion:

  • Rate-limit automatic remediation: at most a few nodes restarted, replaced or failed over per period, and anything beyond that waits for a human.
  • Stop data movement when more than a few nodes are down at once, since re-replicating everything during a network partition only makes it worse.
  • Compare views from several vantage points before acting. Redis Cluster's majority-of-primaries rule and Lifeguard's confirmations from several nodes both do this.

Failover across regions is a special case. Cross-region links have higher latency, more jitter and longer partitions. An automated failover from one region to another on a short timeout risks exactly the split-brain scenario described in Distributed Systems Fundamentals: a brief connectivity loss promotes a remote primary while the local one keeps serving. Many organisations therefore automate failover within a region, where quorums are fast and reliable, and keep cross-region failover as a deliberate, human-approved action, or require a quorum that spans three regions.

Redis Sentinel as a worked case. Redis Sentinel monitors a primary and its replicas. Each Sentinel pings the primary, and if one does not get a valid reply within down-after-milliseconds, it considers the primary subjectively down (SDOWN). When enough Sentinels, at least the configured quorum, agree, the primary is objectively down (ODOWN), and the Sentinels elect one of themselves, by majority, to perform the failover, which promotes a replica. With asynchronous replication, the old primary, if it was merely partitioned with some clients, can keep accepting writes that will be lost when it rejoins as a replica. Redis's min-replicas-to-write and min-replicas-max-lag settings limit the damage: a primary that cannot reach enough replicas within the lag bound stops accepting writes. It is a fencing mechanism built into the old leader, with the clock bounding the window.

When to Use It#

  • Heartbeats with a fixed timeout: small groups and clear-cut decisions, such as load balancer health checks, active-passive pairs with fencing, or monitoring a handful of services. Pick the timeout from what a false positive costs.
  • Phi-accrual detection: when network conditions vary between pairs of nodes or over time, as across racks, zones or clouds, and you want one tunable threshold that adapts.
  • Consensus-backed membership (ZooKeeper, etcd): small clusters where every member must agree on who is in, who leads and who owns what, such as brokers, controllers and lock holders.
  • Gossip-based membership: large clusters of hundreds or thousands of nodes, peer-to-peer databases, and service meshes where availability during partitions matters more than instantaneous agreement.
  • SWIM: when you need membership and failure detection with constant per-node cost, fast detection and few false positives, usually by using memberlist, Serf or Consul rather than writing your own.
  • Quorums and fencing: always, whenever a failure verdict leads to promoting a leader or granting exclusive access.

When NOT to Use It#

  • Do not write your own failure detector or gossip protocol for production. The subtle cases (incarnations, refutation, partial partitions, the detector's own slowness) take years to get right. Use the detection built into your database, orchestrator, or a library such as memberlist or Akka Cluster.
  • Do not use gossip membership to elect a single leader. Gossip views can disagree, so two nodes may each think they are the oldest or lowest-ID member. Use a consensus store.
  • Do not use a consensus store for a 5,000-node heartbeat fleet. Every lease renewal is a replicated write. Use gossip or hierarchical monitoring, and keep only the important, low-churn state in consensus.
  • Do not trigger expensive recovery on a fast detector. Route around a node in seconds, but wait minutes, or for a human, before moving its data.
  • Do not make liveness depend on dependencies. A health check that fails whenever the database is slow turns one problem into a fleet-wide restart.

How to Implement It#

  1. Decide what each verdict triggers, and set detection speed per action: seconds for routing, tens of seconds for leader election, minutes or human approval for data movement and cross-region failover.
  2. Use separate signals for separate questions: a lightweight liveness heartbeat, readiness based on real request success, and dependency health in metrics and alerts rather than in liveness.
  3. Use an adaptive or suspicion-based detector (phi-accrual or SWIM with suspicion), with thresholds tuned against measured network behaviour, and raise thresholds in noisy environments.
  4. Probe from more than one vantage point before declaring death: indirect probes, majority agreement, or several monitors.
  5. Protect every leadership change with a majority quorum, an increasing epoch or term, and fencing at the storage layer, or STONITH for shared-disk clusters.
  6. Announce graceful leaves on shutdown, so planned restarts never look like failures.
  7. Checksum and validate gossip and heartbeat messages, and bound the state a node accepts.
  8. Rate-limit automatic remediation, and alert when many nodes are suspected at once.
  9. Test it: kill processes, pause them with SIGSTOP, add packet loss and latency with tc netem, and create asymmetric partitions, measuring both detection time and false positives.
// Phi-accrual failure detector (normal model) for one monitored node
export class PhiAccrualDetector {
  private gaps: number[] = [];
  private last?: number;
 
  constructor(
    private windowSize = 1000,
    private minStdDevMs = 100,       // avoid hypersensitivity on quiet networks
    private acceptablePauseMs = 0,   // tolerance added to the mean, e.g. for GC
  ) {}
 
  heartbeat(nowMs: number): void {
    if (this.last !== undefined) {
      this.gaps.push(nowMs - this.last);
      if (this.gaps.length > this.windowSize) this.gaps.shift();
    }
    this.last = nowMs;
  }
 
  phi(nowMs: number): number {
    if (this.last === undefined || this.gaps.length === 0) return 0;
    const n = this.gaps.length;
    const rawMean = this.gaps.reduce((a, b) => a + b, 0) / n;
    const variance = this.gaps.reduce((a, g) => a + (g - rawMean) ** 2, 0) / n;
    const std = Math.max(Math.sqrt(variance), this.minStdDevMs);
    const mean = rawMean + this.acceptablePauseMs;
    const y = (nowMs - this.last - mean) / std;
    // logistic approximation of the normal tail, as used by Akka
    const e = Math.exp(-y * (1.5976 + 0.070566 * y * y));
    const pLater = y > 0 ? e / (1 + e) : 1 - 1 / (1 + e);
    return -Math.log10(Math.max(pLater, 1e-300));
  }
 
  isAvailable(nowMs: number, threshold = 8): boolean {
    return this.phi(nowMs) < threshold;
  }
}

The caller passes monotonic time, such as performance.now(), not wall-clock time, so that a clock step cannot make every node look dead at once. A real implementation keeps a running sum and sum of squares instead of recomputing over the window.

TechnologyFits when
Load balancer health checks (AWS ALB and NLB, Envoy, NGINX, HAProxy)Removing failed backends from traffic within seconds
Kubernetes liveness, readiness and startup probes; node leasesRestarting stuck containers, draining unready pods, detecting failed nodes
keepalived (VRRP), Pacemaker with CorosyncActive-passive pairs with a virtual IP and fencing
ZooKeeper ephemeral nodes, etcd leasesSmall, strongly consistent membership and leader election
HashiCorp memberlist, Serf, ConsulSWIM-based membership and failure detection for large clusters
Akka ClusterJVM applications needing gossip membership, phi-accrual detection and a split-brain resolver
Cassandra, ScyllaDB gossipBuilt in; tune phi_convict_threshold for the environment
Redis Sentinel and Redis ClusterFailure detection and failover for Redis, with quorum-based agreement

Trade-offs#

OptionProsConsPick when
Fixed timeoutSimple; predictable; easy to explainToo slow or too jumpy; ignores network variationSmall, uniform environments; load balancer checks
Phi-accrualAdapts to each link's jitter; one meaningful thresholdNeeds history; more complex; still trades speed for accuracyClusters across racks, zones or noisy clouds
Central monitor or consensus storeSingle, consistent view; simple clientsBottleneck and dependency; one vantage pointSmall clusters needing agreement, such as leader and broker lists
All-to-all heartbeatsFast and directN squared messagesUp to a few dozen nodes
Gossip heartbeatsScales; no single point of failure; robust to bad linksSlower detection; views briefly differ; spreads corruptionLarge peer-to-peer databases such as Cassandra
SWIM with suspicionConstant load per node; fast detection; few false positivesWeakly consistent; needs tuning for WANLarge service fleets, Consul, Nomad
Short timeoutsFast reactionMore false positives, flapping, failover stormsCheap actions, such as routing around a node
Long timeoutsFew false positivesLong outages before reactionExpensive actions, such as data movement and cross-region failover

Common Pitfalls#

  • Equating "no heartbeat" with "dead" and promoting a new leader without quorum or fencing, leading to split brain.
  • One timeout for every action, so a 5-second blip both drains traffic, which is fine, and starts re-replicating terabytes, which is not.
  • Liveness probes that check dependencies, restarting the whole fleet when the database stutters.
  • Measuring heartbeat gaps with the wall clock, so an NTP step makes every peer look dead or alive at once.
  • Heartbeats from a dedicated thread with no quality signal, so a node with stuck request threads looks perfectly healthy.
  • Two-node clusters without a witness, where every partition is either an outage or a split brain.
  • No hysteresis, so nodes near the threshold flap between healthy and failed.
  • Unvalidated gossip, letting one corrupted message spread through the whole cluster.
  • Automatic remediation without a rate limit, so a network problem that makes half the nodes look dead triggers mass restarts and rebuilds.
  • Not announcing graceful shutdowns, so every deployment looks like a wave of failures.

Real-World Examples#

  • Apache Cassandra gossips once per second with a three-message digest exchange and uses a phi-accrual detector with a default conviction threshold of 8, keeping ring ownership changes separate from liveness.
  • Consul, Nomad and Serf use HashiCorp's memberlist, a SWIM implementation with the Lifeguard extensions, for LAN and WAN gossip pools, while Consul servers use Raft for the consistent catalog.
  • Akka Cluster combines gossip membership, phi-accrual detection and a split-brain resolver for JVM applications.
  • Redis Cluster marks nodes PFAIL locally and FAIL only when a majority of primaries agree, and Redis Sentinel distinguishes subjectively and objectively down with a quorum.
  • Amazon S3 had a multi-hour outage on 20 July 2008 that Amazon attributed to corrupted gossip messages about server state spreading through the system. Checksums on gossip messages were among the fixes.
  • HDFS waits about 10.5 minutes before declaring a DataNode dead, because the response, re-replicating its blocks, is expensive.
  • Kubernetes separates liveness, readiness and startup probes, and evicts pods from a failed node only after a grace period, to avoid reacting to brief node problems.
  • GitHub's October 2018 incident, where a connectivity loss of under a minute triggered a cross-region database failover, is a widely cited example of how a correct-looking failure verdict can still cause split-brain-like divergence.

In the Interview#

Deep Dive: Designing failure detection for a 2,000-node storage clusterShow

The setting. A Dynamo-style key-value store runs on 2,000 nodes across three availability zones, with three replicas per key, one per zone. Requirements: route around a crashed node within about 10 seconds, keep false positives to a few per day across the whole cluster, never lose acknowledged writes, and avoid moving data for temporary failures.

Layer 1: membership and detection. Use SWIM, through a library such as memberlist, with a 1-second probe interval, a 500 ms probe timeout and 3 indirect probers. Choose indirect probers from other zones where possible, so a single zone's network trouble cannot make a node look dead to its own zone's probers. With 2,000 nodes, log10 N is about 3.3, so a suspicion multiplier of 2 gives a suspicion timeout of about 6.6 seconds. Expected detection is 1 to 2 seconds to first suspicion, plus about 7 seconds of suspicion, so routing changes happen within roughly 10 seconds of a crash. Lifeguard's local health awareness keeps overloaded nodes from accusing others.

Load check. Each node sends about 1 probe per second, plus gossip to 3 nodes every 200 ms, carrying piggybacked updates. With messages of a few hundred bytes, each node sends roughly 20 small packets per second, under 10 KB per second. The whole cluster's detection traffic is a few tens of MB per second, spread evenly. All-to-all heartbeats at the same rate would need 4 million messages per second.

Layer 2: what the verdict triggers.

  • Suspected or dead in SWIM: coordinators stop sending reads to the node and redirect writes to other nodes as hinted handoff, storing hints for replay. Writes still reach a quorum of two out of three replicas, since the other two zones are healthy.
  • Down for more than 3 hours (the hint window): hints stop accumulating, and the node will need anti-entropy repair, with Merkle trees, when it returns.
  • Down for more than 24 hours, or confirmed dead by an operator or by the cloud provider's instance status: replace the node, and stream its key ranges to the replacement. This is the only step that moves data, and it never happens automatically for nodes that are merely suspect.

Layer 3: protection against mass verdicts. If more than 5% of nodes are suspected within a minute, the cluster pauses automated replacements and pages an engineer, because it is most likely a network or zone problem, not 100 simultaneous machine failures. A zone-wide failure is handled by the quorum design itself: two zones still form a write quorum for every key.

Layer 4: leadership. The store has a small control plane, a 5-node Raft group, that owns the authoritative ring layout and schema. Gossip spreads the ring to all nodes quickly, but changes to it go through Raft, each with an increasing ring version, and nodes reject requests computed with an older version than they have seen. Gossip is never used to decide who is in charge.

Testing. Before production, run fault scenarios: kill nodes, pause them for 3, 10 and 60 seconds, drop 10% of packets on one zone's links, partition one zone, and slow one node's disk. For each, measure time to route around, number of false suspicions, and whether any acknowledged write was lost.

Deep Dive: Gray failures and passive detectionShow

Heartbeats see only what they test. Peng Huang and colleagues, in "Gray Failure: The Achilles' Heel of Cloud-Scale Systems" (HotOS 2017), described failures where the system's own failure detector reports a component as healthy, while the applications using it experience it as broken: a node whose heartbeat agent works but whose disk I/O stalls, a switch that drops a fraction of packets, a service that answers health checks but times out on real requests. The paper's central observation is differential observability: the failure detector and the applications observe the component differently, so they disagree.

Passive detection: let real traffic be the probe. Clients see every request's outcome, so they can detect failures that probes miss:

  • Outlier ejection. Envoy and other service-mesh proxies track each upstream host's consecutive errors, error rate and latency compared with its peers, and temporarily eject hosts that are much worse than the rest, readmitting them after a back-off period. An ejected host is not declared dead cluster-wide, only avoided by that client for a while.
  • Circuit breakers stop calls to a dependency whose error rate crosses a threshold, and probe it occasionally to see if it has recovered. See Resilience Patterns.
  • Latency-aware load balancing, such as choosing the less loaded of two random backends, or weighting by recent latency, naturally sends less traffic to a slow node before any detector notices.
  • Hedged requests for idempotent reads send a second request to another replica after a short delay, so one slow replica affects only tail latency, not correctness.

Combining active and passive signals. A robust design uses active probes to detect crashes quickly and uniformly, and passive signals from real traffic to detect gray failures, feeding both into routing decisions. Severe or persistent passive signals can escalate into active remediation, such as draining and replacing a node whose disk is failing, while brief ones only adjust traffic weights.

Watch the watcher. Failure detectors themselves fail grayly. A monitor that is slow, or whose network is congested, reports others as down. Mitigations include detecting from several vantage points, alerting when the detector's own probe success rate drops for all targets, and Lifeguard-style self-awareness.

Deep Dive: Why perfect detection is impossible, and why consensus does not need itShow

The impossibility. In an asynchronous network, there is no bound on message delay, so for any timeout T, a healthy node's heartbeat can take longer than T. A detector that never suspects a correct node would therefore have to wait forever, and would never detect a crash. This is the same insight behind the FLP result: crashed and slow are indistinguishable without timing assumptions (see Distributed Systems Fundamentals).

Eventually perfect detection with growing timeouts. Under partial synchrony, where delays become bounded after some unknown time, there is a simple way to build an eventually perfect detector. Each node starts with a timeout T for each peer. Whenever it suspects a peer and later receives a heartbeat from it, it learns it was wrong, and increases that peer's timeout, for example by doubling it. After the network stabilises, each timeout grows at most a few times until it exceeds the real delay bound, and from then on correct nodes are never suspected again, while crashed nodes, which send nothing, are still always suspected. Real systems cap the growth and decay timeouts back slowly, but the principle, learning from mistakes, is the same one phi-accrual applies statistically.

Consensus is safe with a wrong detector. The key design insight behind Paxos and Raft is that the failure detector only affects liveness, never safety. In Raft, a follower that wrongly suspects a healthy leader starts an election with a higher term. In the worst case, it wins, and the old leader steps down when it sees the higher term. No committed entry is lost, because the new leader must have every committed entry to win votes from a majority. The false positive costs an election, perhaps a few hundred milliseconds of unavailability, but never correctness. If the detector is wrong constantly, the cluster may hold elections forever and make no progress, a loss of liveness, but it still never commits conflicting entries. This is exactly the right division of labour: the failure detector can be fast and imperfect, because the quorum and term rules underneath make its mistakes safe. Any design that lets a failure verdict directly grant exclusive power, without such a rule underneath, has made its safety depend on an impossible detector. See Consensus and Leader Election and Coordination.

Key Takeaways#

  • A failure detector can only suspect, never know: silence means crashed, slow, paused or partitioned, and these look the same.
  • Every detector trades detection time against false positives. Choose the point per action: fast for routing, slow for data movement, quorum-protected for leadership.
  • Phi-accrual detectors learn each link's heartbeat rhythm and output a suspicion level, so one threshold adapts to quiet and noisy networks alike.
  • Membership is either strongly consistent, in ZooKeeper or etcd for small groups needing agreement, or eventually consistent, through gossip for large clusters.
  • Gossip spreads information to N nodes in about log N rounds with constant load per node, and anti-entropy, often with Merkle trees, catches anything it misses.
  • SWIM adds indirect probes, a suspect state with incarnation-based refutation, and piggybacked dissemination, which keeps detection fast and false positives rare. Lifeguard makes the detector account for its own health.
  • Cassandra uses gossip with phi-accrual, Consul uses SWIM through memberlist plus Raft for its catalog, and Redis Cluster requires a majority of primaries to agree before failing a node.
  • False positives are inevitable, so failover must be made safe with majority quorums, epochs, fencing tokens, STONITH or witnesses, or a false positive becomes a split brain.