Sub topic 11
Cluster Membership and Failure Detection with Gossip
This chapter assumes you know how the consistent-hash ring places keys on nodes, how a preference list is built, and that each key is replicated to N nodes. You should also be comfortable reading short Python snippets.
Why membership is a problem
The ring from the earlier chapters only works if every node agrees on who is in it. A coordinator that computes a preference list needs to know which nodes exist, which are alive, and which tokens (virtual nodes) each one owns. Without that, it cannot route a write to the right replicas.
Membership has two parts:
- Membership list: the set of nodes that belong to the cluster and the ring positions they own. It changes when an operator adds or removes a node.
- Failure detection: a continuous guess about which listed nodes are currently reachable. It changes whenever a machine crashes, restarts, or becomes slow.
Keeping these separate matters. A node that is down for ten minutes is still a member. Its keys should not be reshuffled across the ring because of a short outage. Hinted handoff, covered in a later chapter, exists to bridge that gap.
Centralized versus decentralized approaches
One option is a central registry, such as ZooKeeper or etcd, that holds the list. Nodes register with it and clients read from it. This gives a single source of truth, but the registry becomes a dependency. If it is unavailable, membership changes stall.
A leaderless store avoids that dependency. Every node keeps its own copy of the membership view and exchanges it with peers using a gossip protocol. This fits a design whose goal is no single point of failure.
| Approach | Strength | Weakness |
|---|---|---|
| Central registry | One authoritative view, simple to reason about | Extra system to run, and a failure point for changes |
| Gossip | No central component, scales to many nodes | Views are only eventually consistent |
How gossip works
In gossip (also called epidemic) dissemination, each node periodically picks a few random peers and exchanges state with them. Information spreads like a rumor. After one round, two nodes know a fact. After the next, about four, and so on. The number of rounds needed grows with the logarithm of the cluster size, so a thousand-node cluster converges in a small number of rounds.
A typical node keeps a table like this:
| Node | Heartbeat counter | Last updated (local clock) | Status |
|---|---|---|---|
| node-a | 120 | 10:47:30 | up |
| node-b | 98 | 10:47:29 | up |
| node-c | 77 | 10:46:50 | suspected |
Each node increments its own heartbeat counter every second. During a gossip round it sends its table to a random peer, and the peer merges it in, keeping the higher counter for each node. When a counter rises, the receiver records the time on its own clock.
Note the last point. Nodes compare counters, not timestamps from other machines, so clock skew between servers does not affect detection.
A runnable merge
The core of the protocol is the merge function. This sketch keeps a heartbeat counter per node and a local time of the last increase.
import time
class Membership:
def __init__(self, self_id: str):
self.self_id = self_id
# node id -> (heartbeat counter, local time of last increase)
self.table = {self_id: (0, time.monotonic())}
def beat(self):
counter, _ = self.table[self.self_id]
self.table[self.self_id] = (counter + 1, time.monotonic())
def merge(self, remote: dict):
"""Merge a remote table of node id -> heartbeat counter."""
now = time.monotonic()
for node, counter in remote.items():
known = self.table.get(node)
if known is None or counter > known[0]:
self.table[node] = (counter, now)
def digest(self) -> dict:
return {node: c for node, (c, _) in self.table.items()}
a = Membership("node-a")
b = Membership("node-b")
for _ in range(3):
a.beat()
b.beat()
b.merge(a.digest())
a.merge(b.digest())
print(sorted(a.digest().items()))
print(sorted(b.digest().items()))Both nodes end with the same table: node-a at 3 and node-b at 1. Because the merge keeps the maximum, it is safe to apply the same message twice or in any order. This property is why gossip tolerates duplicated and reordered packets.
Detecting failures
Gossip also carries failure information. The simplest detector uses a fixed timeout: if a node's counter has not increased for T seconds, mark it as suspected. This is easy but brittle. A value of T that suits a quiet network produces false alarms during a garbage-collection pause or a busy period. A value large enough to avoid those makes real failures slow to notice.
The phi accrual detector
Cassandra and Akka use the phi accrual failure detector. Instead of a yes/no answer, it outputs a suspicion level, phi, based on the history of inter-arrival times of heartbeats from that node. If heartbeats usually arrive every second and the next one is overdue, phi rises smoothly. The application picks a threshold. A higher threshold means fewer false positives but slower detection.
The detector adapts on its own. A node on a slow, jittery link builds a wider history, so it needs a longer delay to reach the same phi.
Suspicion is local and imperfect
A failure detector cannot be both complete and perfect in an asynchronous network. A slow node and a dead node look identical from outside. So each node forms its own opinion, and opinions can differ. Node A may think C is down while node B can still reach it. This is a normal state, and the rest of the design must tolerate it.
For this reason, many systems make a distinction between:
- Suspected or down (local): this node cannot reach the peer. Requests skip it and hints are stored for it.
- Removed (cluster-wide): an explicit, operator-driven decision that the node has left permanently and its tokens are reassigned.
Automatic removal on suspicion is risky. If a network partition makes half the cluster look dead, automatic removal would trigger large data transfers, and that extra load could cause more failures. Dynamo-style systems therefore treat permanent join and leave as administrative actions and treat crashes as temporary.
Joining, leaving, and seeds
A new node needs to find the cluster. It is configured with a few seed nodes, which are well-known addresses. On startup it contacts a seed, receives the membership table, and then gossips normally. Seeds are only a bootstrap aid. They have no special authority once the node is part of the cluster.
When a node joins, it picks its tokens (its virtual node positions), announces them through gossip, and streams the data ranges it now owns from the current replicas. Only after that does it start serving reads. Announcing the tokens before the data is present would send reads to a node that cannot answer them.
A node that leaves gracefully announces a leaving state, streams its ranges to the nodes that inherit them, and is then removed.
Gotchas and failure modes
- Split views. Two nodes may disagree about the ring for a few seconds after a change. Two coordinators can then compute different preference lists for the same key. Quorum overlap and read repair absorb this for short periods. Long disagreement is a sign of a partition or a stuck node.
- Stale entries returning. If a removed node's old entry is still in some tables, gossip can reintroduce it. Real systems keep a tombstone with a generation number, so that a restarted node with a new generation supersedes its old entry, and a removed entry is not revived.
- Gossip storms. Each node sends a fixed number of messages per round, so total traffic grows linearly with the node count. Sending the full table every time is wasteful, so production implementations exchange digests first and send only differences, as the sequence diagram shows.
- Seed dependence. If every node lists the same single seed, new nodes cannot join while it is down. Configure several seeds, spread across failure domains.
- Pauses mistaken for crashes. A long garbage-collection pause stops heartbeats. The node is marked down, then returns. Use an adaptive detector and avoid thresholds tuned too aggressively.
- Symmetric partitions. In a partition each side concludes the other is down. Both sides keep serving, which is the availability choice made in the CAP discussion, and the divergence is repaired later.
Connecting to the rest of the design
Membership feeds two later mechanisms. Request routing uses the table to pick a coordinator and to skip nodes believed down. Sloppy quorums and hinted handoff use failure suspicion to decide when to write to a stand-in node and when to hand the data back after the real owner recovers. If the detector is too eager, you trigger hinted writes needlessly. If it is too slow, requests wait on a dead replica until they time out.
Exercise
A 5-node cluster uses a fixed 3-second timeout detector. One node pauses for 4 seconds during garbage collection and then resumes. Describe what happens, and name one change that reduces the problem without making real crashes much slower to detect.
Show answer
The other nodes see no heartbeat increase for 4 seconds, so they mark the node as suspected and start skipping it and storing hints for it. When it resumes, its counter increases and gossip marks it up again, so the system did extra work for a node that never crashed. Switching to an adaptive detector such as phi accrual, which judges overdue heartbeats against the node's own history, or raising the timeout moderately, reduces false positives. The adaptive detector also keeps detection fast for nodes with steady heartbeats.
Exercise
Why does the gossip merge keep the maximum counter for each node, and why does that make duplicate or reordered messages harmless?
Show answer
Taking the maximum is idempotent, commutative, and associative. Applying the same message twice leaves the table unchanged, and applying messages in a different order produces the same final table. So network duplicates and reordering cannot corrupt the membership view.
Exercise
Why do Dynamo-style stores usually require an operator to remove a node permanently instead of removing it automatically once it is suspected down?
Show answer
Suspicion is local and can be wrong, and a partition can make many healthy nodes look dead at once. Automatic removal would reassign their tokens and start large data transfers, adding load and possibly causing more failures. Treating the outage as temporary and using hinted handoff and repair is safer.