Chapter 07 / 10 · Distributed Systems

Membership, failure detection and coordination

A wallet server pauses for fifteen seconds, loses its lease, and wakes up still acting as owner. The storage has to say no.

This chapter lets you hand out authority in a cluster safely: decide that a machine is probably dead, give its work to another, and make sure that if the first machine was only paused, it cannot do damage when it wakes. The tools are failure detectors, a small coordination service, leases and fencing tokens.

The wallet has grown. Accounts are split into 64 shards, and each shard has one primary wallet server that processes its transfers. Which server is primary for which shard is decided by a coordination service built on consensus, etcd in our case, using the approach from the end of the last chapter. Server A is primary for shard 7. Mid-transfer, A’s runtime starts a garbage-collection pause that lasts fifteen seconds. Everyone else concludes A is dead and gives shard 7 to server B. Then A wakes up and finishes the transfer it was in the middle of.

Deciding that someone is dead

The first chapter established that a dead machine and a slow one look identical from outside. A failure detector therefore cannot report facts. It reports suspicion, and the design question is how to make that suspicion accurate enough to act on and fast enough to matter.

The simplest detector is a heartbeat with a fixed timeout: A sends “I am alive” every second, and if five seconds pass without one, A is declared dead. The two numbers trade against each other. A five-second threshold mistakes any pause longer than five seconds for a death. A thirty-second threshold rarely makes that mistake, but shard 7 stops processing transfers for thirty seconds every time a server genuinely dies.

Adaptive detectors do better by learning what normal looks like. The phi accrual detector, used in Cassandra and Akka, records the intervals between recent heartbeats and, at any moment, computes how unlikely the current silence would be if the node were alive. It reports that as a number, phi, on a logarithmic scale: a phi of 8 means that under the model of recent arrivals, a live node would be this late about one time in a hundred million. On a network where heartbeats normally arrive within 2 ms, a 500 ms gap is alarming; on a jittery cross-region link, the same gap is routine. A fixed timeout treats both the same.

At cluster scale, a different problem appears. If each of 1,000 nodes sends a heartbeat to every other node every second, that is about a million messages per second spent on knowing who is alive. SWIM, the protocol behind HashiCorp’s memberlist and therefore Consul, replaces that with two ideas. Each round, a node pings one random member. If no reply comes, it does not conclude anything yet; it asks a few other members to ping the silent node on its behalf. Only if none of them get a reply is the node marked suspect, and the suspicion is spread by piggybacking it on the pings that are being sent anyway. The indirect probe matters because a bad link between two particular machines should not convince the whole cluster that one of them is dead. Each node sends a constant number of messages per round regardless of cluster size.

None of these detectors can be right every time. The design consequence is that anything the system does on the basis of “A is dead” must be safe even when A is alive. The rest of the chapter is about making that true.

Put agreement in one small service

Every wallet server could run Raft with every other to decide shard ownership, but that spreads delicate code across the fleet. The common alternative is a small, separate coordination service, such as etcd, ZooKeeper or Consul, that runs consensus among three or five machines and exposes a few primitives: a strongly consistent key-value store, compare-and-set operations, watches that notify clients of changes, and leases or sessions that expire if a client stops renewing them.

Leader election for a shard is a few lines on top of those primitives. Each server that wants shard 7 tries to create the key /wallet/shards/7/primary with its own name, attached to its lease, and only if the key does not exist. One succeeds. The others watch the key. If the primary’s lease expires, etcd deletes the key, the watchers are notified, and they race to create it again.

The ZooKeeper paper’s lasting point is about what does not go through this service. Transfers go from the API to shard 7’s primary directly. The coordination service sees only lease renewals and ownership changes: 64 shards renewing once a second is 64 small writes per second, well within what a three-node etcd cluster handles. etcd’s documentation suggests keeping its data to a few gigabytes. It is built to hold the small facts everyone must agree on, not the data itself.

A lease is a promise with an expiry

Ownership must expire. A lock with no expiry, held by a server that has died, leaves shard 7 unowned forever, or until someone intervenes at 3 a.m. A lease is ownership for a fixed period, renewed while the holder is healthy. Say the lease lasts ten seconds and A renews it every three.

The holder has to reason carefully about its own lease. It should measure the lease from the moment it sent the renewal request, not when the reply arrived, because the server may have started the lease when it processed the request. It should use the monotonic clock, for the reasons in the time chapter. And it should stop acting some margin before ten seconds have passed, to allow for clocks that run at slightly different rates. Note what this assumes: not that A’s clock and etcd’s clock agree on the time, but that they agree roughly on how long ten seconds is. That is a much weaker and more reliable assumption.

Leases also explain the leader-lease reads from the consensus chapter. A leader that has just heard from a majority knows no other leader can be elected for about an election timeout, so for slightly less than that it can serve reads without checking. The same reasoning, the same clock-rate assumption, and the same weakness, which is next.

Predict first

A holds the lease for shard 7. It checks the lease (valid, two seconds left), reads Asha’s balance (₹2,000), and is about to write the new balance of ₹1,500 when a 15-second pause begins. During the pause the lease expires, B takes shard 7, and B processes another of Asha’s payments, writing ₹1,200. Then A resumes. What happens, and could A have prevented it by checking its lease again just before writing?

Show the worked answer

A resumes exactly where it stopped, unaware that fifteen seconds have passed, and writes ₹1,500. B’s write of ₹1,200 is overwritten. Asha has made two payments and been charged for one. This is a lost update caused by two servers each believing they own shard 7.

Checking again does not help. The pause can happen between the check and the write, no matter how close together they are. A process cannot know that it has been paused, and cannot make a check and a write on another machine happen as one indivisible step. Any protection has to live where the write lands.

Fencing tokens: make the storage say no

The fix is a fencing token. Every time the coordination service grants ownership of shard 7, it attaches a number that is larger than any it has granted before. In etcd, the revision at which the ownership key was created serves; in ZooKeeper, the version or transaction id of the node does. A’s grant carried token 33. B’s carries 34.

The holder sends its token with every write, and the storage remembers the highest token it has seen for the shard. It rejects any write carrying a lower one.

wallet Alock servicewallet Bledger storagelease · token 33pausedlease expirestoken 34write · 34 ✓highest seen = 34write · token 33rejected · 33 < 34
Fig 7 · A is paused while holding token 33. B gets token 34 and writes. When A wakes and writes with 33, the storage rejects it

In a SQL database, the check can be one conditional statement at the start of the transaction that writes the balance:

BEGIN;
UPDATE shard_fence SET token = 33
  WHERE shard = 7 AND token <= 33;
-- 0 rows updated: someone with a newer token has written. ROLLBACK.
UPDATE accounts SET balance = 1500 WHERE id = 'asha';
COMMIT;

When B first writes with 34, the fence moves to 34. When A wakes and tries 33, the condition fails, A rolls back, and on seeing the rejection it knows it has lost ownership. The protection works no matter how long the pause was or what A believes, because the decision is made by the storage, which sees every write in order.

The cost is that every system that receives writes must take part. The shard’s database can check tokens. The bank’s payout API, which the wallet calls when Asha withdraws to her bank account, cannot be asked to. For those, the idempotency key from the RPC chapter is the defence: if A wakes and resends a payout that B already sent, the bank sees the same key and returns the earlier result. Where neither fencing nor idempotency is possible, such as an SMS provider without keys, a duplicate is possible and the design should make it harmless.

Two kinds of lock

Not every lock needs fencing, and the distinction saves real effort. Martin Kleppmann draws it clearly in his essay on distributed locking: some locks exist for efficiency, others for correctness.

PurposeExample in the walletIf two holders act at onceWhat is enough
EfficiencyOnly one server builds the nightly statement PDFsSome statements are built twice; wasted CPUA lease, even an approximate one
CorrectnessOnly one server writes shard 7’s balancesLost updates, wrong balancesA lease plus fencing at the storage
External effectOnly one server sends a given bank payoutMoney sent twiceIdempotency keys at the receiver

Locks built on a cache with expiry, such as a key in Redis with a timeout, are reasonable for the first row and dangerous for the second, because nothing downstream checks them. The question to ask of any lock is what happens if two processes hold it at the same moment. If the answer involves money, the lock alone is not the protection.

How long should a lease be?

The lease length sets two numbers that pull against each other. When A genuinely dies, shard 7 is unowned until A’s lease expires. If A renewed just before dying, that is the full ten seconds, plus the time for B to notice, acquire the key and load whatever state it needs. Shard 7’s users see roughly ten to twelve seconds in which transfers fail or wait.

A two-second lease would cut that to two or three seconds. It would also mean that any pause, network hiccup or slow renewal longer than two seconds costs A its ownership, whether or not A was in trouble. Each unnecessary handover has its own cost: transfers in flight on A are rejected by the fence and retried, B starts with cold caches, and if the cause was a slow network rather than a slow A, B may lose the lease in turn. Renewal traffic is rarely the constraint; 64 shards renewing every 600 ms is about a hundred small writes per second.

The sensible way to choose is from measurements. Look at the longest pauses the wallet servers actually experience, from garbage collection, from the hypervisor, from disk stalls, and at the latency distribution of renewals to the coordination service. Set the lease comfortably above the worst of those, and then ask whether the resulting failover time is acceptable for a shard. If it is not, the remedy is usually to shorten the pauses, for example by tuning the runtime, rather than to shorten the lease below them.

When the coordination service is the outage

Moving agreement into one small service concentrates a risk, and it is worth walking through how it materialises.

etcd commits every write to disk before acknowledging it, so its latency follows its disk’s flush latency; its documentation is emphatic about giving it fast, dedicated storage. Suppose the etcd machines share storage with a noisy neighbour, as the wallet did in the first chapter, and flushes slow from milliseconds to seconds. Lease renewals from the wallet servers begin to time out. Nothing is wrong with any wallet server, but within one lease period, every primary has failed to renew. Correctly, each one stops processing transfers for its shard, because it can no longer prove it is the owner.

Then every server tries to acquire the now-free shards, which means 64 contested writes to an etcd that is already too slow to handle renewals. Some acquisitions succeed, some time out, some servers win shards and lose them again at the next renewal. For several minutes, the wallet processes almost no transfers, although no wallet server and no wallet database failed. The coordination service is not on the data path, but it is on the availability path.

The mitigations each cost something. Dedicated fast disks for etcd cost money. A separate etcd cluster for the wallet, rather than one shared with the rest of the company, costs operational effort, and buys isolation from other teams’ load. Leases somewhat longer than etcd’s worst plausible hiccup cost slower failover. Spreading the start times of renewals, and backing off acquisition attempts with jitter, keeps a recovery from becoming a stampede. What should not change is the primaries’ behaviour: a server that cannot renew its lease must stop, because continuing would bring back exactly the split ownership the lease exists to prevent.

Coordination you can design away

The cheapest coordination is the kind the design makes unnecessary. Assigning each account to exactly one shard, with one owner, means transfers within a shard need no distributed locks at all: the owner orders them in its own log. If each shard is itself a Raft group, Raft’s term number already acts as a fencing token, since a follower rejects appends from a leader with an older term, and the storage layer and the consensus layer are the same thing.

The coordination service is also easy to misuse. It is not a database, so wallet data does not belong in it. It is not a queue, so using watches as a work queue for every transfer puts the data path back through consensus. And it is shared, so a burst of writes from one team’s misbehaving client can slow lease renewals for everyone, causing leases to expire across the fleet. Revisit the setup if lease renewals start to approach the service’s write capacity, or if ownership changes often enough that the time spent moving shards becomes visible to users.

Every transfer so far has stayed within one shard. Asha and Ravi, however, are on different shards with different owners, and a transfer between them has to debit one and credit the other atomically. The next chapter, Distributed transactions, looks at the ways to do that and what each one costs.