Skip to content
Lesson 54

Consensus basics

Two machines both sure they're in charge paid 140 hotels twice. Learn how machines agree on one leader by majority, why no vote can stop a frozen ex-leader, and how a rising number checked by the database makes a double run impossible.

The lesson in text

Click a paragraph to hear it.

01Two bosses at 2 a.m.

Every night at two, StayHub pays its partner hotels: about 4,000 hotels, around €2 million in total. The job runs on three machines, so if one dies, another can take over.

But only one machine may pay at a time. So the job uses a lock: think of the single key card to the payout office. Whoever holds it does the work. The lock lives in Redis, expires after 60 seconds, and the holder renews it every 20.

Tuesday, half past seven. Finance opens the bank file. 140 hotels were paid twice last night: €61,000 left StayHub's account by mistake. Karim asks: we had a lock for exactly this. How?

In this lesson, you'll learn how machines agree on one leader, why even a perfect lock can't stop a sleeping one, and the check that makes a double payment impossible.

02The machine that slept

Here's what happened. At two o'clock, machine A takes the lock and starts paying. Ten seconds later, its cloud provider pauses the whole machine for maintenance. For 90 seconds, A is frozen, mid-sentence.

A can't renew the lock while it's frozen. After 60 seconds, the lock expires. Machine B sees a free lock, takes it, and starts paying from the top of the list. So far, everyone followed the rules.

Then A wakes up. From the inside, no time has passed. It still believes it holds the lock, and carries on paying. Two machines, both sure they're in charge.

Two machines, both sure they're in charge
  1. 02:00:00Machine A takes the lock (60 s, renewed every 20 s) and starts paying
  2. 02:00:10A:A's machine is paused for maintenance: frozen for 90 s
  3. 02:01:00Nobody renewed the lock: it expires
  4. 02:01:00B:Machine B takes the free lock and pays from the top of the list
  5. 02:01:40A:A wakes up. For A, no time has passed: it carries on paying
Everyone followed the rules. A frozen program can't feel its own pause, so a longer expiry only waits for a longer pause. Result: 140 hotels paid twice, €61,000.

A frozen program can't feel its own pause. And a longer timer doesn't fix it: five minutes only waits for a six-minute pause. Machines and networks can freeze for longer than you'd think.

03A show of hands

First question: who decides who holds the lock? Here, one Redis machine. If it restarts at the wrong moment, it can forget, and hand the key card to a second holder. For things that must never happen twice, machines take a vote instead.

Think of five colleagues choosing who holds the key card, by a show of hands. Three hands win. That's a majority, and it's the whole trick.

Any two majorities of five share at least one person, and that person can't vote for two different people. So two winners at once is impossible. Agreeing this way is called consensus.

Majorities: why two winners are impossible
ABCDEA, B, C vote for one; C, D, E would need C too.
MachinesMajorityCan lose
321
431 (no better than 3)
532
Any two groups of 3 out of 5 share at least one member, and each member votes once per term. Adding a fourth machine raises the majority to 3 without surviving more failures.

It also survives failures. With five machines, three still decide when two are down. With three machines, two decide, so one can fail.

04Terms and heartbeats

The best-known recipe is called Raft. One machine is the leader. Many times a second, it sends the others a small heartbeat: I'm still here.

If the heartbeats stop, a follower waits a random moment, then stands for election. It raises the term number, say from 5 to 6, and asks for votes. Each machine votes once per term. A majority wins.

A higher term always wins. And a change counts only once a majority has stored it. So an old leader, cut off from the majority, can't make anything final.

An election in Raft, simplified
Leader (term 5)
Follower 1
Follower 2
heartbeat: I'm still here
heartbeat… then silence
term 6: vote for me?
yes (one vote per term)
term 6 leader: 2 of 3 votes
A higher term always wins, and a change is final only once a majority has stored it, so a leader cut off from the majority can't make anything final. Tools like etcd and ZooKeeper do all this for you.

You'll never build this yourself. Tools like etcd and ZooKeeper do it for you. Kubernetes, for example, keeps its whole state in etcd.

05No vote wakes a sleeper

So, is a voted lock enough for the payouts? Not quite. A vote makes sure there's one leader per term. It can't reach into a frozen machine and tell it that its term is over.

You might add a check before each payment: do I still hold the lock? But the freeze can come right after the check. Yes, I hold it. Frozen for 90 seconds. Then it pays, with exactly the old belief.

Only one party can catch a stale leader at the moment it acts: the thing it writes to. Here, that's the payouts database.

06The newer key card

Think of a hotel room. A guest loses her key card, and the desk makes a new one. The new card opens the door. The old one, found later in a coat pocket, doesn't. The door remembers the newest card.

Do the same with the lock. Every time it's granted, it comes with a number that only goes up. Machine A got 33. Machine B, a minute later, got 34. That number is a fencing token.

The payouts database remembers the highest token it has seen. A payment arrives with token 33. The database answers: I've seen 34. Refused. And the check runs in the same transaction as the payment, so nothing can slip in between.

A fencing token, checked by the database
Machine A (token 33)
Payouts database
Machine B (token 34)
payout, token 34 → highest seen: 34
wakes up: payout, token 33
refused: 34 already seen. A stops; alert
BEGIN;one transaction
UPDATE fences SET token = 33 WHERE resource = 'payouts' AND token <= 33;0 rows: a newer holder exists → stop
INSERT INTO payouts (hotel_id, period, cents) … ON CONFLICT DO NOTHING;the payout itself
COMMIT;
Like the newest key card: the database remembers the highest token it has seen and refuses older ones. The check and the payout are in one transaction, so a pause can't fall between them.

So when A wakes up, its very next payment is refused, and it stops. An alert says a machine was fenced: a pause happened, and the system caught it.

07Make a second run harmless

Two more layers. First, make a double payout impossible in the data itself. The payouts table gets a rule: one payout per hotel and per period. A second one is simply refused.

Second, each bank transfer carries a key built from the hotel and the period. Sent twice, it's paid once. You met this in the lesson on retries.

And who grants the lock? StayHub adds no new system. The payouts database already holds the payouts, so it grants the lock too, with its token. One place, one transaction.

Three layers. The lock makes two runners rare. The token stops a stale one. The rule makes a double payout harmless anyway. Then test it: pause a machine for 90 seconds on purpose, and count the payouts.

Three layers against a double payout
Lease from the payouts database
Makes two runners rare. No new system: the database that holds the payouts grants the lock.
Fencing token
Stops a stale runner: every payout checks the token in its own transaction. Alert when a machine is fenced.
One payout per hotel and period
Makes a double payout harmless anyway: a unique rule in the table, and a key on each bank transfer.
Test it on purpose: on staging, pause a machine for 90 seconds in the middle of a run, then count the payouts per hotel. Each hotel must be paid exactly once.

08Four is not safer

A few weeks later, the search team runs its own etcd, to pick one leader for the job that rebuilds the search index. Four machines, two in each of two data centres, called zones. Four is safer than three, they say.

At 11:20, the link between the two zones drops for six minutes. Each side has two machines. A majority of four is three. Neither side has three.

So there's no leader at all. For six minutes, the search index stops updating, and guests see stale prices. Consensus never allows two leaders. The price is that sometimes, it allows none.

Four machines need three votes, so they survive one failure, exactly like three. Use odd numbers: three or five. And spread them over three zones, one each, so losing any zone still leaves two of three.

Count majorities, not machines
4 nodes, 2 zones
Zone A: ● ● · Zone B: ● ●
Link cut: 2 and 2, majority needs 3 → no leader
3 nodes, 3 zones
Zone A: ● · Zone B: ● · Zone C: ●
Lose any zone: 2 of 3 remain → still a leader
11:20, the link between two zones drops for 6 minutes: the 4-node cluster has 2 + 2, no side reaches 3, so there's no leader and the search index stops updating. One node in each of three zones keeps 2 of 3 after losing any zone.

09Your job as lead

Karim wants a proper etcd cluster for all of StayHub's coordination. Omar says: that's a new critical system on my pager at two in the morning, and the payouts already live in Postgres. For now, Omar wins. Write down when to revisit: when several jobs in different databases need leaders.

Then Claude Code proposes its fix: the lock now lasts five minutes, and before each payment, the code checks that it still holds the lock. Both feel safe. Neither is.

A longer timer only waits for a longer pause, and the check can come just before the freeze. Ask instead for one payout per hotel and period, and a token the database checks in the same transaction as each payout.

For anything that must happen only once, ask: what does it cost if two run at once? What makes a second run harmless? Who checks the token? And for anything that votes: how many machines, in how many zones?

Let's recap. Machines agree by majority, in terms that only go up. A vote gives one leader per term, but can't wake a sleeper, so the database refuses old tokens. Make a second run harmless, and count majorities, not machines. Next, a new module: what the network does with every packet.

Check yourself

0/10 answered
  1. 1Machine A took the lock, froze for 90 seconds, and the lock expired; machine B took it. Why did A keep paying when it woke up?

  2. 2Five machines vote on a leader. How many votes win?

  3. 3Why can't two leaders win the same election?

  4. 4A five-machine cluster splits into a group of two and a group of three. Which side can elect a leader?

  5. 5What is a fencing token?

  6. 6Claude Code adds a check before each payment: "do I still hold the lock?" Is the race closed?

  7. 7A guest finds her old key card in a coat pocket after the desk made her a new one. What does the door do?

  8. 8The search team runs etcd on four machines, two in each of two zones. The link between the zones drops. What happens?

  9. 9How should you size a cluster that votes?

  10. 10What is the best first protection against paying a hotel twice?

Free account

Save your progress — create a free account

Free. No card. Your finished lessons follow you to any device, and you can ask questions in the community.

Create my free account
Founding members

Every lesson is free while we build. Lock in €9/month for later.

The first 100 members keep the founding price for as long as they stay. Reserving is free: no card, nothing is charged.

See the founding offer

Questions from the community

All questions →