Distributed systems · L2Leader election and leases

Leader election and leases

Many systems need exactly one node in charge. Learn how leases pick that node, why an old leader can still act, and how fencing tokens stop it.

L2 SeniorDistributed systems20 min read
Fact-checked by AI against cited sources · Human review pendingLast reviewed 13 Nov 2026 · How we check content
Section 1 of 8

What broke

On 2 November 2020, a network switch in one Cloudflare data centre partly failed. It stayed up enough that other systems did not route around it. But it dropped some of the packets it should have passed on. 1

Cloudflare's control plane used etcd, a store built on Raft, to coordinate its database clusters. One etcd node sat behind the bad switch. It could reach one peer, but not the etcd leader. 1

That node kept starting elections and voting for itself. The other follower kept voting for the existing leader. The votes tied again and again. Cloudflare writes that Raft leader elections block all writes until they finish, so etcd became read-only. 1

Now two database clusters could not record in etcd that they had a healthy primary. So the cluster manager promoted a synchronous replica to be the new primary. 1

The promotion lost no data. But a bug in the manager forced a rebuild of every replica. One cluster handled authentication for the API and the dashboard. Its new primary had to carry all the reads alone, and it was overloaded. 1

The switch recovered by itself after about six minutes. The incident lasted 6 hours and 33 minutes. API success fell as low as 75%, and the dashboard was up to 80 times slower. Cloudflare's conclusion: "we may not want to invoke the promotion process so quickly." 1

Section 2 of 8

The idea in simple words

Many systems want exactly one node to do a job. A database primary is the only node that takes writes. A scheduler must start each cron job once. In a highly available Kubernetes setup, only one kube-controller-manager and one kube-scheduler are active. The other copies stand by. 6

Picking that one node is leader election. Keeping it safe takes two more tools.

A lease is leadership with an end time. The leader must renew it often. If it stops renewing, for example because it crashed, the lease runs out and another node takes over. Nobody has to prove the old leader is dead. They only have to wait.

But you learned in failure detection that silence is ambiguous. The old leader may be paused, not dead. When it wakes up, it still believes it is the leader. Now two leaders act at once. This is split-brain.

So the last check must sit where the damage happens: in the storage. Every new leader gets a bigger number, called a fencing token. The storage rejects a write that carries a smaller number than one it has already seen. 2 3 Raft calls a similar number a term.

The key idea. A lease tells the old leader when to stop. A fencing token protects your data when it does not stop in time.

Section 3 of 8

How it works

Getting a lease

Do not write this yourself on a plain database row and your own timer. Use a coordination service that already runs consensus, or a tested lock library. How these services work inside is the topic of the later lesson on ZooKeeper, etcd and coordination. Here is what you use from the outside.

  • etcd. A session holds a lease with a time to live. The default is 60 seconds. Campaign blocks until you become the leader. Session.Done closes when the lease ends, so you know to stop. 7
  • ZooKeeper. Each candidate creates an ephemeral node with the sequential flag under one path. The one with the smallest number leads. Each other candidate watches only the node just below its own. So one failure wakes one client, not all of them. 9
  • Consul. You create a session, then try to acquire a key with it. The answer is true if you are now the leader. 10 Consul warns that this lock "has no enforcement mechanism". Any client can still write the key. 10
  • Kubernetes. Control plane parts hold a Lease object to stay the single active copy. 6 The client-go leaderelection package gives your own controllers the same thing. 4
  • DynamoDB. The DynamoDB lock client stores each lock as an item. The owner sends heartbeats that change a record version number. A waiting client takes over only if that number did not change for a full lease period. 11 The record version number is a random UUID, so it is not a fencing token.

Notice one thing in the DynamoDB design. The waiting client does not trust a timestamp from another machine. It times the wait on its own clock. client-go does the same: it acts only on timestamps it captured itself. 4

The timing rules

kube-controller-manager uses three timing settings. 5

SettingDefaultMeaning
Lease duration15 sHow long other candidates wait after the last renewal they saw.
Renew deadline10 sHow long the leader keeps trying to renew before it stops leading.
Retry period2 sThe wait between tries to get or renew the lease.

The renew deadline must be less than the lease duration. 5 That gap is your safety margin. The leader gives up after 10 seconds without a renewal. The others wait 15 seconds before they take over. So a running leader stops about 5 seconds before anyone else starts.

This works only if clocks run at about the same speed. client-go says it tolerates any clock skew, but not any skew rate. 4 Its example: to survive a node whose clock runs twice as fast, set the lease to 60 seconds and the renew deadline to 30. 4 Each node measures how long it waited. It never compares its clock reading with another machine's.

The lease duration also sets your failover time. Kubernetes calls it "effectively the maximum duration that a leader can be stopped before it is replaced". 5

Why the old leader thinks it is still leader

The margin protects a leader that is running. It does nothing for a leader that is not running at all.

Kleppmann describes a client that pauses while it holds a lock. Its lease expires, another client gets the lock, and then the first one wakes up and writes. 2 Stop-the-world GC pauses "have sometimes been known to last for several minutes". 2 A clock jump can do it too. If the lock service's clock jumps forward, it ends the lease while the holder still thinks it has time. 2 Leases need clocks that run at about the same rate and do not jump. 3 4 A network partition looks the same from outside: the old leader is healthy, but its renewals never arrive.

In each case, the old leader's belief is out of date. It checked "am I still the leader?" and then acted. A pause, a clock jump or a lost message came between the check and the act. No check inside the leader can close that gap. Step through it.

A paused leader wakes up; the fencing token stops its late writeA Lease B Storage token 33write · 33max: 33 GC pauserenew 15 s: expiredtoken 34write · 34max: 34 write · 3333 < 34: rejected ✓ A learns it lost the lease and stopsB's newer data is never overwritten SeniorPath
  1. Node A gets the lease with fencing token 33. It writes to the storage and sends the token with the write. The storage remembers the biggest token it has seen: 33.
  2. A stops in a long garbage collection pause. Its renewals never reach the lease service. From the outside, A looks dead. Inside A, nothing has changed.
  3. After the lease duration, here 15 seconds, the lease expires. Node B gets it with token 34 and writes. The storage now remembers 34.
  4. A wakes up. It still believes it is the leader and sends a write with token 33. The storage has already seen 34, so it rejects the write.
  5. The rejection tells A it is no longer the leader. A stops leader work. The lease alone could not stop the late write. The check in the storage did.
Step 1 of 5

Fencing: the storage enforces the term

Google's Chubby lock service, described in a 2006 paper, handles this with a sequencer. It holds the lock name, the lock mode and a lock generation number. The leader sends it with each request. The server checks it and rejects the request if it is no longer valid. 3 The paper's simplest version is even smaller: pass one extra integer, the lock acquisition count, with each write. The file server adds one if-statement that rejects a count lower than the current one. 3

Kleppmann calls this number a fencing token. With ZooKeeper, you can use the zxid or the znode version. 2 With etcd, Election.Rev gives the creation revision of the leader key. 7 etcd revisions only grow over the life of a cluster, so a newer leader gets a bigger one. 8

In your own database, the check is a conditional write:

-- Leader with token 34 writes. A paused leader 33 can no longer win.
UPDATE job_state
SET    last_run = now(), token = 34
WHERE  job_id = 'nightly-report' AND token <= 34;
-- 0 rows changed? A newer leader exists. Stop at once.

This is the same idea as a Raft term in Consensus and Raft. Locks, atomics and deadlocks covers the same fix for a single lock, and Redis in depth covers the Redlock debate.

Libraries say plainly that they do not do this for you. client-go "does not guarantee that only one client is acting as a leader (a.k.a. fencing)". 4 If a system cannot check tokens, Chubby offers a weaker fallback, the lock-delay. When a holder fails, nobody may take its lock for a while, at most one minute. Chubby calls it "imperfect". 3

Failover timing

A short lease means fast failover. It also means more false failovers, because a GC pause or a slow network looks like a crash. A long lease means fewer mistakes, but a real crash leaves you without a leader for longer. client-go puts it this way: tolerance to clock skew rate "varies inversely to master availability". 4

Also ask what the lease is really measuring. At Cloudflare, the databases were fine. The coordination service was sick, and the promotion logic read that as a dead primary. 1 GitHub saw failover go wrong twice too: in 2012 a busy primary was taken for a dead one, and in 2018 a 43-second network cut led to writes on both coasts.

Section 4 of 8

Trade-offs

OptionFast failover?Safe if the old leader wakes up?Use it when
Short lease (a few seconds)Yes No Pauses cause false failovers, and two leaders can overlap.Duplicate work is cheap, like a cache warmer.
Long lease (a minute or more)No Better, but a long pause can still outlast it.Leader work is slow and rare, like a nightly batch.
Lease plus fencing tokenYes Yes The storage rejects old leaders.Leader writes must be correct: money, orders, primary databases.
Chubby-style lock-delayNo Adds the delay to every failover.Partly. Chubby calls it imperfect. 3The storage cannot check tokens.
Human-approved failoverNo Minutes, not seconds.Yes , if the person fences the old primary first.Rare, risky moves of a primary database.
Section 5 of 8

At work: how a senior uses this

  • Ask: "If two nodes believe they lead for one minute, what breaks?" If the answer is "nothing much", a lease is enough. If it is "money moves twice", you need fencing.
  • Find where the token is checked. It must be in the storage or the downstream service, not in the leader's own code.
  • Make leader code stop when it loses the lease. In etcd, watch Session.Done. In client-go, stop all work in the callback for lost leadership.
  • Measure lease time with a monotonic clock, not the wall clock.
  • Check that the renew deadline is clearly shorter than the lease duration, and that both are longer than your worst real GC pause.
  • Ask what triggers a failover. A sick coordination service should not, by itself, promote a new database primary.
  • Check that the new leader can take the full load before it is promoted. At Cloudflare, it had no local replicas left to help. 1
  • Alert on leader changes. Many changes per hour mean the lease is too short or something is pausing.
Section 6 of 8

With AI

What to ask the agent

"Our report job runs on 3 pods and uses client-go leader election. Show the lease settings and explain what happens if the leader has a 30-second GC pause. Which writes could happen twice?"

"Add a fencing token to this job. Take it from the etcd election revision, send it with every write, and make the database reject writes with a smaller token. Write a test for a paused old leader."

"List every automatic failover in our system. For each, say what signal triggers it and whether a sick coordination service alone could trigger it."

What to check yourself

  • The token check is a conditional write in the storage, not an "am I leader?" call just before the write.
  • The token always grows. A host name, random ID or timestamp from the leader's clock is not a fencing token.
  • The leader stops all work on lost leadership. It does not finish the current batch first.
  • Timeouts come from your measured worst pauses, not from guesses.
  • The agent did not shorten the lease for faster failover without saying how many false failovers that adds.
Section 7 of 8

Check yourself

1. A Kubernetes controller uses the default settings: lease duration 15 s, renew deadline 10 s. Why must the renew deadline be shorter?

Show answer

So the old leader stops leading before another candidate is allowed to take over. The leader gives up after 10 seconds without a renewal. The others wait 15 seconds. The gap is the safety margin.

2. The leader holds a valid lease, then has a 40-second garbage collection pause. The lease lasts 15 seconds. What is true when it wakes up?

Show answer

Another node may now be leader, but the old one still believes it leads, until it checks. A paused process cannot notice that time passed. Unless something rejects it, it carries on as leader.

3. Which check actually stops a late write from an old leader?

Show answer

The storage rejects any write whose fencing token is smaller than the biggest one it has seen. A pause can fall between the leader's own check and its write. Only a check at the storage closes that gap.

4. Your app needs a fencing token from an etcd election. What can you use?

Show answer

The creation revision of the leader key, from Election.Rev. etcd revisions only grow over the life of a cluster, so a later leader's key has a bigger revision.

Your progress is saved only in this browser. Export it to keep it safe.

Was this clear?
Report a mistake (opens GitHub in a new tab)
Section 8 of 8

Go deeper

Show 11 sources and related lessons
  1. Tom Lianza and Chris Snook, “A Byzantine failure in the real world”, The Cloudflare Blog (November 2020) (opens in a new tab)
    The official write-up. A partly failed switch stalled etcd elections, and two database clusters promoted a new primary.
  2. Martin Kleppmann, “How to do distributed locking” (February 2016) (opens in a new tab)
    Why a lease can expire while its holder is paused, and how a fencing token makes the storage reject the late write.
  3. Mike Burrows, “The Chubby lock service for loosely-coupled distributed systems”, OSDI 2006 (opens in a new tab)
    Google's lock service for electing primaries. Section 2.4 covers sequencers and lock-delay.
  4. leaderelection package - k8s.io/client-go/tools/leaderelection - Go Packages (opens in a new tab)
    The Kubernetes leader election library. Its overview is honest about fencing and clock skew rate.
  5. Kubernetes documentation, “kube-controller-manager” (opens in a new tab)
    The leader election flags, their defaults and what each one means.
  6. Kubernetes documentation, “Leases” (opens in a new tab)
    How Kubernetes uses Lease objects for node heartbeats and to keep one active copy of control plane parts.
  7. concurrency package - go.etcd.io/etcd/client/v3/concurrency - Go Packages (opens in a new tab)
    Sessions, elections and mutexes on top of etcd leases.
  8. etcd documentation (v3.5), “Data model” (opens in a new tab)
    Every change creates a new revision, and revisions only grow.
  9. Apache ZooKeeper documentation, “ZooKeeper Recipes and Solutions” (opens in a new tab)
    The leader election recipe with sequential ephemeral nodes, and how it avoids the herd effect.
  10. HashiCorp Consul documentation, “Application leader election” (opens in a new tab)
    Leader election for your own app with Consul sessions and a key-value lock.
  11. Alexander Patrikalakis and Sasha Slutsker, “Building Distributed Locks with the DynamoDB Lock Client”, AWS Database Blog (August 2017) (opens in a new tab)
    A lease built on conditional writes, with heartbeats that change a record version number.

Real incident: Cloudflare, 2 Nov 2020: Cloudflare outage: a half-broken switch stalled etcd and set off database promotions

Related: Failure detection and membership · Consensus and Raft · Locks, atomics and deadlocks · Redis in depth · Replication · Time, clocks and ordering · Coordination services: ZooKeeper and etcd

Term

See full entry

Jump to a section

  1. 1What broke
  2. 2The idea in simple words
  3. 3How it works
  4. 4Trade-offs
  5. 5At work
  6. 6With AI
  7. 7Check yourself
  8. 8Go deeper