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.
- 02:00:00Machine A takes the lock (60 s, renewed every 20 s) and starts paying
- 02:00:10A:A's machine is paused for maintenance: frozen for 90 s
- 02:01:00Nobody renewed the lock: it expires
- 02:01:00B:Machine B takes the free lock and pays from the top of the list
- 02:01:40A:A wakes up. For A, no time has passed: it carries on paying
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.
| Machines | Majority | Can lose |
|---|---|---|
| 3 | 2 | 1 |
| 4 | 3 | 1 (no better than 3) |
| 5 | 3 | 2 |
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.
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.
BEGIN;one transactionUPDATE fences SET token = 33 WHERE resource = 'payouts' AND token <= 33;0 rows: a newer holder exists → stopINSERT INTO payouts (hotel_id, period, cents) … ON CONFLICT DO NOTHING;the payout itselfCOMMIT;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.
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.
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 answered1Machine 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?
2Five machines vote on a leader. How many votes win?
3Why can't two leaders win the same election?
4A five-machine cluster splits into a group of two and a group of three. Which side can elect a leader?
5What is a fencing token?
6Claude Code adds a check before each payment: "do I still hold the lock?" Is the race closed?
7A guest finds her old key card in a coat pocket after the desk made her a new one. What does the door do?
8The search team runs etcd on four machines, two in each of two zones. The link between the zones drops. What happens?
9How should you size a cluster that votes?
10What is the best first protection against paying a hotel twice?
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 accountEvery 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