Leader Election: Exactly One Active Node
"Raft ensures that there is at most one leader in a given term." — Diego Ongaro and John Ousterhout, In Search of an Understandable Consensus Algorithm (Extended Version), section 5.1, 2014
Summary: Leader election picks one node out of many to do a job that must not be done twice at the same time (schedule, compact, own a partition, accept writes); every practical method gives you "at most one leader per term or epoch", never "exactly one at every instant", so the leader's writes must carry that epoch and the storage must reject old ones. Focus: Why single-leader roles exist, split brain under partitions and pauses, Raft election (terms, randomized election timeouts, RequestVote, heartbeats, the election restriction, Pre-Vote, CheckQuorum, leader leases), Paxos/Multi-Paxos and ZAB in one paragraph each, leases on etcd, ZooKeeper, Consul and the Kubernetes Lease object with client-go's LeaseDuration / RenewDeadline / RetryPeriod, database and Redis leadership, fencing tokens (term, leader epoch, controller epoch, zxid, create revision), failover arithmetic, graceful step-down, hot standby, per-shard leaders (Kafka partitions, CockroachDB and TiKV Raft groups), bully and ring algorithms, observability, Jepsen-style testing, and the Laravel tools (onOneServer, Horizon's master supervisor, a singleton worker). Learning goal: Choose the election mechanism for a role from what you already run; size lease and timeout knobs and state the failover time and the safety margin they give; fence every write the leader makes; and prove the behaviour with partition tests instead of hoping.
This chapter closes the Resilience group, right after Distributed Locking, which owns Redis locks, Redlock and the lock-level view of fencing tokens; here a lock is just one way to hold a leadership role. Neighbours keep their depth: Replication Topologies owns what the leader does with the data (leader-follower, multi-leader, leaderless); Distributed SQL, Consensus & 2PC owns consensus inside databases; Replication, Read Replicas & Failover owns PostgreSQL/MySQL failover tooling (Patroni and friends); CAP and PACELC owns the theorem you hit during a partition; Gossip Protocols owns failure detection by gossip; Kafka in Depth owns the broker; Containers & Kubernetes owns the platform the Lease object lives in.
Page map
| If you are looking for | Go to |
|---|---|
| The whole page in three tables | Everything in one minute |
| Why one leader at all, and why "exactly one" is impossible | Why it exists, Split brain |
| Bully, Lamport's Paxos, Chubby, ZooKeeper, Raft, Kubernetes | Where it comes from |
| Terms, epochs, the logical clock behind fencing | Terms and epochs |
| Raft: randomized election timeout, RequestVote, heartbeat, election restriction | Raft leader election |
| Pre-Vote, CheckQuorum, disruptive servers | Pre-Vote and CheckQuorum |
| Leader lease, lease-based reads, ReadIndex | Leader lease |
| Paxos, Multi-Paxos, ZAB, Kafka KRaft | Paxos, Multi-Paxos and ZAB |
| TTL, renew, holder identity on a store | Leases on a coordination store |
| Kubernetes Lease, client-go leaderelection, LeaseDuration/RenewDeadline/RetryPeriod | Kubernetes |
| etcd campaign, ZooKeeper ephemeral node, Consul leader | etcd, ZooKeeper, Consul |
| Advisory lock, lease row, FOR UPDATE SKIP LOCKED | Database-based election |
| Redis as a leadership lock | Redis-based election |
| Fencing tokens: leader epoch, controller epoch, zxid | Fencing the leader's writes |
| Detection time vs lease length vs false positives | Failover timing |
| Graceful step-down, hand-off, hot standby | Step-down and standby |
| Kafka partition leaders, Raft groups in CockroachDB/TiKV | Per-shard leaders |
| Bully and ring algorithms | Classic algorithms |
| Metrics, logs and alerts for leadership | Observability |
| Partition tests, Jepsen | Testing |
Laravel scheduler onOneServer, Horizon, singleton workers | Laravel patterns |
| Knobs, defaults, arithmetic, error codes | Mechanics |
| Code | Go, Laravel |
| Ten classic failures and their fixes | Solving the classic problems |
| Which mechanism for which role | Choosing |
| From one server to many regions | In architecture |
| Runnable simulator and expected experiments | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The approaches.
| Approach | In plain words | Who decides | Fencing token | Typical failover | Examples |
|---|---|---|---|---|---|
| Consensus inside the system | The replicas vote; a majority makes a leader for one term | The replicas themselves | Raft term, Kafka leader epoch, ZooKeeper zxid epoch | About one election timeout (Raft paper: 150-300 ms recommended; etcd default 1000 ms) | etcd, ZooKeeper, Consul servers, Kafka KRaft controllers, CockroachDB, TiKV |
| Lease on a coordination store | Candidates race to write "I hold it until T" in a store that runs consensus | The store's compare-and-swap | Lease transitions, etcd create revision, zxid, Consul LockIndex | Lease length: client-go defaults 15 s | Kubernetes Lease via client-go, etcd Campaign, ZooKeeper ephemeral sequential znodes, Consul sessions |
| Database row or lock | The same, with your SQL database as the store | The database | An epoch column you add | Lease TTL you choose; advisory locks: until the session dies | PostgreSQL lease row, pg_try_advisory_lock, FOR UPDATE SKIP LOCKED shard claims |
| Redis lock | SET key owner NX PX ttl, renewed while working | One Redis primary | None built in; add one | Lock TTL | Laravel Cache::lock, onOneServer |
| Static assignment | A config flag says who is leader | A human | None | Until someone notices | IS_LEADER=true on one host (an anti-pattern) |
| Bully / ring | Highest live ID wins after messages around the group | The processes | Usually none | Depends on timeouts | Textbook; not used at scale |
The knobs that decide behaviour.
| Knob | Product | Default | Too low | Too high |
|---|---|---|---|---|
| Election timeout | Raft paper / etcd | 150-300 ms suggested / --election-timeout=1000 ms | False elections, leader churn | Slow failover |
| Heartbeat interval | etcd --heartbeat-interval | 100 ms | CPU and network spent on heartbeats | Long election timeout needed |
LeaseDuration | client-go leaderelection | 15 s | Leadership flaps on API-server latency | Standbys wait long after a crash |
RenewDeadline | client-go | 10 s | Leader gives up on short API hiccups | Smaller safety margin to LeaseDuration |
RetryPeriod | client-go | 2 s | Load on the API server | Slow acquire and renew |
| Session TTL | etcd concurrency.WithTTL | 60 s | Leadership lost on a short GC pause | Slow failover |
| Session timeout | ZooKeeper (negotiated) | min 2 x tickTime, max 20 x tickTime (tickTime=2000 ms in the sample config) | Expired sessions on pauses | Slow failover |
LockDelay | Consul session | 15 s | Quick re-acquire after invalidation, more risk | Longer gap after a holder dies |
| Lock TTL | Laravel Cache::lock($name, $seconds) | Your choice; scheduler run locks use 3600 s | Lock expires mid-job | Dead server blocks the role |
The failure cases in one table.
| Event | What a correct design does | What a naive design does |
|---|---|---|
| Leader crashes | Standby takes over after the lease or election timeout, epoch + 1 | Nothing until a human moves the flag |
| Leader is partitioned from the majority / store | It stops after RenewDeadline or CheckQuorum; the majority elects a new leader | Both sides act: split brain |
| Leader pauses (GC, VM freeze, SIGSTOP) longer than the lease | A new leader starts; the old one wakes up and its writes are rejected by epoch | The old leader overwrites the new leader's work |
| Clocks run at different rates | Tolerated up to LeaseDuration / RenewDeadline | Overlapping leaders |
| Planned deploy | Leader finishes the current unit, releases or resigns, standby takes over in about one retry period | Everyone waits a full lease, or two run during the roll |
| Network flaps briefly | Pre-Vote / CheckQuorum keep the current leader | Repeated elections, term inflation, availability drops |
The picture is the whole decision. Columns 1 and 2 put the hard part (agreement) in a system built for it; columns 3 and 4 reuse what you already run. In every column the fencing check lives in the store you write to, not in the leader.
Why it exists
Many jobs are correct only when one process does them at a time: a cron-style scheduler that sends invoices, a compactor that rewrites files, a partition owner that orders writes to one key range, a controller that reconciles cluster state, the primary that accepts writes for a replicated database. Run two and you get double charges, interleaved rewrites, conflicting writes and fights over the same object. Run none and the work stops. Leader election is how a group of identical replicas picks the one that acts, and how they pick another when it fails.
| Role | Why it must be single | What two leaders cause |
|---|---|---|
| Scheduler (billing run, report, cleanup) | Each run must happen once | Duplicate invoices, duplicate e-mails |
| Compactor / garbage collector | Rewrites shared files | Deleted live data, corrupted segments |
| Partition or shard owner | Defines the order of writes | Diverging replicas, lost updates |
| Kubernetes controller / operator | Reconciles desired vs actual state | Two controllers fight; resources flap |
| Database primary / Raft leader | Single source of the log order | Split brain: two histories |
| Kafka controller | Assigns partition leaders | Conflicting leadership decisions |
| Sequencer / ID allocator | Hands out increasing numbers | Duplicate IDs |
The fundamental trade-off:
| Simpler / faster failover | Safer / stronger |
|---|---|
| Short lease or election timeout | Longer timeout: fewer false positives |
| Trust the leader's own belief | Fence every write with an epoch |
| Redis or a cache lock | A consensus store (etcd, ZooKeeper, Kubernetes API) |
| One leader for everything | One leader per shard |
| Wait for the lease to expire on deploy | Graceful release or resign |
The analogy we reuse on this page: the night shift supervisor's badge. A factory runs around the clock and exactly one person may sign off on shipments. The badge is valid until the time printed on it; the supervisor must go to the front desk to have it re-stamped every hour. If the supervisor faints in a storeroom, the desk waits until the printed time passes, then issues a new badge with a higher serial number to a colleague. The loading dock only accepts signatures with the highest serial number it has seen. When the fainted supervisor wakes and signs with the old badge, the dock refuses. The printed time is the lease, the re-stamp is the renewal, the serial number is the epoch, and the dock's check is fencing.
Leader election, locks, consensus, failover, service discovery
| Mechanism | Question it answers | Owner page |
|---|---|---|
| Distributed lock | Who may touch this resource now? (short, per operation) | Distributed Locking |
| Leader election | Who holds this role until it fails? (long-lived) | This page |
| Consensus | What value or log order did a majority agree on? | Distributed SQL, Consensus & 2PC |
| Database failover | Which replica becomes the primary? | Replication & Failover |
| Service discovery | Where is the leader, so I can send it requests? | Service Discovery |
| Failure detection | Is that node dead or just slow? | Gossip Protocols |
A leader election is a lock with a long lifetime, an identity that others can read, and a hand-off procedure. Most production elections are built from a lock (a lease) on top of a consensus system.
Three common misunderstandings, up front
- "Leader election guarantees exactly one leader." It guarantees at most one leader per term or epoch (Raft, ZAB, Kafka) or at most one lease holder according to the store. A deposed leader can still be running and still believe it leads. client-go says it plainly: the implementation "does not guarantee that only one client is acting as a leader (a.k.a. fencing)".
- "If I check
isLeader()before each write, I am safe." The check and the write are two steps; a pause between them (Kleppmann's example is a stop-the-world GC pause) lets the lease expire after the check passed. Only a check inside the storage, atomic with the write, closes the gap. - "Short timeouts mean high availability." Short timeouts mean fast detection of real failures and frequent false positives: elections triggered by a slow disk or a GC pause. Each false election is a small outage. The Raft paper's rule is
broadcastTime ≪ electionTimeout ≪ MTBF.
Where it comes from
Bully algorithm, 1982. Hector Garcia-Molina's paper "Elections in a Distributed Computing System" (IEEE Transactions on Computers) introduced the bully algorithm, in which the process with the highest ID among the live ones becomes coordinator. We read the Wikipedia summary, not the original paper (secondary source). Ring-based elections (Chang and Roberts, 1979) pass an election message around a logical ring.
Paxos, 1989/1998 and 2001. Leslie Lamport's Paxos solved consensus with crash failures and an asynchronous network; Paxos Made Simple (2001) opens with "The Paxos algorithm, when presented in plain English, is very simple." Multi-Paxos runs a long-lived distinguished proposer, which is a leader in all but name.
Chubby, 2006. Google described Chubby, a lock service built on Paxos, used by systems such as GFS and Bigtable to elect masters (we saved the Google Research page; the paper's text is not quoted here).
ZooKeeper and ZAB, 2008-2011. Apache ZooKeeper offered coordination "recipes" on top of its atomic broadcast protocol ZAB. Its leader election recipe uses SEQUENCE|EPHEMERAL znodes and watches only the predecessor to avoid the "herd effect". Its internals page explains the zxid: "The epoch number represents a change in leadership."
Raft, 2014. Ongaro and Ousterhout designed Raft for understandability, with leader election as a separate subproblem: terms, randomized election timeouts and two RPCs. etcd, Consul, CockroachDB, TiKV and Kafka's KRaft mode all use Raft or a dialect of it.
Kafka leader epoch, 2017, and KRaft. KIP-101 added a leader epoch to every message to fix log truncation bugs; KIP-595 then defined Kafka's Raft dialect for the metadata quorum, where the leader epoch is "used both to fence zombies and to reconcile logs which have diverged."
Kubernetes leader election. Control-plane components (kube-controller-manager, kube-scheduler) use the coordination.k8s.io/v1 Lease object so that only one instance is active "while the other instances are on stand-by"; client-go's leaderelection package is how operators and controllers do the same.
Year Event What changed in practice
1 1979 Chang & Roberts ring election Election by passing messages around a ring
2 1982 Garcia-Molina bully algorithm Highest live ID wins; assumes reliable timeouts
3 1989+ Lamport's Paxos; 2001 Paxos Made Simple Safety under partitions with a majority quorum
4 2006 Google Chubby (Paxos lock service) Elect masters by holding a lock in a consensus service
5 2008+ ZooKeeper recipes, ZAB, zxid epochs Ephemeral sequential znodes; epoch per leadership
6 2014 Raft (Ongaro & Ousterhout) Terms, randomized timeouts; etcd, Consul, CockroachDB
7 2017 Kafka KIP-101 leader epoch Epoch stamped on every record
8 2020+ Kafka KIP-595 KRaft Raft-style controller quorum, no ZooKeeper
9 - Kubernetes Lease + client-go leaderelection Lease object with holderIdentity and leaseTransitionsThe concept catalogue
Every block follows the same order: plain words, the usual misunderstanding, a definition, a timeline, real scenarios, per-product behaviour, and how to use it.
Single leader: why some work needs one owner Must-know
In plain words: some work is only correct if one process does it at a time, so the replicas agree on one of them to do it and keep the others ready.
Common misunderstanding: "Every service should be stateless and horizontally scaled, so leaders are a smell." Request handling should be; but ordering, scheduling, compaction and reconciliation are naturally single-writer. Making them parallel safely means partitioning them (one leader per shard), not removing the leader.
Definition: a single-leader role is a named responsibility (for example billing-scheduler) with at most one active holder per epoch; the other replicas are standbys that campaign for the role when it becomes free.
Three replicas, role "billing-scheduler"
1 r1, r2, r3 start; all campaign
2 r2 wins (epoch 1) and runs the billing loop; r1, r3 wait as hot standbys
3 r2 crashes at 02:00:10
4 the lease expires at 02:00:25; r3 wins (epoch 2) and resumes from the stored cursor
5 r2 restarts at 02:01:00 and becomes a standbyReal scenario: a monthly invoice run that must charge each customer once; a search index compactor; Kubernetes controllers in a highly available control plane; a Kafka KRaft active controller with hot standbys; a job that renews TLS certificates for a fleet; a single WebSocket "presence" aggregator per region.
What provides it:
| Product | Leader role | Standbys |
|---|---|---|
| Kubernetes control plane | One active kube-controller-manager, one active kube-scheduler | Other instances "on stand-by" via the Lease |
| Kafka KRaft | One active controller | "Each controller is either an active or a hot standby" |
| PostgreSQL with Patroni | One primary accepting writes | Replicas, promoted by the DCS (etcd/Consul/ZooKeeper) lease |
Laravel scheduler with onOneServer | Per run, one server executes the task | Other servers skip that run |
| Horizon | One master supervisor per machine (not per cluster) | None: other machines run their own |
Fix / how to use it: name the role, decide the mechanism (Choosing), make the leader's work resumable from stored state (a cursor), and fence its writes.
Split brain and why "exactly one" is impossible Must-know
In plain words: a node cannot tell "the others are dead" from "I am cut off" or "I was frozen", so there are moments when two nodes both believe they lead.
Common misunderstanding: "With a good enough failure detector, we will never have two leaders." In an asynchronous network no timeout distinguishes a dead node from a slow one. A process can also be paused after any instruction, including right after it checked that it is the leader.
Definition: split brain is the state where two or more nodes act as leader for the same role at the same time. Majority-based protocols prevent two leaders from being elected in the same term, but cannot stop a deposed leader from believing it still leads until it hears about the newer term. The only complete defence is to make its actions ineffective: fencing.
5 nodes, A is leader in term 4; the network splits {A, B} | {C, D, E}
1 t=0 A keeps sending heartbeats; only B receives them
2 t=0.3s C times out, becomes candidate in term 5, gets votes from D and E (3 of 5)
3 t=0.3s C is leader in term 5; A is still leader in term 4 on its side
4 t=0.3s+ a client connected to A sends a write; A cannot reach a majority, the write never commits
5 t=0.3s+ but if A also performs side effects (sends e-mails, writes to S3), they happen twice
6 t=heal A receives a message with term 5 and steps downReal scenario: a scheduler on both sides of a network partition sends the same reminder twice; two database primaries after an automated failover accept conflicting writes (failover tooling is in Replication & Failover); a Kubernetes controller paused by CPU throttling wakes up after its lease was taken; a VM live migration freezes a leader for 20 seconds.
What prevents it:
| Mechanism | Prevents two elected in one term | Stops a zombie from acting | Product |
|---|---|---|---|
| Majority vote per term | Yes | No (needs term checks) | Raft (etcd, Consul, CockroachDB), ZAB, KRaft |
| Lease with expiry | Yes, if clocks run at similar rates | No, the holder may be paused | Kubernetes Lease, etcd session, Consul session, Redis lock |
| CheckQuorum / step-down on deadline | Shortens the zombie window | Partly | etcd raft CheckQuorum, client-go RenewDeadline |
| Fencing token checked by storage | n/a | Yes | Kafka FENCED_LEADER_EPOCH, your epoch column |
| STONITH (power off the old node) | n/a | Yes, brutally | Pacemaker clusters |
Fix / how to use it: assume split brain will happen and design so that it is harmless: epochs on writes, idempotent side effects (API Idempotency), and quorum-checked state.
Terms and epochs: the logical clock of leadership Must-know
In plain words: every new leadership gets a bigger number, and everybody refuses orders that carry a smaller number than the biggest one they know.
Common misunderstanding: "A term is a time period, like a lease." A term is a counter, not a duration. Raft: "Terms act as a logical clock [14] in Raft, and they allow servers to detect obsolete information such as stale leaders."
Definition: a term (Raft), epoch (ZAB, Kafka "leader epoch", Kafka "controller epoch"), or generation is a monotonically increasing integer bumped at each election. Rules from the Raft paper: "if one server's current term is smaller than the other's, then it updates its current term to the larger value. If a candidate or leader discovers that its term is out of date, it immediately reverts to follower state. If a server receives a request with a stale term number, it rejects the request."
Raft term exchange
1 n1 (leader, term 3) -> n2: AppendEntries(term=3)
2 n2 (term 5, it voted in a newer election) -> n1: reject, term=5
3 n1 sets term=5, becomes follower
4 any request still in flight from n1 with term 3 is rejected everywhereReal scenario: Kafka's leader epoch is a "32 bit, monotonically increasing number representing a continuous period of leadership for a single partition. This is marked on all messages." (KIP-101); ZooKeeper's 64-bit zxid uses "the high order 32-bits for the epoch and the low order 32-bits for the counter"; a Kubernetes Lease's leaseTransitions counts "transitions of a lease between holders"; an etcd election's Rev() is the leader key's creation revision.
What provides it:
| Product | Name | Where it is checked |
|---|---|---|
| Raft (etcd, Consul, CockroachDB, TiKV) | Term | Every RPC |
| Kafka partitions | Leader epoch (stamped on records) | Brokers, followers, clients (FENCED_LEADER_EPOCH) |
| Kafka controller | Controller epoch (ZooKeeper mode) / KRaft leader epoch | Brokers (STALE_CONTROLLER_EPOCH, NOT_CONTROLLER) |
| ZooKeeper | zxid high 32 bits | Followers ACK NEW_LEADER from one server only |
| Kubernetes | spec.leaseTransitions | Nobody: you must check it in your storage |
| etcd election | Leader key create revision (Election.Rev()) | Your Txn Compare or your storage |
| Consul | LockIndex on the KV entry | Nobody: you must check it |
Fix / how to use it: read the epoch when you become leader, put it on every write, and store the highest accepted epoch next to the data.
Raft leader election Must-know
In plain words: everyone starts as a follower with a random alarm clock; whoever's alarm rings first asks the others for votes, and if a majority agrees it becomes leader and keeps everyone's alarms from ringing by sending heartbeats.
Common misunderstanding: "The node with the most data, or the lowest ID, is chosen." Raft chooses whoever times out first among nodes whose logs are at least as up to date as a majority's; the randomness, not the ID, breaks ties.
Definition (Raft section 5.2): a follower that receives no valid RPC for an election timeout "increments its current term and transitions to candidate state. It then votes for itself and issues RequestVote RPCs in parallel to each of the other servers in the cluster." A candidate wins "if it receives votes from a majority of the servers in the full cluster for the same term"; each server votes "for at most one candidate in a given term, on a first-come-first-served basis". Leaders send "periodic heartbeats (AppendEntries RPCs that carry no log entries)". Split votes are broken by randomized election timeouts "chosen randomly from a fixed interval (e.g., 150–300ms)". The election restriction (5.4.1) makes a voter refuse a candidate whose log is less up to date (compare the last entry's term, then the index), so a new leader always has every committed entry.
5 servers, timeouts random in 150-300 ms, heartbeat 50 ms (this chapter's simulator, seed 42)
1 t=195 n1 term=1 candidate timeout 268 ticks, RequestVote to all
2 t=200 n1 term=1 LEADER won with 3 of 5 votes
3 t=200+ n1 sends empty AppendEntries every 50 ms; followers reset their timers
4 t=400 network: partition [[1] [0 2 3 4]]
5 t=543 n0 term=2 candidate (its timer expired; it heard nothing from n1)
6 t=549 n0 term=2 LEADER won with 3 of 5 votes
7 t=1202 n1 term=1 step-down heartbeat from n0 in term 2 (after the partition heals)Real scenario: an etcd cluster behind a Kubernetes control plane re-elects within about one election timeout after the leader's VM dies; a CockroachDB range re-elects its Raft leader after a node drains; Consul servers elect a leader on cluster start; Kafka KRaft controllers elect the active controller.
What provides it:
| Product | Election timeout | Heartbeat | Notes |
|---|---|---|---|
| Raft paper | 150-300 ms recommended | Below the timeout | "Adding just 5ms of randomness helps significantly" (median downtime 287 ms) |
| etcd server | --election-timeout=1000 ms | --heartbeat-interval=100 ms | Timeout "at least 10 times the round-trip time"; maximum 50000 ms |
| etcd raft library | ElectionTick | HeartbeatTick | "We suggest ElectionTick = 10 * HeartbeatTick" |
| CockroachDB | Raft per range | Store-level liveness with leader leases | Followers "become candidates after randomized election timeouts" |
| Kafka KRaft | Raft dialect, pull-based | Fetch requests | Uses "offset/epoch" instead of "index/term" |
Fix / how to use it: do not implement Raft for an application role; use it through etcd, Consul or the Kubernetes API. Tune only the timeouts, from measured round-trip time. The simulator in Go shows the mechanics.
Pre-Vote and CheckQuorum Important
In plain words: before starting a real election, a node asks "would you vote for me?" without changing anything; and a leader that cannot hear a majority stops calling itself leader.
Common misunderstanding: "A node that was cut off and comes back is harmless." In plain Raft it has been incrementing its term at every timeout. When it reconnects, its high term forces the healthy leader to step down, and the cluster runs an unnecessary election.
Definition: Pre-Vote (Ongaro's thesis, section 9.6; etcd raft PreVote) adds a phase in which a would-be candidate asks for votes for term + 1 without incrementing its own term; voters grant only if they have not heard from a leader recently and the log is up to date. etcd describes it as preventing "disruption when a node that has been partitioned away rejoins the cluster". CheckQuorum (etcd raft CheckQuorum): "Leader steps down when quorum is not active for an electionTimeout." The Raft paper also has servers "disregard RequestVote RPCs when they believe a current leader exists".
Same partition as above, PreVote + CheckQuorum on (simulator, seed 42)
1 t=209 n1 term=1 LEADER won with 3 of 5 votes
2 t=409 partition [[1] [0 2 3 4]]
3 t=575 n4 term=2 LEADER won with 3 of 5 votes
4 t=658 n1 term=1 step-down check quorum: heard from 1 of 5
5 t=1209 healed; n1 never inflated its term, so no further election happensReal scenario: a flapping top-of-rack switch isolates one etcd member every few minutes; without Pre-Vote each reconnection deposes the leader and Kubernetes API writes stall; with Pre-Vote the isolated member's pre-votes are refused and the leader stays.
What provides it:
| Product | Pre-Vote | Leader step-down without quorum |
|---|---|---|
| etcd raft library | Config.PreVote | Config.CheckQuorum |
| etcd server | Pre-vote enabled in current releases (check --pre-vote for your version) | CheckQuorum used by the server |
| Kafka KRaft | Pre-vote added by KIP-996 (newer releases; verify for your version) | EndQuorumEpoch for graceful resign |
| This chapter's simulator | Config.PreVote | Config.CheckQuorum |
Fix / how to use it: keep both enabled where your product exposes them. CheckQuorum also shortens the zombie window from "until the partition heals" (650 ms in the simulator run above) to about one election timeout (83 ms in the run), which is shorter but still not zero.
Leader lease and lease-based reads Important
In plain words: a leader that recently heard from a majority assumes no one else can have been elected yet, and serves reads without asking again; that assumption depends on clocks.
Common misunderstanding: "The leader can always answer reads from memory, it has the latest data." A deposed leader that does not know it was deposed will serve stale reads. Raft: a leader "must check whether it has been deposed before processing a read-only request".
Definition: for linearizable reads Raft's leader either exchanges heartbeats with a majority first (etcd raft ReadOnlySafe, the ReadIndex approach) or relies on "the heartbeat mechanism to provide a form of lease [9], but this would rely on timing for safety (it assumes bounded clock skew)" (ReadOnlyLeaseBased, which "can be affected by clock drift" and requires CheckQuorum). CockroachDB's leaseholder is the one replica that "can serve reads or propose writes", and its Leader leases keep the lease co-located with Raft leadership.
Lease-based read, bounded clock drift assumed
1 t=0 leader L gets heartbeat acks from a majority
2 t=0-T L serves reads locally (lease of length T < election timeout)
3 t=T lease over: L must hear from a majority again before local reads
if L's clock runs slow, its T is longer than the followers' timeout: a new leader may exist, stale read possibleReal scenario: etcd serializable vs linearizable reads; CockroachDB reads served by the leaseholder without a Raft round trip; TiKV lease reads.
What provides it:
| Product | Read mode | Risk |
|---|---|---|
etcd raft ReadOnlySafe (default) | Quorum round trip per read batch | Extra latency |
etcd raft ReadOnlyLeaseBased | Local reads within the lease | Unbounded clock drift breaks linearizability |
| CockroachDB leaseholder | Local strongly consistent reads | Leader leases tie lease to Raft leadership and store liveness |
| etcd client serializable read | Any member, may be stale | Documented as not linearizable |
Fix / how to use it: for application leadership, never serve "I am leader, so this is the truth" reads from memory after a pause; re-check or read from the consensus store. Details of read modes belong to Consistency Models.
Paxos, Multi-Paxos and ZAB Good to know
In plain words: older relatives of Raft; they also need a majority, and they also end up with one distinguished proposer that acts as a leader.
Common misunderstanding: "Paxos has no leader, so it avoids the leader problem." Basic Paxos agrees on one value without a fixed leader, but a practical system that agrees on a sequence of values (Multi-Paxos) elects a distinguished proposer to avoid duelling proposers, and that proposer faces the same split-brain questions.
Definition: Paxos uses numbered proposals (ballots); a proposal with a higher number supersedes a lower one, which plays the same role as a term. Multi-Paxos skips the first phase while a stable leader keeps its ballot. ZAB (ZooKeeper Atomic Broadcast) elects a leader, which picks a new epoch: "the leader simply increments the zxid", and "Leadership activation will ensure that only one leader uses a given epoch". ZooKeeper's internals page answers "Isn't this just Paxos?" with "to us active messaging looks just like 2 phase commit without the need to handle aborts".
ZAB leader activation (ZooKeeper internals)
1 servers in LOOKING state elect the one that has seen the highest zxid
2 new leader takes epoch e of the highest zxid it has seen and starts at (e+1, 0)
3 leader syncs followers, proposes NEW_LEADER; followers ACK NEW_LEADER from a single server only
4 after a quorum ACKs, the leader activates and starts issuing proposals stamped (e+1, n)Real scenario: ZooKeeper ensembles behind older Kafka, HBase and Hadoop clusters; Google Chubby and Spanner (Paxos); Kafka KRaft "beginning with Kafka log replication and adding Raft leader election" (KIP-595).
What provides it:
| Protocol | Ordering number | Leader | Products |
|---|---|---|---|
| Paxos / Multi-Paxos | Ballot / proposal number | Distinguished proposer | Chubby, Spanner |
| ZAB | Epoch in zxid | ZooKeeper leader | Apache ZooKeeper |
| Raft | Term | Raft leader | etcd, Consul, CockroachDB, TiKV |
| KRaft | Leader epoch | Active controller | Apache Kafka |
Fix / how to use it: you rarely choose between them for an application; you choose a product. Consensus internals are taught in Distributed SQL, Consensus & 2PC.
Leases on a coordination store: TTL, renew, holder identity Must-know
In plain words: instead of voting, candidates race to write "held by me until T" into a store that is itself replicated with consensus; the winner must keep re-writing it before T.
Common misunderstanding: "The lease expiry timestamp in the store tells me when I may take over." Comparing someone else's timestamp with your clock makes you depend on clock offset. client-go does not do that: it "only acts on timestamps captured locally" and treats the remote timestamps only as a sign that the record changed.
Definition: a lease is a record with a holder identity, a duration (TTL), and acquire/renew times, written with compare-and-swap. The holder renews periodically. A candidate may take over only when the record has not changed for a full lease duration as measured by its own clock. Every change of holder increments a transition counter that doubles as an epoch.
client-go defaults: LeaseDuration 15 s, RenewDeadline 10 s, RetryPeriod 2 s
1 t=0 A: create Lease {holderIdentity: A, leaseDurationSeconds: 15, leaseTransitions: 0}
2 t=2 A: update renewTime (CAS on resourceVersion succeeds) B: observes change, timer restarts
3 t=4 A: partitioned from the API server; renew fails
4 t=12 A: has not renewed for RenewDeadline (10 s since t=2): stops leading, exits
5 t=17 B: record unchanged for 15 s on B's clock: CAS {holderIdentity: B, leaseTransitions: 1}Real scenario: every Kubernetes operator built with controller-runtime; Patroni's leader key in etcd/Consul; HashiCorp Vault HA standby; a Go service using etcd concurrency.Election.
What provides it:
| Store | Lease object | Renewal | Expiry decided by |
|---|---|---|---|
| Kubernetes API | coordination.k8s.io/v1 Lease | Update renewTime with resourceVersion CAS | Candidates' local clocks |
| etcd | Lease attached to the leader key | Keepalive stream (session) | etcd server (TTL) |
| ZooKeeper | Ephemeral znode tied to a session | Session heartbeats | ZooKeeper (session timeout) |
| Consul | Session (optional TTL, node/service checks) | PUT /v1/session/renew | Consul servers |
| PostgreSQL row | Your leader_leases row | UPDATE ... expires_at | Database now() |
| Redis | SET NX PX key | Owner-checked PEXPIRE script | Redis server clock |
Fix / how to use it: pick the store you already depend on, keep the TTL well above GC and network pauses you measure, and add fencing. Code: lease.go.
Kubernetes Lease and client-go leaderelection Must-know
In plain words: Kubernetes has a built-in object for "who holds this role", and client-go has a ready-made loop that acquires it, renews it and calls your function while you lead.
Common misunderstanding: "client-go's leader election makes my controller exactly-once." Its own documentation says it does not guarantee that only one client acts as leader; it is tolerant to clock offset but "not tolerant to arbitrary clock skew rate".
Definition: the Lease spec has holderIdentity, leaseDurationSeconds ("a duration that candidates for a lease need to wait to force acquire it. This is measured against the time of last observed renewTime"), acquireTime, renewTime, leaseTransitions, and for the alpha Coordinated Leader Election feature strategy and preferredHolder (with LeaseCandidate objects). leaderelection.LeaderElectionConfig has Lock, LeaseDuration ("Core clients default this value to 15 seconds"), RenewDeadline (10 s, "the duration that the acting master will retry refreshing leadership before giving up"), RetryPeriod (2 s), Callbacks (OnStartedLeading, OnStoppedLeading, OnNewLeader), ReleaseOnCancel, WatchDog and Name. RunOrDie "blocks until leader election loop is stopped by ctx or it has stopped holding the leader lease". Validation rejects configurations where "leaseDuration must be greater than renewDeadline" or "renewDeadline must be greater than retryPeriod*JitterFactor" (JitterFactor = 1.2).
kube-controller-manager pair (HA control plane)
1 kcm-1 acquires Lease kube-system/kube-controller-manager, starts controllers
2 kcm-2 runs RunOrDie, OnNewLeader("kcm-1"), waits
3 kcm-1's node loses its network; renewals fail for 10 s; OnStoppedLeading, process exits
4 kcm-2 sees no renewTime change for 15 s, updates holderIdentity, leaseTransitions+1
5 kcm-2: OnStartedLeading(ctx) starts the controllersReal scenario: cluster operators (cert-manager, database operators) run two or three replicas with one active; the kubelet's node heartbeats are also Lease updates in kube-node-lease ("every kubelet heartbeat is an update request to this Lease object, updating the spec.renewTime field"); API server identity leases.
What provides it:
| Component | Lease | Note |
|---|---|---|
kube-controller-manager, kube-scheduler | kube-system Leases | Flags --leader-elect, --leader-elect-lease-duration, --leader-elect-renew-deadline, --leader-elect-retry-period |
| kubelet | One Lease per Node in kube-node-lease | Node heartbeat, not election |
| kube-apiserver | Identity Leases (leaseDurationSeconds: 3600 in the docs example) | Garbage collected after 1 hour |
| controller-runtime managers | LeaderElection: true, LeaderElectionID | Uses client-go underneath |
| Coordinated Leader Election (alpha) | LeaseCandidate + strategy | CoordinatedLeaderElection feature gate |
Fix / how to use it: use resourcelock.LeaseLock, a unique identity per process (Pod name plus a random suffix), exit the process in OnStoppedLeading, set ReleaseOnCancel: true only if your work stops before the context is cancelled ("or you may have two processes simultaneously acting on the critical path"), and fence with leaseTransitions. Code: kubelease.go.
etcd election, ZooKeeper ephemeral nodes, Consul sessions Important
In plain words: the three classic coordination stores each have a recipe: etcd has an election API, ZooKeeper has ephemeral sequential nodes, Consul has sessions and KV locks.
Common misunderstanding: "If the store is linearizable, the lock it gives me is safe." Jepsen's etcd 3.4.3 analysis found key-value operations "appear to be strict serializable" but "etcd locks are fundamentally unsafe": a lease can expire while the client still thinks it holds the lock. The same is true of any lease-based recipe without fencing.
Definition:
- etcd
concurrency.NewSession(cli, concurrency.WithTTL(ttl))(default TTL 60 s) andconcurrency.NewElection(session, prefix).Campaign(ctx, val)"puts a value as eligible for the election on the prefix key"; "only one can be the leader at a time".Proclaimupdates the value,Resign"lets a leader start a new election",Observestreams leader changes,Rev()is "the leader key's creation revision". Errors:election: not leader,election: no leader. The gRPCv3electionservice exposes the same (Campaign,Proclaim,Leader,Observe,Resign); itsLeaderKeycan "transactionally guard API requests on leadership still being held". - ZooKeeper recipe: create
/election/guid-n_withSEQUENCE|EPHEMERAL; "The process that created the znode with the smallest appended sequence number is the leader"; each process watches only its predecessor "to avoid the herd effect". The ephemeral node disappears when the session expires. - Consul: create a session,
PUT /v1/kv/service/leader?acquire=<session>returnstrueorfalse; the holder renews the session; others watch with blocking queries. Sessions haveTTL,Behavior(releaseby default) andLockDelay(15 s by default). Consul warns: "this locking system has no enforcement mechanism that requires clients to acquire a lock before they perform an operation."
ZooKeeper ephemeral sequential recipe
1 A creates /election/guid-n_0000000007, B creates ..._0000000008, C ..._0000000009
2 A has the smallest: A leads; B watches 7, C watches 8 (no herd)
3 A's session expires; ZooKeeper deletes ..._7; only B is notified
4 B lists children, sees it is now the smallest: B leads
5 C keeps watching 8Real scenario: Patroni keeps the PostgreSQL leader key in etcd, Consul or ZooKeeper; HBase masters and older Kafka controllers used ZooKeeper; Vault and Nomad HA use their own Raft or Consul; Go services use etcd's concurrency package.
What provides it:
| Store | Acquire | Lose | Fencing value |
|---|---|---|---|
| etcd | Campaign (blocks) | Session lease expires / Resign | Election.Rev(); Txn Compare(CreateRevision(key), "=", rev) |
| ZooKeeper | Smallest ephemeral sequential znode | Session expiry | zxid or znode version (Kleppmann: "you can use the zxid or the znode version number as fencing token") |
| Consul | ?acquire=<session> returns true | Session invalidated or TTL not renewed | LockIndex on the KV entry |
| Kubernetes | Lease update with CAS | RenewDeadline passed | leaseTransitions |
Fix / how to use it: use the official recipe through its client library, handle session loss as "stop all leader work now", and fence. Code: etcdelect.go.
Database-based election: advisory locks, lease rows, SKIP LOCKED Must-know
In plain words: if every replica already talks to the same PostgreSQL or MySQL, a row (or a lock inside the database) can say who leads.
Common misunderstanding: "A session advisory lock is a perfect leader lock: it is released automatically when the leader dies." It is released when the database session ends, which can be long after the application froze, and it is lost silently behind a transaction-pooling proxy. It also has no epoch.
Definition: three patterns.
- Advisory lock:
SELECT pg_try_advisory_lock(42)on a dedicated connection. PostgreSQL: "Once acquired at session level, an advisory lock is held until explicitly released or the session ends." MySQL'sGET_LOCK('name', 0)is similar. - Lease row: one row per role with
holder,epochandexpires_at, acquired and renewed by one conditional statement using the database clock. - Per-shard claims: rows for each shard claimed with
FOR UPDATE SKIP LOCKEDso many workers each become leader of a different shard without waiting; PostgreSQL: "With SKIP LOCKED, any selected rows that cannot be immediately locked are skipped".
-- Acquire or renew in one statement; epoch increments only on takeover
INSERT INTO leader_leases AS l (name, holder, epoch, expires_at, renewed_at)
VALUES ('billing', 'web-3:8f2c', 1, now() + interval '15 seconds', now())
ON CONFLICT (name) DO UPDATE
SET holder = EXCLUDED.holder,
epoch = CASE WHEN l.holder = EXCLUDED.holder AND l.expires_at > now()
THEN l.epoch ELSE l.epoch + 1 END,
expires_at = EXCLUDED.expires_at,
renewed_at = now()
WHERE l.holder = EXCLUDED.holder OR l.holder IS NULL OR l.expires_at <= now()
RETURNING epoch; -- no row returned: someone else leads Two app servers, lease row with TTL 15 s (database clock)
1 10:00:00 web-1: upsert -> epoch 8 returned web-2: upsert -> 0 rows (held)
2 10:00:05 web-1: renew -> epoch 8 web-2: 0 rows
3 10:00:07 web-1 freezes (VM migration)
4 10:00:20 web-1's expires_at passes
5 10:00:21 web-2: upsert -> epoch 9
6 10:00:30 web-1 wakes, writes with epoch 8 -> fenced UPDATE affects 0 rowsReal scenario: a Laravel or Go monolith on three VMs with one PostgreSQL that needs one billing worker; Quartz and similar schedulers use a locks table; queue workers claiming tenants or shards with SKIP LOCKED.
What provides it:
| Product | Primitive | Released on | Note |
|---|---|---|---|
| PostgreSQL | pg_try_advisory_lock / pg_advisory_unlock | Session end or unlock | Visible in pg_locks; breaks with PgBouncer transaction pooling |
| PostgreSQL | pg_try_advisory_xact_lock | Transaction end | Short critical sections only |
| PostgreSQL / MySQL 8 | FOR UPDATE SKIP LOCKED | Transaction end | Per-shard claims, job queues |
| MySQL | GET_LOCK(name, timeout) / RELEASE_LOCK | Session end | Named lock per connection |
| Any SQL | Lease row with expires_at and epoch | Expiry by now() | Portable, fencing built in |
Fix / how to use it: prefer the lease row (it has an epoch and uses one clock); keep writes to the same database inside a transaction that re-checks the lease row FOR SHARE. Code: pglease.go. Lock modes are covered in Locks & Concurrency Control.
Redis-based election Important
In plain words: SET role:leader my-id NX PX 15000 makes you leader if nobody is; you keep it by extending the key while you work.
Common misunderstanding: "Redis is fast and we already have it, so it is the best leader lock." It is the weakest of the options: Redis replication is asynchronous, so a failover can lose the key and hand leadership to a second node, and the key value has no order, so it is not a fencing token. The Redis docs say a replica-based setup cannot implement mutual exclusion: "Client B acquires the lock to the same resource A already holds a lock for. SAFETY VIOLATION!"
Definition: acquire with SET key owner NX PX ttl; renew and release with Lua scripts that check the owner first (Laravel's RedisLock::refresh() and release() do this). Redlock is a multi-instance variant discussed in Distributed Locking together with Kleppmann's critique.
Redis primary + replica, leader lock with TTL 15 s
1 A: SET leader A NX PX 15000 on primary -> OK
2 primary crashes before replicating the key
3 replica promoted; the key does not exist there
4 B: SET leader B NX PX 15000 -> OK: two leaders until A's next renew failsReal scenario: Laravel's onOneServer and withoutOverlapping on the redis cache store; Sidekiq Enterprise-style "leader" processes; homegrown cron dedup.
What provides it:
| Feature | Product | Gives you | Missing |
|---|---|---|---|
SET NX PX + owner-checked Lua | Redis, Valkey | Lease with TTL and owner | Order, durability across failover |
Cache::lock()->get(), refresh(), release() | Laravel 13 | The same, from PHP | Epoch |
| Redlock | redis.io pattern | Majority of independent Redis instances | Fencing token (Kleppmann) |
WAIT numreplicas timeout | Redis | Fewer lost writes on failover | Not a consensus guarantee |
Fix / how to use it: acceptable for "it is fine if this rarely runs twice" (cache warmers, reports with idempotent output); for anything that writes money or state, add an epoch from your database and fence. Code: LeaderLease.php.
Fencing the leader's writes Must-know
In plain words: the storage keeps the highest leader number it has seen and refuses any write that comes with a smaller one.
Common misunderstanding: "Fencing is the leader checking that it is still the leader." That is a check in the wrong place. The leader can be paused right after the check. Fencing is the resource checking the token, atomically with the write.
Definition: a fencing token is a number that "increases (e.g. incremented by the lock service) every time a client acquires the lock" (Kleppmann). Every write carries it; "the storage server remembers that it has already processed a write with a higher token number (34), and so it rejects the request with token 33." In consensus systems the term or epoch is the token and the replicas check it; in application systems you must add the check to your own storage.
Fenced writes (this chapter's TestZombieLeaderIsFenced)
1 pod-a acquires the lease: epoch 1; writes invoice-run=started (epoch 1) -> accept, highest=1
2 pod-a stops for 40 s (stop-the-world)
3 pod-b acquires after LeaseDuration: epoch 2; writes invoice-run=taken over (epoch 2) -> accept, highest=2
4 pod-a wakes, IsLeader() still true in its memory; writes (epoch 1) -> reject: stale epoch
5 pod-a's next Step sees holder pod-b and calls OnStoppedLeadingReal scenario: Kafka followers and clients reject requests with an old leader epoch (FENCED_LEADER_EPOCH, code 74); brokers reject requests from an old controller (STALE_CONTROLLER_EPOCH, code 11); HDFS NameNode HA fences the old active; a billing cursor in PostgreSQL with a fence_epoch column; object storage writes using conditional requests on a generation number.
What provides it:
| Resource | How to check the token | Atomic? |
|---|---|---|
| PostgreSQL / MySQL row | UPDATE ... SET fence_epoch = $e WHERE id = $id AND fence_epoch <= $e | Yes, one statement |
| Same database as the lease | Transaction: SELECT ... FROM leader_leases WHERE epoch = $e AND expires_at > now() FOR SHARE, then write | Yes, the row lock blocks takeover |
| etcd | Txn().If(Compare(CreateRevision(leaderKey), "=", rev)).Then(Put(...)) | Yes |
| Kafka | Leader epoch on produce/fetch | Yes, broker-side |
| ZooKeeper | setData(path, data, expectedVersion) | Yes, version check |
| External HTTP API | Pass the epoch; the API must store and compare it | Only if the API supports it; otherwise use idempotency keys |
| Files / object storage | Conditional writes on a generation/ETag | Yes where supported |
Fix / how to use it: derive the token from the election (term, leaseTransitions, Rev(), a database epoch), never from the leader's clock; accept an equal epoch (the same leader writes many times) or a higher one, and reject a lower one. Code: fencing.go, FencedInvoiceRuns.php.
Failover timing: detection time, lease length, false positives Must-know
In plain words: you cannot tell a dead leader from a slow one, so you wait; waiting longer means fewer false alarms and longer outages.
Common misunderstanding: "Failover time is the lease duration." It is detection plus election plus the new leader's warm-up: with client-go defaults a crashed leader is replaced after about 15 s plus up to one jittered retry period, and then the new leader may need to load state before doing useful work.
Definition: detection time is how long until a standby decides the leader is gone (election timeout or lease duration). A false positive is an election when the leader was alive but slow (GC pause, disk stall, saturated network). The safety margin is the time between the old leader stopping on its own (RenewDeadline, CheckQuorum) and the earliest moment another node can start (LeaseDuration). The tolerated clock-rate difference is about LeaseDuration / RenewDeadline: client-go's example sets 60 s and 30 s "to tolerate some nodes progressing forward in time twice as fast as other nodes".
Arithmetic with client-go defaults (15 s / 10 s / 2 s)
1 crash of the leader -> standby acquires at 15 s + up to 2 x 1.2 = 2.4 s jitter: 15-17.4 s
2 partition of the leader -> old leader stops at <= 10 s; new one starts at >= 15 s: 5 s with nobody
3 graceful release -> standby acquires on its next retry: about 2-4.4 s
4 clock-rate tolerance -> 15 / 10 = 1.5x; this chapter's test shows overlap at 2x and none at 1.9x with 60/30
5 false positive budget -> any API-server or GC stall longer than 10 s on the leader causes a leader changeReal scenario: a 12-second full GC in a JVM controller with a 10-second RenewDeadline causes a leader change every time it happens; an etcd cluster stretched across regions with the default 1000 ms election timeout flaps when cross-region RTT spikes; Raft's paper measured that "In the absence of randomness, leader election consistently took longer than 10 seconds" due to split votes.
What provides it:
| Mechanism | Detection | False-positive trigger | Knob |
|---|---|---|---|
| Raft election | Election timeout | Heartbeats delayed beyond timeout | --election-timeout, --heartbeat-interval |
| client-go Lease | LeaseDuration | API-server latency, leader CPU starvation | LeaseDuration, RenewDeadline, RetryPeriod |
| etcd session | Session TTL | Keepalive delays | WithTTL |
| ZooKeeper session | Session timeout | GC pause longer than the timeout | Negotiated within minSessionTimeout/maxSessionTimeout |
| Consul session | TTL or health checks | Failing check on a busy node | TTL, LockDelay, checks |
| Kafka ISR | replica.lag.time.max.ms | Slow follower dropped from ISR | Broker config |
Fix / how to use it: measure p99.9 pause and round-trip times, then set the timeout an order of magnitude above them; make RenewDeadline comfortably shorter than LeaseDuration; alert on leader-change rate, not on single changes. Retry policies belong to Timeouts, Retries & Jitter.
Graceful step-down, hand-off and hot standby Important
In plain words: when you know the leader is going away (deploy, drain), let it finish, give up the role on purpose, and have a warm replacement ready.
Common misunderstanding: "On SIGTERM just release the lock." Releasing while work is still running creates two leaders on purpose. client-go warns that with ReleaseOnCancel "you must ensure all code guarded by this lease has successfully completed prior to cancelling the context".
Definition: step-down is a leader voluntarily ceasing to lead: stop accepting work, finish or abandon the current unit, persist progress, then release (client-go ReleaseOnCancel, etcd Resign, Consul ?release=, Laravel $lock->release(), Kafka KRaft EndQuorumEpoch "used by a leader to gracefully step down", Raft's leadership transfer extension). A hot standby has the code loaded, connections open and state cached so that it can start immediately when it wins; a cold standby starts from scratch.
Rolling deploy of a singleton worker
1 SIGTERM to leader L (epoch 12)
2 L stops taking new batches; current batch commits (fenced with 12)
3 L releases: holder cleared (client-go writes leaseDurationSeconds: 1)
4 standby S retries within RetryPeriod, acquires epoch 13, starts from the stored cursor
5 L exits; downtime about one retry period instead of a full leaseReal scenario: Kubernetes rolling updates of operators; kube-controller-manager lock release on exit ("actively releases its leader election lock during leader transitions, rather than waiting for the lock's TTL to expire"); Kafka controlled shutdown moving partition leadership away first; Laravel deploys sending SIGTERM to Supervisor-managed workers.
What provides it:
| Product | Graceful release | Standby warmth |
|---|---|---|
| client-go | ReleaseOnCancel: true | Standby Pods run informers already |
| etcd | Election.Resign(ctx) | Campaigners block in Campaign |
| Consul | PUT /v1/kv/<key>?release=<session> | Watchers via blocking queries |
| Kafka | Controlled shutdown, EndQuorumEpoch | Hot standby controllers |
| Laravel command | $this->trap(SIGTERM, ...) then $lock->release() | Other servers loop on tryAcquire() |
Fix / how to use it: stop work, persist, release, exit, in that order; make the standby able to resume from persisted state, so a hand-off loses nothing.
Per-shard leaders: Kafka partitions, Raft groups Must-know
In plain words: instead of one leader for everything, split the data into many shards and give each shard its own leader, spread across machines.
Common misunderstanding: "A single leader is a scalability limit, so leader-based systems do not scale." They scale by having thousands of leaders: each Kafka partition has its own leader, each CockroachDB range and TiKV Region is its own Raft group.
Definition: multi-leader partitioning (not multi-leader replication) assigns a leader per shard. Kafka: each partition has a leader broker and an ISR; the controller assigns leaders and bumps the leader epoch. CockroachDB: "Raft organizes all nodes that contain a replica of a range into a group—unsurprisingly called a Raft group", and the leaseholder serves the range. TiKV: each Region (a key range) is a Raft group with three replicas by default, scheduled by the Placement Driver (PD).
Kafka topic orders, 6 partitions, 3 brokers, replication factor 3
1 p0 leader b1 (epoch 4), p1 leader b2 (epoch 2), p2 leader b3 (epoch 7), ...
2 b2 dies; controller elects new leaders for p1 and p4 from their ISRs, epochs +1
3 producers get NOT_LEADER_OR_FOLLOWER, refresh metadata, retry on the new leaders
4 p0, p2, p3, p5 never noticed: only b2's partitions failed overReal scenario: Kafka partition leadership; CockroachDB ranges (leaseholder rebalancing across nodes); TiKV Regions; your own system where each tenant or shard has an owner claimed with SKIP LOCKED rows (see Sharding at System Level).
What provides it:
| Product | Unit | Leader | Who assigns | Epoch |
|---|---|---|---|---|
| Kafka | Partition | Partition leader broker | Active controller | Leader epoch |
| CockroachDB | Range | Raft leader = leaseholder (Leader leases) | Raft per range | Raft term, lease sequence |
| TiKV | Region | Raft leader | Raft per Region; PD balances | Raft term, Region epoch |
| Your app | Shard row | Worker that claimed it | FOR UPDATE SKIP LOCKED | shard_owners.epoch |
Fix / how to use it: when one leader becomes a bottleneck, shard the role; keep each shard's leadership and fencing independent; watch for hot shards. Partitioning mechanics are in Sharding at System Level and Kafka in Depth.
Classic algorithms: bully and ring Good to know
In plain words: textbook algorithms where the node with the highest ID wins after a round of messages; neat on a whiteboard, unsafe on a real network.
Common misunderstanding: "Bully is a simple alternative to Raft." It assumes a reliable failure detector (a timeout that really means "dead") and no partitions; under a partition each side elects its own highest ID, which is split brain by design.
Definition: bully: a process that notices the coordinator is gone sends Election to all higher IDs; if none answers it sends Coordinator (Victory) to all; a higher process that receives Election replies Answer (Alive) and starts its own election. Ring (Chang and Roberts): an election message travels around a logical ring collecting or comparing IDs; the highest ID is announced in a second pass.
Bully with processes 1..5, coordinator 5 crashes
1 2 notices: Election -> 3, 4, 5
2 3 and 4 answer Alive; 3 and 4 start their own elections
3 4: Election -> 5 (no answer)
4 4: Coordinator(4) -> 1, 2, 3
5 partition {1,2} | {3,4}: side {1,2} elects 2, side {3,4} keeps 4: two coordinatorsReal scenario: university courses and interview questions; some old LAN cluster software; Elasticsearch's pre-7 Zen discovery used a bully-like rule with minimum_master_nodes added to avoid split brain (inference from Elastic's public history, not verified here).
What provides it:
| Algorithm | Messages per election | Partition safety | Used at scale |
|---|---|---|---|
| Bully | O(n²) worst case | None | No |
| Ring | O(n) to O(n²) | None | No |
| Raft / ZAB / Paxos | O(n) per round | Majority quorum | Yes |
Fix / how to use it: know them for interviews and history; in production use a quorum-based store.
Observability: leader changes, term, lease age Important
In plain words: you should be able to answer at any moment "who leads, since when, in which epoch, and how often did that change today?"
Common misunderstanding: "Alert when the leader changes." A single change after a deploy is normal; alert on the rate of changes and on "no leader for longer than X".
Definition: the minimum set: current leader identity, current term or epoch, leader changes per hour, time since last successful renew on the leader, time with no leader, number of rejected (fenced) writes. etcd exposes etcd_server_has_leader, etcd_server_leader_changes_seen_total and etcd_server_proposals_failed_total; client-go exposes a leader election metric (LeaderMetric in the package) and a HealthzAdaptor whose check "fails (returns an error) if we own the lease but had not been able to renew it". Logs: client-go prints "successfully acquired lease" and "failed to renew lease".
A useful log line per transition
1 level=INFO msg="leader elected" role=billing holder=web-3:8f2c epoch=9 previous=web-1:11aa
2 level=WARN msg="leader stepped down" role=billing epoch=9 reason="renew deadline exceeded"
3 level=WARN msg="fenced write rejected" role=billing epoch=8 highest=9 resource=invoice_runs/2026-11Real scenario: a dashboard panel "leader changes in the last 24 h" for etcd, Kafka controller and each operator; an alert on etcd_server_has_leader == 0 for 1 minute; a fenced-write counter that should stay at zero except during incidents.
What provides it:
| Product | Leader signal | Change signal |
|---|---|---|
| etcd | etcd_server_has_leader | etcd_server_leader_changes_seen_total, etcd_server_proposals_failed_total |
| Kafka KRaft | Active controller metric (ActiveControllerCount) | Leader election rate metrics |
| Kubernetes | kubectl get lease -n kube-system (holder, age) | Events "became leader" / leaseTransitions |
| Consul | consul operator raft list-peers | Leadership change telemetry |
| Your app | Log lines + gauge leader_epoch | Counter leader_changes_total, fenced_writes_total |
Fix / how to use it: export epoch and identity as labels or log fields; correlate leader changes with GC and network metrics. The general stack is in Observability and alert design in Alerting That Actually Works.
Testing with partitions: Jepsen style Must-know
In plain words: you only know your election is safe after you have cut networks, paused processes and skewed clocks on purpose and checked that the invariant still holds.
Common misunderstanding: "Unit tests with mocks cover it." Mocked tests cover the happy path; the bugs are in timing, partitions and pauses. Jepsen exists because vendors' claims often fail under exactly these faults.
Definition: a partition test runs the real or simulated system, injects faults (network partitions isolating single nodes, majority/minority splits, process pauses, crashes, clock skew) while clients run operations, records a history, and checks invariants (at most one leader per term; no write from a stale epoch is accepted; no lost acknowledged write). Jepsen "aims to improve the safety of distributed databases, queues, consensus systems"; its etcd test introduced "network partitions isolating single nodes, separating the cluster into majority and minority components, and non-transitive partitions", crashes, pauses and clock skew.
This chapter's chaos test (TestElectionSafetyUnderChaos)
1 for seed in 0..149: 5 nodes, PreVote/CheckQuorum varied by seed
2 40 random steps: partition(random cut) | heal | crash(random) | restart(random)
3 leaders propose entries; run 50-450 ticks
4 check: ElectionSafetyViolations() is empty (never two leaders in one term)Real scenario: Jepsen analyses of etcd, Consul, ZooKeeper-based systems, Kafka, Redis-Raft; CI tests with fake clocks for lease logic (this chapter's lease_test.go); game days with tc netem and iptables drops (Chaos Engineering).
What provides it:
| Tool | Level | Faults |
|---|---|---|
| Jepsen (Clojure) | Real clusters | Partitions, pauses, crashes, clock skew, membership changes |
Deterministic simulation (this chapter's raftsim, FoundationDB-style) | In process | Any, reproducible by seed |
Fake clocks (lease_test.go, Laravel travel) | Unit | Time jumps, clock rate differences |
tc netem, iptables, Toxiproxy | Staging | Latency, loss, partitions |
| Chaos Mesh / Litmus (Kubernetes) | Staging/production | Pod kill, network chaos, time chaos |
Fix / how to use it: encode the invariants as assertions, run many seeds in CI, and repeat the destructive tests in staging before trusting a new election setup.
Laravel patterns: onOneServer, Horizon, singleton workers Must-know
In plain words: Laravel gives you per-run deduplication for scheduled tasks; for a continuously running singleton you build a small lease loop yourself.
Common misunderstanding: "onOneServer() elects a scheduler leader." It does not elect anybody. Every server's cron still runs schedule:run; for each due task the first server to take a cache lock for that task and that minute runs it. The framework's CacheSchedulingMutex builds the lock name from $event->mutexName().$time->format('Hi') with a 3600-second expiry.
Definition: onOneServer() requires "the database, memcached, dynamodb, or redis cache driver as your application's default cache driver" and "all servers must be communicating with the same central cache server"; "The first server to obtain the task will secure an atomic lock on the job". Schedule::alwaysOnOneServer() applies it to all tasks; "Scheduled closures without a name are excluded and will continue to run on every server". withoutOverlapping() prevents a task from overlapping its own previous run. Horizon's master supervisor is one per machine: MasterSupervisor::name() is the slugged hostname plus a random token, and ensureNoOtherMasterSupervisors() throws "A master supervisor is already running on this machine." Coordination between machines happens through the Redis queues, not through an election. Cache::lock($name, $seconds) gives get(), block(), owner(), refresh() (owner-checked on the Redis and database drivers), release(), forceRelease() and Cache::restoreLock($name, $owner).
Three servers, cron every minute, report:generate ->onOneServer()
1 17:00:00.120 web-1 schedule:run: lock "framework/schedule-<hash>1700" -> acquired, runs the report
2 17:00:00.180 web-2 schedule:run: same lock -> taken, skips
3 17:00:00.240 web-3 schedule:run: same lock -> taken, skips
4 17:00 next Friday: whoever's cron fires first wins; there is no "leader server"Real scenario: weekly reports, daily cleanup and sitemap generation with onOneServer; a billing worker or a WebSocket fan-out process that must run continuously on exactly one server (singleton worker with a lease); Horizon on each queue server.
What provides it:
| Need | Laravel 13 tool | Guarantee | Gap |
|---|---|---|---|
| Scheduled task once per run | ->onOneServer() + Schedule::useCache('redis') | One server per run, if the cache is shared | Redis failover can duplicate; no fencing |
| No overlap with the previous run | ->withoutOverlapping() | Lock until the run ends (expires after 24 h by default per expiresAt) | Per task, not per server |
| Same job with different parameters | ->name('check_uptime:example.com') | Separate locks per name | You must name them |
| Continuous singleton worker | Command + Cache::lock + refresh() + epoch | One holder per lock TTL | Needs fencing for safety |
| Queue processing | Horizon master supervisor per machine | One Horizon per host | Not a cluster leader |
| Unique jobs | ShouldBeUnique | One queued copy per key | Not leadership; see Laravel Queue Internals |
Fix / how to use it: onOneServer for scheduled tasks with idempotent effects; a lease loop with epoch fencing for continuous work. Code: Laravel.
Mechanics
What each knob does, in one place
| Knob | Product | Default (source) | Rule |
|---|---|---|---|
| Election timeout | Raft | 150-300 ms recommended (paper) | broadcastTime ≪ electionTimeout ≪ MTBF |
--election-timeout | etcd server | 1000 ms (tuning docs) | At least 10 x RTT; upper limit 50000 ms |
--heartbeat-interval | etcd server | 100 ms | About 0.5-1.5 x RTT |
ElectionTick / HeartbeatTick | etcd raft library | Suggest 10:1 | ElectionTick must be greater than HeartbeatTick |
PreVote, CheckQuorum | etcd raft library | Off in the library struct (enable them) | CheckQuorum required for ReadOnlyLeaseBased |
LeaseDuration | client-go | 15 s | Greater than RenewDeadline |
RenewDeadline | client-go | 10 s | Greater than RetryPeriod x 1.2 |
RetryPeriod | client-go | 2 s | Jittered by JitterFactor = 1.2 while acquiring |
ReleaseOnCancel | client-go | false | True only if guarded work has stopped |
WithTTL | etcd concurrency session | 60 s ("If TTL is <= 0, the default 60 seconds TTL will be used") | Above the longest pause |
tickTime, minSessionTimeout, maxSessionTimeout | ZooKeeper | tickTime=2000 (sample), 2x and 20x tickTime | Session timeout negotiated in range |
TTL, LockDelay, Behavior | Consul session | No TTL, 15 s, release | TTL makes sessions expire if not renewed |
unclean.leader.election.enable | Kafka | Disabled (since 0.11.0.0) | Enabling trades consistency for availability |
replica.lag.time.max.ms | Kafka | Broker config | Slow followers leave the ISR |
| Lock seconds | Laravel Cache::lock | Caller-defined; scheduler per-run lock 3600 s | Above the longest batch, renewed with refresh() |
Failover arithmetic
| Scenario | Formula | client-go defaults | Raft (etcd defaults) |
|---|---|---|---|
| Crash detection + takeover | LeaseDuration + jitter(RetryPeriod) | 15-17.4 s | About 1-2 x election timeout: 1-2 s |
| Partition: time with no leader | LeaseDuration - RenewDeadline (minimum) | 5 s | About one election timeout |
| Graceful hand-off | About one RetryPeriod | 2-4.4 s | Leadership transfer: about one RTT plus catch-up |
| Tolerated clock-rate ratio | LeaseDuration / RenewDeadline | 1.5 | n/a (terms do not depend on clock rate; lease reads do) |
| Leader changes caused by a pause of P | Leader change if P > RenewDeadline | P > 10 s | P > election timeout |
Error names and messages you will see
| Product | Error / message | Meaning | What to do |
|---|---|---|---|
| Kafka | NOT_LEADER_OR_FOLLOWER (6) | Request reached a broker that is not the leader | Refresh metadata, retry |
| Kafka | STALE_CONTROLLER_EPOCH (11) | "The controller moved to another broker." | Ignore the old controller's request |
| Kafka | NOT_CONTROLLER (41) | "This is not the correct controller for this cluster." | Find the active controller |
| Kafka | FENCED_LEADER_EPOCH (74) | "The leader epoch in the request is older than the epoch on the broker." | Refresh leader and epoch |
| Kafka | UNKNOWN_LEADER_EPOCH (75) | "The leader epoch in the request is newer than the epoch on the broker." | Retry after metadata propagates |
| etcd | election: not leader | Proclaim/Resign called without leadership | Campaign again |
| etcd | election: no leader | Leader() found no leader | Wait or campaign |
| client-go | leaseDuration must be greater than renewDeadline | Invalid config | Fix knobs |
| client-go | failed to renew lease <ns>/<name>: ... | Renewal gave up after RenewDeadline | Process should exit |
| Consul CLI | Error! Did not acquire lock | Another session holds the key | Watch and retry |
| Laravel | Illuminate\Contracts\Cache\LockTimeoutException | block() waited too long | Treat as "not leader" |
| Horizon | A master supervisor is already running on this machine. | Second horizon on the same host | Use one per host |
| This chapter | fencing: stale epoch: got 1, highest 2 / StaleEpochException | Deposed leader tried to write | Step down immediately |
Go
The Go module (academy/leader-election) has one package per idea. The simulator and the lease elector run without any infrastructure and are fully tested; the client-go, etcd and PostgreSQL adapters compile against real clients. Dependencies: k8s.io/client-go v0.33.4 and go.etcd.io/etcd/client/v3 v3.6.4, pinned because newer client-go releases require a newer Go; client-go v0.33 itself needs go 1.24.0, which is why go.mod says go 1.24.0.
Before
One SET NX with a 30-second TTL, never renewed, never re-checked, unfenced writes:
// Command before shows the usual first attempt at "only one instance runs
// the billing job": a Redis-style SET NX with a TTL, checked once, then a
// long job with unconditional writes. Every replica runs this loop.
package main
import (
"context"
"fmt"
"os"
"time"
)
// Locker is whatever key-value store is at hand (Redis SET NX EX, a cache).
type Locker interface {
SetNX(ctx context.Context, key, value string, ttl time.Duration) (bool, error)
}
// Ledger is the database the job writes to.
type Ledger interface {
MarkInvoiced(ctx context.Context, customerID int) error
}
func runBilling(ctx context.Context, l Locker, db Ledger, customers []int) error {
host, _ := os.Hostname()
ok, err := l.SetNX(ctx, "billing-leader", host, 30*time.Second)
if err != nil || !ok {
return err // someone else is "the leader"
}
// Problems:
// 1. The job takes 10 minutes; the 30 s TTL expires and a second replica
// becomes "leader" while this one is still running.
// 2. Nothing renews the key, and nothing checks it again.
// 3. A GC pause or VM freeze longer than 30 s is invisible to this code.
// 4. Writes carry no epoch, so the database cannot tell an old leader
// from the current one: customers are invoiced twice.
// 5. With Redis replication, a failover can lose the key entirely.
for _, id := range customers {
if err := db.MarkInvoiced(ctx, id); err != nil {
return err
}
}
return nil
}
func main() { fmt.Println("compile-only example; see runBilling") }After
A deterministic Raft election simulator: terms, randomized election timeouts, RequestVote with the election restriction, heartbeats, Pre-Vote, CheckQuorum, partitions, crashes:
// Package raftsim is a deterministic, single-process simulator of Raft leader
// election (Ongaro & Ousterhout, section 5.2): terms, randomized election
// timeouts, RequestVote, heartbeats (empty AppendEntries), the election
// restriction (votes only for an up-to-date log), plus the two extensions
// production implementations add: Pre-Vote and CheckQuorum.
//
// Time is a tick counter, the network is a delayed message queue, and
// partitions are blocked links, so every run with the same seed is identical.
// It simulates elections only; log replication is reduced to "a follower
// copies the leader's log on every heartbeat".
package raftsim
import (
"fmt"
"math/rand"
"sort"
)
// State is a node's role.
type State int
const (
Follower State = iota
PreCandidate
Candidate
Leader
)
func (s State) String() string {
return [...]string{"follower", "pre-candidate", "candidate", "leader"}[s]
}
// Config holds the timing knobs, all in ticks.
type Config struct {
Nodes int
ElectionTimeoutMin int // e.g. 150 (the paper's 150-300 ms with 1 tick = 1 ms)
ElectionTimeoutMax int // equal to Min disables randomization
HeartbeatInterval int // must be well below ElectionTimeoutMin
MinDelay, MaxDelay int // one-way network delay
PreVote bool
CheckQuorum bool
Seed int64
}
// DefaultConfig follows the paper's recommendation: 150-300 ms timeouts,
// heartbeats at a third of the minimum timeout, 1-5 ms network delay.
func DefaultConfig(seed int64) Config {
return Config{Nodes: 5, ElectionTimeoutMin: 150, ElectionTimeoutMax: 300,
HeartbeatInterval: 50, MinDelay: 1, MaxDelay: 5, Seed: seed}
}
type msgType int
const (
msgVote msgType = iota
msgVoteResp
msgPreVote
msgPreVoteResp
msgHeartbeat
msgHeartbeatResp
)
type message struct {
typ msgType
from, to int
term uint64
granted bool
lastLogIndex int
lastLogTerm uint64
log []uint64
deliverAt int
seq int
}
// Node is one simulated server. Term, VotedFor and Log are the persistent
// state Raft writes to disk before answering an RPC.
type Node struct {
ID int
State State
Term uint64
VotedFor int
Log []uint64 // the term of each entry
LeaderID int
Crashed bool
electionElapsed int
electionTimeout int
heartbeatElapsed int
votes map[int]bool
recentActive map[int]bool
}
func (n *Node) lastLog() (int, uint64) {
if len(n.Log) == 0 {
return 0, 0
}
return len(n.Log), n.Log[len(n.Log)-1]
}
// Event is one line of the simulation timeline.
type Event struct {
Tick int
Node int
Term uint64
Kind string
Detail string
}
func (e Event) String() string {
if e.Node < 0 {
return fmt.Sprintf("t=%5d %-12s %-18s %s", e.Tick, "", e.Kind, e.Detail)
}
return fmt.Sprintf("t=%5d n%d term=%-3d %-18s %s", e.Tick, e.Node, e.Term, e.Kind, e.Detail)
}
// Cluster is the simulated cluster plus its network.
type Cluster struct {
cfg Config
Nodes []*Node
Now int
Events []Event
queue []message
seq int
blocked map[[2]int]bool
rng *rand.Rand
// leadersByTerm records every node that ever became leader in a term.
leadersByTerm map[uint64]map[int]bool
}
// New builds a cluster where every node starts as a follower in term 0.
func New(cfg Config) *Cluster {
c := &Cluster{cfg: cfg, blocked: map[[2]int]bool{},
rng: rand.New(rand.NewSource(cfg.Seed)), leadersByTerm: map[uint64]map[int]bool{}}
for i := 0; i < cfg.Nodes; i++ {
n := &Node{ID: i, VotedFor: -1, LeaderID: -1}
c.Nodes = append(c.Nodes, n)
c.resetTimeout(n)
}
return c
}
func (c *Cluster) majority() int { return c.cfg.Nodes/2 + 1 }
func (c *Cluster) resetTimeout(n *Node) {
n.electionElapsed = 0
span := c.cfg.ElectionTimeoutMax - c.cfg.ElectionTimeoutMin
n.electionTimeout = c.cfg.ElectionTimeoutMin
if span > 0 {
n.electionTimeout += c.rng.Intn(span + 1)
}
}
func (c *Cluster) log(n *Node, kind, format string, args ...any) {
c.Events = append(c.Events, Event{Tick: c.Now, Node: n.ID, Term: n.Term, Kind: kind, Detail: fmt.Sprintf(format, args...)})
}
func (c *Cluster) send(m message) {
delay := c.cfg.MinDelay
if c.cfg.MaxDelay > c.cfg.MinDelay {
delay += c.rng.Intn(c.cfg.MaxDelay - c.cfg.MinDelay + 1)
}
c.seq++
m.deliverAt, m.seq = c.Now+delay, c.seq
c.queue = append(c.queue, m)
}
func (c *Cluster) broadcast(from *Node, m message) {
for _, p := range c.Nodes {
if p.ID != from.ID {
m.from, m.to = from.ID, p.ID
c.send(m)
}
}
}
// Partition splits the cluster: links between different groups drop messages.
func (c *Cluster) Partition(groups ...[]int) {
c.blocked = map[[2]int]bool{}
group := map[int]int{}
for g, ids := range groups {
for _, id := range ids {
group[id] = g
}
}
for _, a := range c.Nodes {
for _, b := range c.Nodes {
if group[a.ID] != group[b.ID] {
c.blocked[[2]int{a.ID, b.ID}] = true
}
}
}
c.Events = append(c.Events, Event{Tick: c.Now, Node: -1, Kind: "network", Detail: fmt.Sprintf("partition %v", groups)})
}
// Heal removes every partition.
func (c *Cluster) Heal() {
c.blocked = map[[2]int]bool{}
c.Events = append(c.Events, Event{Tick: c.Now, Node: -1, Kind: "network", Detail: "healed"})
}
// Crash stops a node; Restart brings it back as a follower with its
// persistent state (term, vote, log) intact.
func (c *Cluster) Crash(id int) { c.Nodes[id].Crashed = true; c.log(c.Nodes[id], "crash", "") }
func (c *Cluster) Restart(id int) {
n := c.Nodes[id]
n.Crashed, n.State, n.LeaderID = false, Follower, -1
c.resetTimeout(n)
c.log(n, "restart", "as follower")
}
// Propose appends one entry on a leader (used to make logs differ).
func (c *Cluster) Propose(id int) bool {
n := c.Nodes[id]
if n.Crashed || n.State != Leader {
return false
}
n.Log = append(n.Log, n.Term)
return true
}
// Tick advances time by one tick: deliver due messages, then run timers.
func (c *Cluster) Tick() {
c.Now++
sort.Slice(c.queue, func(i, j int) bool {
if c.queue[i].deliverAt != c.queue[j].deliverAt {
return c.queue[i].deliverAt < c.queue[j].deliverAt
}
return c.queue[i].seq < c.queue[j].seq
})
var due, later []message
for _, m := range c.queue {
if m.deliverAt > c.Now {
later = append(later, m)
} else {
due = append(due, m)
}
}
c.queue = later // replies sent while delivering are appended to this
for _, m := range due {
if c.blocked[[2]int{m.from, m.to}] || c.Nodes[m.to].Crashed {
continue // dropped
}
c.receive(c.Nodes[m.to], m)
}
for _, n := range c.Nodes {
if !n.Crashed {
c.tickNode(n)
}
}
}
// RunUntil ticks until cond is true or max ticks pass; it reports success.
func (c *Cluster) RunUntil(max int, cond func() bool) bool {
for i := 0; i < max; i++ {
c.Tick()
if cond() {
return true
}
}
return false
}
// Run ticks a fixed number of times.
func (c *Cluster) Run(ticks int) {
for i := 0; i < ticks; i++ {
c.Tick()
}
}
// Leaders lists live nodes that currently believe they are leader.
func (c *Cluster) Leaders() []int {
var ids []int
for _, n := range c.Nodes {
if !n.Crashed && n.State == Leader {
ids = append(ids, n.ID)
}
}
return ids
}
// ElectionSafetyViolations returns terms in which more than one node became
// leader. Raft's Election Safety property says this is always empty.
func (c *Cluster) ElectionSafetyViolations() []uint64 {
var bad []uint64
for term, ids := range c.leadersByTerm {
if len(ids) > 1 {
bad = append(bad, term)
}
}
return bad
}
func (c *Cluster) tickNode(n *Node) {
if n.State == Leader {
n.heartbeatElapsed++
if n.heartbeatElapsed >= c.cfg.HeartbeatInterval {
n.heartbeatElapsed = 0
c.broadcast(n, message{typ: msgHeartbeat, term: n.Term, log: append([]uint64(nil), n.Log...)})
}
if c.cfg.CheckQuorum {
n.electionElapsed++
if n.electionElapsed >= c.cfg.ElectionTimeoutMin {
n.electionElapsed = 0
if len(n.recentActive)+1 < c.majority() {
c.becomeFollower(n, n.Term, -1)
c.log(n, "step-down", "check quorum: heard from %d of %d", len(n.recentActive)+1, c.cfg.Nodes)
return
}
n.recentActive = map[int]bool{}
}
}
return
}
n.electionElapsed++
if n.electionElapsed >= n.electionTimeout {
if c.cfg.PreVote {
c.startPreVote(n)
} else {
c.startElection(n)
}
}
}
func (c *Cluster) startPreVote(n *Node) {
n.State, n.votes, n.LeaderID = PreCandidate, map[int]bool{n.ID: true}, -1
c.resetTimeout(n)
idx, lt := n.lastLog()
c.log(n, "pre-vote", "asks for term %d without bumping its own", n.Term+1)
c.broadcast(n, message{typ: msgPreVote, term: n.Term + 1, lastLogIndex: idx, lastLogTerm: lt})
}
func (c *Cluster) startElection(n *Node) {
n.Term++
n.State, n.VotedFor, n.votes, n.LeaderID = Candidate, n.ID, map[int]bool{n.ID: true}, -1
c.resetTimeout(n)
idx, lt := n.lastLog()
c.log(n, "candidate", "timeout %d ticks, RequestVote to all", n.electionTimeout)
c.broadcast(n, message{typ: msgVote, term: n.Term, lastLogIndex: idx, lastLogTerm: lt})
c.maybeWin(n)
}
func (c *Cluster) becomeFollower(n *Node, term uint64, leader int) {
if term > n.Term {
n.Term, n.VotedFor = term, -1
}
n.State, n.LeaderID = Follower, leader
c.resetTimeout(n)
}
func (c *Cluster) maybeWin(n *Node) {
if len(n.votes) < c.majority() {
return
}
switch n.State {
case PreCandidate:
c.startElection(n)
case Candidate:
n.State, n.LeaderID, n.heartbeatElapsed = Leader, n.ID, 0
n.electionElapsed, n.recentActive = 0, map[int]bool{}
if c.leadersByTerm[n.Term] == nil {
c.leadersByTerm[n.Term] = map[int]bool{}
}
c.leadersByTerm[n.Term][n.ID] = true
c.log(n, "LEADER", "won with %d of %d votes", len(n.votes), c.cfg.Nodes)
c.broadcast(n, message{typ: msgHeartbeat, term: n.Term, log: append([]uint64(nil), n.Log...)})
}
}
// upToDate is the election restriction (section 5.4.1): grant a vote only
// if the candidate's last entry has a higher term, or the same term and an
// index at least as large.
func upToDate(n *Node, idx int, term uint64) bool {
myIdx, myTerm := n.lastLog()
return term > myTerm || (term == myTerm && idx >= myIdx)
}
// inLease is true when a follower heard from a live leader recently; with
// CheckQuorum on, such a follower ignores vote requests (Raft thesis 4.2.3).
func (c *Cluster) inLease(n *Node) bool {
return c.cfg.CheckQuorum && n.LeaderID != -1 && n.electionElapsed < c.cfg.ElectionTimeoutMin
}
func (c *Cluster) receive(n *Node, m message) {
switch m.typ {
case msgPreVote:
granted := m.term > n.Term && upToDate(n, m.lastLogIndex, m.lastLogTerm) && !c.inLease(n) && n.State != Leader
c.send(message{typ: msgPreVoteResp, from: n.ID, to: m.from, term: m.term, granted: granted})
case msgPreVoteResp:
if n.State == PreCandidate && m.term == n.Term+1 && m.granted {
n.votes[m.from] = true
c.maybeWin(n)
}
case msgVote:
if m.term > n.Term {
if c.inLease(n) {
c.send(message{typ: msgVoteResp, from: n.ID, to: m.from, term: n.Term})
return
}
c.becomeFollower(n, m.term, -1)
}
granted := m.term == n.Term && (n.VotedFor == -1 || n.VotedFor == m.from) && upToDate(n, m.lastLogIndex, m.lastLogTerm)
if granted {
n.VotedFor = m.from
c.resetTimeout(n)
}
c.send(message{typ: msgVoteResp, from: n.ID, to: m.from, term: n.Term, granted: granted})
case msgVoteResp:
if m.term > n.Term {
c.becomeFollower(n, m.term, -1)
return
}
if n.State == Candidate && m.term == n.Term && m.granted {
n.votes[m.from] = true
c.maybeWin(n)
}
case msgHeartbeat:
if m.term < n.Term {
// A stale leader learns the newer term from the rejection.
c.send(message{typ: msgHeartbeatResp, from: n.ID, to: m.from, term: n.Term})
return
}
if n.State != Follower || n.LeaderID != m.from {
if n.State == Leader {
c.log(n, "step-down", "heartbeat from n%d in term %d", m.from, m.term)
}
c.becomeFollower(n, m.term, m.from)
} else {
if m.term > n.Term {
n.Term, n.VotedFor = m.term, -1
}
n.electionElapsed = 0
}
n.Log = append(n.Log[:0], m.log...)
c.send(message{typ: msgHeartbeatResp, from: n.ID, to: m.from, term: n.Term, granted: true})
case msgHeartbeatResp:
if m.term > n.Term {
c.log(n, "step-down", "saw term %d from n%d", m.term, m.from)
c.becomeFollower(n, m.term, -1)
return
}
if n.State == Leader && m.granted {
n.recentActive[m.from] = true
}
}
}Its tests: one stable leader; endless split votes without randomization; crash failover; a partitioned leader that keeps believing; CheckQuorum; Pre-Vote stopping term inflation; a stale log that cannot win; 150 seeds of random chaos with the Election Safety invariant:
package raftsim
import (
"math/rand"
"testing"
)
func oneLeader(c *Cluster) func() bool {
return func() bool { return len(c.Leaders()) == 1 }
}
func TestElectsExactlyOneLeader(t *testing.T) {
c := New(DefaultConfig(1))
if !c.RunUntil(2000, oneLeader(c)) {
t.Fatalf("no leader after 2000 ticks")
}
// Stable: heartbeats keep followers from starting new elections.
leader, term := c.Leaders()[0], c.Nodes[c.Leaders()[0]].Term
c.Run(5000)
if got := c.Leaders(); len(got) != 1 || got[0] != leader || c.Nodes[leader].Term != term {
t.Fatalf("leadership changed without a failure: %v term %d", got, c.Nodes[leader].Term)
}
}
func TestNoRandomizationMeansSplitVotesForever(t *testing.T) {
cfg := DefaultConfig(1)
cfg.ElectionTimeoutMax = cfg.ElectionTimeoutMin // every node times out together
cfg.MaxDelay = cfg.MinDelay // perfectly symmetric network
c := New(cfg)
if c.RunUntil(10000, oneLeader(c)) {
t.Fatalf("expected endless split votes, got leader %v", c.Leaders())
}
if c.Nodes[0].Term < 30 {
t.Fatalf("expected many failed terms, got term %d", c.Nodes[0].Term)
}
}
func TestLeaderCrashFailover(t *testing.T) {
c := New(DefaultConfig(7))
c.RunUntil(2000, oneLeader(c))
old := c.Leaders()[0]
oldTerm := c.Nodes[old].Term
crashAt := c.Now
c.Crash(old)
if !c.RunUntil(2000, oneLeader(c)) {
t.Fatalf("no new leader")
}
nl := c.Leaders()[0]
if nl == old || c.Nodes[nl].Term <= oldTerm {
t.Fatalf("new leader %d term %d, old %d term %d", nl, c.Nodes[nl].Term, old, oldTerm)
}
// Downtime is at least one election timeout and usually below two.
if d := c.Now - crashAt; d < 150 || d > 700 {
t.Fatalf("failover took %d ticks", d)
}
// The old leader comes back and follows: it sees the higher term.
c.Restart(old)
c.Run(500)
if c.Nodes[old].State != Follower || c.Nodes[old].Term != c.Nodes[nl].Term {
t.Fatalf("restarted node state %v term %d", c.Nodes[old].State, c.Nodes[old].Term)
}
}
func TestPartitionedLeaderKeepsBelievingWithoutCheckQuorum(t *testing.T) {
c := New(DefaultConfig(3))
c.RunUntil(2000, oneLeader(c))
old := c.Leaders()[0]
var rest []int
for i := range c.Nodes {
if i != old {
rest = append(rest, i)
}
}
c.Partition([]int{old}, rest)
c.Run(1500)
// Two nodes think they lead, in different terms: the minority one is a zombie.
if got := c.Leaders(); len(got) != 2 {
t.Fatalf("expected old and new leader, got %v", got)
}
if len(c.ElectionSafetyViolations()) != 0 {
t.Fatalf("two leaders in one term")
}
c.Heal()
c.Run(500)
if got := c.Leaders(); len(got) != 1 || got[0] == old {
t.Fatalf("after heal: %v", got)
}
}
func TestCheckQuorumStepsDownMinorityLeader(t *testing.T) {
cfg := DefaultConfig(3)
cfg.CheckQuorum = true
c := New(cfg)
c.RunUntil(2000, oneLeader(c))
old := c.Leaders()[0]
c.Partition([]int{old}, others(c, old))
c.Run(400)
if c.Nodes[old].State == Leader {
t.Fatalf("minority leader did not step down")
}
}
func TestPreVoteStopsTermInflationByIsolatedNode(t *testing.T) {
for _, preVote := range []bool{false, true} {
cfg := DefaultConfig(11)
cfg.PreVote, cfg.CheckQuorum = preVote, preVote
c := New(cfg)
c.RunUntil(3000, oneLeader(c))
leader := c.Leaders()[0]
victim := (leader + 1) % cfg.Nodes
c.Partition([]int{victim}, others(c, victim))
c.Run(3000)
isolatedTerm := c.Nodes[victim].Term
c.Heal()
c.Run(1000)
stillLeader := len(c.Leaders()) == 1 && c.Leaders()[0] == leader
if preVote && (!stillLeader || isolatedTerm != c.Nodes[leader].Term) {
t.Fatalf("pre-vote: leader disrupted (term of isolated node %d)", isolatedTerm)
}
if !preVote && (stillLeader || isolatedTerm < 10) {
t.Fatalf("without pre-vote expected disruption, isolated term %d", isolatedTerm)
}
}
}
func TestStaleLogCannotWin(t *testing.T) {
c := New(DefaultConfig(5))
c.RunUntil(2000, oneLeader(c))
leader := c.Leaders()[0]
lagger := (leader + 1) % 5
c.Partition([]int{lagger}, others(c, lagger))
for i := 0; i < 5; i++ {
c.Propose(leader)
c.Run(60)
}
c.Crash(leader)
c.Heal()
c.RunUntil(3000, oneLeader(c))
if c.Leaders()[0] == lagger {
t.Fatalf("node with a shorter log became leader")
}
}
// TestElectionSafetyUnderChaos is a small Jepsen-style randomized test:
// random partitions, crashes and restarts, many seeds, one invariant.
func TestElectionSafetyUnderChaos(t *testing.T) {
for seed := int64(0); seed < 150; seed++ {
cfg := DefaultConfig(seed)
cfg.PreVote, cfg.CheckQuorum = seed%2 == 0, seed%3 == 0
c := New(cfg)
r := rand.New(rand.NewSource(seed))
for step := 0; step < 40; step++ {
switch r.Intn(4) {
case 0:
perm := r.Perm(cfg.Nodes)
cut := 1 + r.Intn(cfg.Nodes-1)
c.Partition(perm[:cut], perm[cut:])
case 1:
c.Heal()
case 2:
c.Crash(r.Intn(cfg.Nodes))
case 3:
c.Restart(r.Intn(cfg.Nodes))
}
for _, l := range c.Leaders() {
c.Propose(l)
}
c.Run(50 + r.Intn(400))
}
if bad := c.ElectionSafetyViolations(); len(bad) > 0 {
t.Fatalf("seed %d: two leaders in terms %v", seed, bad)
}
}
}
func others(c *Cluster, id int) []int {
var ids []int
for i := range c.Nodes {
if i != id {
ids = append(ids, i)
}
}
return ids
}// Command electionsim prints the timeline of two Raft election scenarios
// (1 tick = 1 ms): a partitioned leader without CheckQuorum (a zombie that
// still believes it leads) and the same partition with Pre-Vote and
// CheckQuorum enabled.
package main
import (
"fmt"
"academy/leader-election/raftsim"
)
func scenario(title string, preVote, checkQuorum bool) {
fmt.Println("==", title)
cfg := raftsim.DefaultConfig(42)
cfg.PreVote, cfg.CheckQuorum = preVote, checkQuorum
c := raftsim.New(cfg)
c.RunUntil(2000, func() bool { return len(c.Leaders()) == 1 })
old := c.Leaders()[0]
c.Run(200)
var rest []int
for i := 0; i < cfg.Nodes; i++ {
if i != old {
rest = append(rest, i)
}
}
c.Partition([]int{old}, rest)
c.Run(800)
fmt.Printf("-- at t=%d nodes that believe they lead: %v\n", c.Now, c.Leaders())
c.Heal()
c.Run(600)
for _, e := range c.Events {
if e.Kind != "pre-vote" || e.Tick < 400 {
fmt.Println(e)
}
}
fmt.Printf("-- at t=%d leaders: %v, terms: ", c.Now, c.Leaders())
for _, n := range c.Nodes {
fmt.Printf("n%d=%d ", n.ID, n.Term)
}
fmt.Printf("\n-- election safety violations: %d\n\n", len(c.ElectionSafetyViolations()))
}
func main() {
scenario("plain Raft: partition the leader away", false, false)
scenario("Pre-Vote + CheckQuorum: same partition", true, true)
}A lease elector with client-go's rules (local-clock expiry, RenewDeadline step-down, epochs, release) over any compare-and-swap store:
// Package lease is a lease-based leader elector over any store that offers
// read + compare-and-swap (a Kubernetes Lease, an etcd key, a SQL row). It
// mirrors the rules of k8s.io/client-go/tools/leaderelection:
//
// - a candidate may take over only after it has watched the record stay
// unchanged for a full LeaseDuration, measured on its OWN clock from the
// moment it observed the record (remote timestamps are never trusted);
// - the leader renews every RetryPeriod and gives up leadership when it has
// not renewed successfully for RenewDeadline, which must be shorter than
// LeaseDuration so the old leader stops before anyone else may start;
// - every change of holder increments Epoch (client-go: LeaderTransitions),
// which the leader attaches to its writes as a fencing token.
package lease
import (
"context"
"errors"
"fmt"
"sync"
"time"
)
// JitterFactor matches client-go: retries wait RetryPeriod * (1 + rand*1.2).
const JitterFactor = 1.2
// Record is what the store keeps; it corresponds to coordination.k8s.io/v1
// LeaseSpec (holderIdentity, leaseDurationSeconds, acquireTime, renewTime,
// leaseTransitions).
type Record struct {
Holder string
LeaseDuration time.Duration
AcquireTime time.Time
RenewTime time.Time
Epoch uint64
}
// ErrConflict means the compare-and-swap lost: someone else wrote first.
var ErrConflict = errors.New("lease: version conflict")
// Store is the minimal contract: read with a version, write if unchanged.
// Version 0 means "the record does not exist yet".
type Store interface {
Get(ctx context.Context, name string) (rec Record, version int64, err error)
CompareAndSwap(ctx context.Context, name string, version int64, rec Record) error
}
// Clock is injectable so tests control time.
type Clock interface{ Now() time.Time }
// Config holds the three client-go knobs plus identity and callbacks.
type Config struct {
Name, Identity string
LeaseDuration time.Duration // client-go default 15s
RenewDeadline time.Duration // client-go default 10s
RetryPeriod time.Duration // client-go default 2s
Store Store
Clock Clock
// OnStartedLeading receives the epoch to attach to every write.
OnStartedLeading func(epoch uint64)
OnStoppedLeading func(reason string)
OnNewLeader func(identity string)
}
// Elector runs one candidate.
type Elector struct {
cfg Config
mu sync.Mutex
observed Record
observedVer int64
observedAt time.Time // local time when observed last changed
leading bool
lastRenew time.Time // local time of the last successful renew
reportedLead string
}
// New validates the knobs with the same rules (and messages) as client-go.
func New(cfg Config) (*Elector, error) {
switch {
case cfg.LeaseDuration <= cfg.RenewDeadline:
return nil, fmt.Errorf("leaseDuration must be greater than renewDeadline")
case cfg.RenewDeadline <= time.Duration(JitterFactor*float64(cfg.RetryPeriod)):
return nil, fmt.Errorf("renewDeadline must be greater than retryPeriod*JitterFactor")
case cfg.RetryPeriod <= 0:
return nil, fmt.Errorf("retryPeriod must be greater than zero")
case cfg.Identity == "":
return nil, fmt.Errorf("Lock identity is empty")
case cfg.Store == nil || cfg.Clock == nil:
return nil, fmt.Errorf("store and clock are required")
}
return &Elector{cfg: cfg}, nil
}
// IsLeader reports what this process believes. A true value is a hint, not
// a guarantee: a paused process cannot know its lease ran out.
func (e *Elector) IsLeader() bool {
e.mu.Lock()
defer e.mu.Unlock()
return e.leading
}
// Epoch returns the epoch of the record this process last observed.
func (e *Elector) Epoch() uint64 {
e.mu.Lock()
defer e.mu.Unlock()
return e.observed.Epoch
}
// Step performs one acquire-or-renew attempt; Run calls it every RetryPeriod.
func (e *Elector) Step(ctx context.Context) {
e.mu.Lock()
defer e.mu.Unlock()
now := e.cfg.Clock.Now()
ok := e.tryAcquireOrRenew(ctx, now)
switch {
case ok && !e.leading:
e.leading, e.lastRenew = true, now
if e.cfg.OnStartedLeading != nil {
e.cfg.OnStartedLeading(e.observed.Epoch)
}
case ok:
e.lastRenew = now
case e.leading && (e.observed.Holder != e.cfg.Identity || now.Sub(e.lastRenew) >= e.cfg.RenewDeadline):
e.leading = false
if e.cfg.OnStoppedLeading != nil {
e.cfg.OnStoppedLeading(fmt.Sprintf("no successful renew for %s", now.Sub(e.lastRenew)))
}
}
if e.observed.Holder != e.reportedLead {
e.reportedLead = e.observed.Holder
if e.cfg.OnNewLeader != nil {
e.cfg.OnNewLeader(e.reportedLead)
}
}
}
func (e *Elector) tryAcquireOrRenew(ctx context.Context, now time.Time) bool {
rec, ver, err := e.cfg.Store.Get(ctx, e.cfg.Name)
if err != nil {
return false
}
if ver != e.observedVer {
// The record changed since we last looked: restart our local timer.
e.observed, e.observedVer, e.observedAt = rec, ver, now
}
held := rec.Holder != "" && rec.Holder != e.cfg.Identity
if held && now.Sub(e.observedAt) < rec.LeaseDuration {
return false // someone else holds an unexpired lease (by OUR clock)
}
next := Record{Holder: e.cfg.Identity, LeaseDuration: e.cfg.LeaseDuration,
AcquireTime: now, RenewTime: now, Epoch: rec.Epoch + 1}
if rec.Holder == e.cfg.Identity && ver != 0 {
next.AcquireTime, next.Epoch = rec.AcquireTime, rec.Epoch // renew keeps the epoch
}
if err := e.cfg.Store.CompareAndSwap(ctx, e.cfg.Name, ver, next); err != nil {
return false
}
e.observed, e.observedVer, e.observedAt = next, ver+1, now
return true
}
// Release gives the lease up on graceful shutdown (client-go ReleaseOnCancel):
// it clears the holder so a standby can acquire at once instead of waiting a
// full LeaseDuration. Call it only after all guarded work has stopped.
func (e *Elector) Release(ctx context.Context) error {
e.mu.Lock()
defer e.mu.Unlock()
if !e.leading {
return nil
}
now := e.cfg.Clock.Now()
rel := Record{LeaseDuration: time.Second, AcquireTime: now, RenewTime: now, Epoch: e.observed.Epoch}
if err := e.cfg.Store.CompareAndSwap(ctx, e.cfg.Name, e.observedVer, rel); err != nil {
return err
}
e.leading = false
e.observed, e.observedVer = rel, e.observedVer+1
if e.cfg.OnStoppedLeading != nil {
e.cfg.OnStoppedLeading("released")
}
return nil
}
// Run loops until ctx is done, then releases. jitter returns a value in
// [0,1); pass rand.Float64 in production.
func (e *Elector) Run(ctx context.Context, jitter func() float64) {
for {
e.Step(ctx)
wait := e.cfg.RetryPeriod
if !e.IsLeader() {
wait += time.Duration(jitter() * JitterFactor * float64(e.cfg.RetryPeriod))
}
select {
case <-ctx.Done():
rctx, cancel := context.WithTimeout(context.Background(), e.cfg.RenewDeadline)
_ = e.Release(rctx)
cancel()
return
case <-time.After(wait):
}
}
}
// MemoryStore is an in-process Store for tests and the lab. It can be made
// unreachable to simulate a partition between one client and the store.
type MemoryStore struct {
mu sync.Mutex
recs map[string]Record
vers map[string]int64
Unreach map[string]bool // identity -> cannot reach the store
ErrUnrch error
}
func NewMemoryStore() *MemoryStore {
return &MemoryStore{recs: map[string]Record{}, vers: map[string]int64{},
Unreach: map[string]bool{}, ErrUnrch: errors.New("store unreachable")}
}
type callerKey struct{}
// As tags a context with the caller identity so partitions can be simulated.
func As(ctx context.Context, identity string) context.Context {
return context.WithValue(ctx, callerKey{}, identity)
}
func (m *MemoryStore) reachable(ctx context.Context) error {
if id, _ := ctx.Value(callerKey{}).(string); m.Unreach[id] {
return m.ErrUnrch
}
return nil
}
func (m *MemoryStore) Get(ctx context.Context, name string) (Record, int64, error) {
m.mu.Lock()
defer m.mu.Unlock()
if err := m.reachable(ctx); err != nil {
return Record{}, 0, err
}
return m.recs[name], m.vers[name], nil
}
func (m *MemoryStore) CompareAndSwap(ctx context.Context, name string, version int64, rec Record) error {
m.mu.Lock()
defer m.mu.Unlock()
if err := m.reachable(ctx); err != nil {
return err
}
if m.vers[name] != version {
return ErrConflict
}
m.recs[name], m.vers[name] = rec, version+1
return nil
}Tests with fake clocks, including clock rate skew beyond and within the tolerance and a zombie that is fenced:
package lease
import (
"context"
"errors"
"testing"
"time"
"academy/leader-election/fencing"
)
// fakeClock is shared "real" time; ratedClock lets one node's clock run
// faster or slower than real time (clock skew RATE, not offset).
type fakeClock struct{ t time.Time }
func (f *fakeClock) Now() time.Time { return f.t }
func (f *fakeClock) Advance(d time.Duration) { f.t = f.t.Add(d) }
type ratedClock struct {
base *fakeClock
start time.Time
rate float64
}
func (r ratedClock) Now() time.Time {
return r.start.Add(time.Duration(float64(r.base.t.Sub(r.start)) * r.rate))
}
type node struct {
e *Elector
ctx context.Context
}
func newNode(t *testing.T, id string, s Store, c Clock, ld, rd, rp time.Duration) node {
t.Helper()
e, err := New(Config{Name: "billing-scheduler", Identity: id, LeaseDuration: ld,
RenewDeadline: rd, RetryPeriod: rp, Store: s, Clock: c})
if err != nil {
t.Fatal(err)
}
return node{e: e, ctx: As(context.Background(), id)}
}
func defaults(t *testing.T, id string, s Store, c Clock) node {
return newNode(t, id, s, c, 15*time.Second, 10*time.Second, 2*time.Second)
}
func TestValidationMatchesClientGo(t *testing.T) {
s, c := NewMemoryStore(), &fakeClock{}
cases := []struct {
ld, rd, rp time.Duration
want string
}{
{10 * time.Second, 10 * time.Second, 2 * time.Second, "leaseDuration must be greater than renewDeadline"},
{15 * time.Second, 2 * time.Second, 2 * time.Second, "renewDeadline must be greater than retryPeriod*JitterFactor"},
}
for _, tc := range cases {
_, err := New(Config{Identity: "a", LeaseDuration: tc.ld, RenewDeadline: tc.rd, RetryPeriod: tc.rp, Store: s, Clock: c})
if err == nil || err.Error() != tc.want {
t.Fatalf("got %v want %q", err, tc.want)
}
}
}
func TestOneLeaderAndEpochs(t *testing.T) {
s, c := NewMemoryStore(), &fakeClock{t: time.Unix(0, 0)}
a, b := defaults(t, "pod-a", s, c), defaults(t, "pod-b", s, c)
a.e.Step(a.ctx)
b.e.Step(b.ctx)
if !a.e.IsLeader() || b.e.IsLeader() || a.e.Epoch() != 1 {
t.Fatalf("a=%v b=%v epoch=%d", a.e.IsLeader(), b.e.IsLeader(), a.e.Epoch())
}
for i := 0; i < 20; i++ { // 40 s of renewals: epoch must not move
c.Advance(2 * time.Second)
a.e.Step(a.ctx)
b.e.Step(b.ctx)
}
if !a.e.IsLeader() || b.e.IsLeader() || a.e.Epoch() != 1 {
t.Fatalf("renewal changed leadership")
}
}
func TestCrashedLeaderIsReplacedAfterLeaseDuration(t *testing.T) {
s, c := NewMemoryStore(), &fakeClock{t: time.Unix(0, 0)}
a, b := defaults(t, "pod-a", s, c), defaults(t, "pod-b", s, c)
a.e.Step(a.ctx)
b.e.Step(b.ctx) // b observes a's record at t=0
// a crashes: it never steps again.
var tookOver time.Duration
for elapsed := time.Duration(0); elapsed <= 30*time.Second; elapsed += 2 * time.Second {
b.e.Step(b.ctx)
if b.e.IsLeader() {
tookOver = elapsed
break
}
c.Advance(2 * time.Second)
}
if tookOver < 15*time.Second || tookOver > 18*time.Second {
t.Fatalf("standby took over after %s, want just after LeaseDuration", tookOver)
}
if b.e.Epoch() != 2 {
t.Fatalf("epoch %d, want 2", b.e.Epoch())
}
}
// overlap steps two nodes in lock-step and reports whether both ever
// believed they were leader at the same moment.
func overlap(a, b node, c *fakeClock, steps int, step time.Duration) bool {
for i := 0; i < steps; i++ {
a.e.Step(a.ctx)
b.e.Step(b.ctx)
if a.e.IsLeader() && b.e.IsLeader() {
return true
}
c.Advance(step)
}
return false
}
func TestPartitionedLeaderStepsDownBeforeStandbyTakesOver(t *testing.T) {
s, c := NewMemoryStore(), &fakeClock{t: time.Unix(0, 0)}
a, b := defaults(t, "pod-a", s, c), defaults(t, "pod-b", s, c)
a.e.Step(a.ctx)
s.Unreach["pod-a"] = true // a cannot reach the API server any more
if overlap(a, b, c, 60, 500*time.Millisecond) {
t.Fatalf("two leaders at once with equal clock rates")
}
if a.e.IsLeader() || !b.e.IsLeader() {
t.Fatalf("a=%v b=%v", a.e.IsLeader(), b.e.IsLeader())
}
}
func TestClockRateSkewBeyondToleranceBreaksSafety(t *testing.T) {
// The leader's clock runs at half speed: its 10 s RenewDeadline lasts
// 20 real seconds, while the standby's 15 s LeaseDuration is real.
// Tolerance is LeaseDuration/RenewDeadline = 1.5 < 2, so they overlap.
s, real := NewMemoryStore(), &fakeClock{t: time.Unix(0, 0)}
slow := ratedClock{base: real, start: real.t, rate: 0.5}
a := defaults(t, "pod-a", s, slow)
b := defaults(t, "pod-b", s, real)
a.e.Step(a.ctx)
s.Unreach["pod-a"] = true
if !overlap(a, b, real, 80, 500*time.Millisecond) {
t.Fatalf("expected an overlap when skew rate exceeds the tolerance")
}
// 60 s / 30 s tolerates a 2x rate difference (the client-go docs example);
// a 1.9x slower leader clock no longer overlaps.
s2, real2 := NewMemoryStore(), &fakeClock{t: time.Unix(0, 0)}
slow2 := ratedClock{base: real2, start: real2.t, rate: 1 / 1.9}
a2 := newNode(t, "pod-a", s2, slow2, 60*time.Second, 30*time.Second, 2*time.Second)
b2 := newNode(t, "pod-b", s2, real2, 60*time.Second, 30*time.Second, 2*time.Second)
a2.e.Step(a2.ctx)
s2.Unreach["pod-a"] = true
if overlap(a2, b2, real2, 400, 500*time.Millisecond) {
t.Fatalf("60s/30s should tolerate a 1.9x rate difference")
}
}
func TestGracefulReleaseHandsOverImmediately(t *testing.T) {
s, c := NewMemoryStore(), &fakeClock{t: time.Unix(0, 0)}
a, b := defaults(t, "pod-a", s, c), defaults(t, "pod-b", s, c)
a.e.Step(a.ctx)
b.e.Step(b.ctx)
if err := a.e.Release(a.ctx); err != nil {
t.Fatal(err)
}
c.Advance(2 * time.Second)
b.e.Step(b.ctx)
if !b.e.IsLeader() || b.e.Epoch() != 2 {
t.Fatalf("standby did not take over after release: leader=%v epoch=%d", b.e.IsLeader(), b.e.Epoch())
}
}
func TestZombieLeaderIsFenced(t *testing.T) {
s, c := NewMemoryStore(), &fakeClock{t: time.Unix(0, 0)}
res := fencing.NewStore()
a, b := defaults(t, "pod-a", s, c), defaults(t, "pod-b", s, c)
a.e.Step(a.ctx)
b.e.Step(b.ctx)
epochA := a.e.Epoch()
if err := res.Write(epochA, "invoice-run", "started by a"); err != nil {
t.Fatal(err)
}
// a stops the world (GC pause, VM freeze, SIGSTOP): no steps for 40 s.
for i := 0; i < 20; i++ {
c.Advance(2 * time.Second)
b.e.Step(b.ctx)
}
if !b.e.IsLeader() {
t.Fatalf("b should lead")
}
if err := res.Write(b.e.Epoch(), "invoice-run", "taken over by b"); err != nil {
t.Fatal(err)
}
// a wakes up, still believes it leads, and writes with its old epoch.
if !a.e.IsLeader() {
t.Fatalf("a's in-memory flag should still be stale-true before its next Step")
}
err := res.Write(epochA, "invoice-run", "zombie write by a")
if !errors.Is(err, fencing.ErrStaleEpoch) {
t.Fatalf("zombie write was accepted: %v", err)
}
if v, _ := res.Get("invoice-run"); v != "taken over by b" {
t.Fatalf("value %q", v)
}
a.e.Step(a.ctx) // its next renew sees pod-b as holder
if a.e.IsLeader() {
t.Fatalf("a did not step down after seeing the new holder")
}
}The storage side of fencing:
// Package fencing is the storage side of leader election: a resource that
// remembers the highest epoch (fencing token) it has accepted and rejects
// writes that carry a lower one. Election gives you "probably one leader";
// this check is what makes a stale leader harmless.
package fencing
import (
"errors"
"fmt"
"sync"
)
// ErrStaleEpoch is returned to a deposed leader (compare Kafka
// FENCED_LEADER_EPOCH, error code 74).
var ErrStaleEpoch = errors.New("fencing: stale epoch")
// Store is a fenced key-value resource.
type Store struct {
mu sync.Mutex
highest uint64
data map[string]string
log []string
}
func NewStore() *Store { return &Store{data: map[string]string{}} }
// Write applies the write only if epoch >= the highest epoch seen so far.
// The check and the write happen under one lock: in SQL this is a single
// conditional UPDATE, in etcd a Txn with a Compare, never read-then-write.
func (s *Store) Write(epoch uint64, key, value string) error {
s.mu.Lock()
defer s.mu.Unlock()
if epoch < s.highest {
s.log = append(s.log, fmt.Sprintf("reject epoch=%d key=%s (highest %d)", epoch, key, s.highest))
return fmt.Errorf("%w: got %d, highest %d", ErrStaleEpoch, epoch, s.highest)
}
s.highest = epoch
s.data[key] = value
s.log = append(s.log, fmt.Sprintf("accept epoch=%d key=%s value=%s", epoch, key, value))
return nil
}
// Get returns a value and whether it exists.
func (s *Store) Get(key string) (string, bool) {
s.mu.Lock()
defer s.mu.Unlock()
v, ok := s.data[key]
return v, ok
}
// Log returns the decision log (accept/reject lines).
func (s *Store) Log() []string {
s.mu.Lock()
defer s.mu.Unlock()
return append([]string(nil), s.log...)
}package fencing
import (
"errors"
"testing"
)
func TestHigherEpochWinsLowerIsRejected(t *testing.T) {
s := NewStore()
steps := []struct {
epoch uint64
ok bool
}{{7, true}, {7, true}, {8, true}, {7, false}, {9, true}, {8, false}}
for i, st := range steps {
err := s.Write(st.epoch, "k", "v")
if st.ok != (err == nil) || (!st.ok && !errors.Is(err, ErrStaleEpoch)) {
t.Fatalf("step %d epoch %d: err=%v", i, st.epoch, err)
}
}
if len(s.Log()) != len(steps) {
t.Fatalf("log %v", s.Log())
}
}Kubernetes: client-go leaderelection with a LeaseLock, and leaseTransitions as the epoch:
// Package kubelease runs a controller-style singleton with client-go's
// leaderelection package and a coordination.k8s.io/v1 Lease. It compiles
// without a cluster; run it in a Pod with a ServiceAccount allowed to get,
// create and update leases in its namespace.
//
// client-go "does not guarantee that only one client is acting as a leader
// (a.k.a. fencing)", so the work function fences its own writes with the
// Lease's spec.leaseTransitions, read right after acquiring.
package kubelease
import (
"context"
"fmt"
"log/slog"
"os"
"time"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/leaderelection"
"k8s.io/client-go/tools/leaderelection/resourcelock"
)
// FencedWork is the leader's job; every write it makes must carry epoch and
// the storage must reject epochs lower than the highest it has seen.
type FencedWork func(ctx context.Context, epoch int64) error
// Run blocks until ctx is cancelled or leadership is lost. Losing the lease
// exits the process: a fresh process is the simplest way to be sure no
// goroutine of the old leader keeps working.
func Run(ctx context.Context, namespace, name string, work FencedWork) error {
cfg, err := rest.InClusterConfig()
if err != nil {
return fmt.Errorf("in-cluster config: %w", err)
}
client := kubernetes.NewForConfigOrDie(cfg)
// Holder identity must be unique per process: Pod name plus a random
// suffix survives a restart of the same Pod name.
id, _ := os.Hostname()
id = fmt.Sprintf("%s_%d", id, time.Now().UnixNano())
lock := &resourcelock.LeaseLock{
LeaseMeta: metav1.ObjectMeta{Name: name, Namespace: namespace},
Client: client.CoordinationV1(),
LockConfig: resourcelock.ResourceLockConfig{Identity: id},
}
leaderelection.RunOrDie(ctx, leaderelection.LeaderElectionConfig{
Lock: lock,
LeaseDuration: 15 * time.Second, // the core-component defaults
RenewDeadline: 10 * time.Second,
RetryPeriod: 2 * time.Second,
ReleaseOnCancel: true, // graceful hand-off on SIGTERM; work must stop first
Name: name,
Callbacks: leaderelection.LeaderCallbacks{
OnStartedLeading: func(ctx context.Context) {
lease, err := client.CoordinationV1().Leases(namespace).Get(ctx, name, metav1.GetOptions{})
if err != nil || lease.Spec.LeaseTransitions == nil || lease.Spec.HolderIdentity == nil || *lease.Spec.HolderIdentity != id {
slog.Error("cannot read epoch, refusing to work", "err", err)
os.Exit(1)
}
epoch := int64(*lease.Spec.LeaseTransitions)
slog.Info("started leading", "identity", id, "epoch", epoch)
if err := work(ctx, epoch); err != nil && ctx.Err() == nil {
slog.Error("leader work failed", "err", err)
os.Exit(1)
}
},
OnStoppedLeading: func() {
// Always called on exit, even if we never led.
slog.Info("stopped leading", "identity", id)
os.Exit(0)
},
OnNewLeader: func(identity string) {
if identity != id {
slog.Info("observed leader", "leader", identity)
}
},
},
})
return nil
}etcd: concurrency.Election with a Txn-guarded write and Rev() as the epoch:
// Package etcdelect elects a leader with etcd's concurrency package
// (go.etcd.io/etcd/client/v3/concurrency) and fences writes in two ways:
//
// - writes that live in etcd itself are wrapped in a Txn whose Compare
// checks that the leader key still exists with our create revision;
// - writes to other systems carry Election.Rev() (the leader key's
// creation revision, strictly increasing across leaders) as the epoch.
//
// It compiles without an etcd cluster.
package etcdelect
import (
"context"
"errors"
"fmt"
"log/slog"
"time"
clientv3 "go.etcd.io/etcd/client/v3"
"go.etcd.io/etcd/client/v3/concurrency"
)
// ErrNotLeader is returned when a guarded write finds that leadership is gone.
var ErrNotLeader = errors.New("etcdelect: leadership lost")
// Leader holds an elected position.
type Leader struct {
cli *clientv3.Client
session *concurrency.Session
election *concurrency.Election
}
// Campaign blocks until this process is leader of prefix or ctx ends. The
// session TTL is the lease length: if this process stops sending keepalives
// for ttlSeconds, etcd deletes the leader key and the next campaigner wins.
func Campaign(ctx context.Context, endpoints []string, prefix, identity string, ttlSeconds int) (*Leader, error) {
cli, err := clientv3.New(clientv3.Config{Endpoints: endpoints, DialTimeout: 5 * time.Second})
if err != nil {
return nil, err
}
s, err := concurrency.NewSession(cli, concurrency.WithTTL(ttlSeconds))
if err != nil {
cli.Close()
return nil, err
}
e := concurrency.NewElection(s, prefix)
if err := e.Campaign(ctx, identity); err != nil {
s.Close()
cli.Close()
return nil, fmt.Errorf("campaign: %w", err)
}
slog.Info("elected", "key", e.Key(), "epoch", e.Rev())
return &Leader{cli: cli, session: s, election: e}, nil
}
// Epoch is the fencing token for writes outside etcd.
func (l *Leader) Epoch() int64 { return l.election.Rev() }
// Lost is closed when the session's lease expires or is revoked.
func (l *Leader) Lost() <-chan struct{} { return l.session.Done() }
// PutIfLeader writes key=value only if our leader key is still the one with
// our create revision: etcd evaluates the Compare and the Put atomically.
func (l *Leader) PutIfLeader(ctx context.Context, key, value string) error {
resp, err := l.cli.Txn(ctx).
If(clientv3.Compare(clientv3.CreateRevision(l.election.Key()), "=", l.election.Rev())).
Then(clientv3.OpPut(key, value)).
Commit()
if err != nil {
return err
}
if !resp.Succeeded {
return ErrNotLeader
}
return nil
}
// Resign hands leadership to the next campaigner at once (graceful
// step-down on deploy) and closes the session.
func (l *Leader) Resign(ctx context.Context) error {
err := l.election.Resign(ctx)
l.session.Close()
l.cli.Close()
return err
}
// Observe streams the current leader's value to followers, e.g. to route
// requests to the leader.
func Observe(ctx context.Context, cli *clientv3.Client, prefix string) (<-chan string, error) {
s, err := concurrency.NewSession(cli)
if err != nil {
return nil, err
}
e := concurrency.NewElection(s, prefix)
out := make(chan string)
go func() {
defer close(out)
defer s.Close()
for resp := range e.Observe(ctx) {
if len(resp.Kvs) > 0 {
out <- string(resp.Kvs[0].Value)
}
}
}()
return out, nil
}PostgreSQL: lease row, fenced writes, per-shard claims with SKIP LOCKED, and an advisory lock for comparison:
-- One row per singleton role. The database clock (now()) is the only clock
-- that decides expiry, so application clock skew does not matter.
CREATE TABLE leader_leases (
name text PRIMARY KEY,
holder text,
epoch bigint NOT NULL DEFAULT 0,
expires_at timestamptz NOT NULL DEFAULT 'epoch',
renewed_at timestamptz
);
-- Resources written by the leader remember the highest epoch they accepted.
CREATE TABLE invoice_runs (
period date PRIMARY KEY,
status text NOT NULL,
fence_epoch bigint NOT NULL DEFAULT 0
);
-- Per-shard leadership: each row is one partition that exactly one worker owns.
CREATE TABLE shard_owners (
shard int PRIMARY KEY,
owner text,
epoch bigint NOT NULL DEFAULT 0,
expires_at timestamptz NOT NULL DEFAULT 'epoch'
);
INSERT INTO shard_owners (shard) SELECT generate_series(0, 63);// Package pglease implements three database-backed leadership patterns on
// PostgreSQL with database/sql (any driver, e.g. github.com/jackc/pgx/v5/stdlib):
//
// 1. a lease row with expiry and an epoch, acquired and renewed by one
// atomic INSERT ... ON CONFLICT DO UPDATE ... WHERE ... RETURNING;
// 2. fenced writes: either a conditional UPDATE on fence_epoch, or a
// transaction that re-checks the lease row FOR SHARE before writing;
// 3. per-shard ownership claimed with FOR UPDATE SKIP LOCKED;
//
// plus a session-level advisory lock for comparison. Schema: schema.sql.
package pglease
import (
"context"
"database/sql"
"errors"
"time"
)
// ErrNotLeader means the lease is held by someone else or has expired.
var ErrNotLeader = errors.New("pglease: not the leader")
// ErrStaleEpoch means a newer leader has already written this resource.
var ErrStaleEpoch = errors.New("pglease: stale epoch")
const acquireOrRenewSQL = `
INSERT INTO leader_leases AS l (name, holder, epoch, expires_at, renewed_at)
VALUES ($1, $2, 1, now() + make_interval(secs => $3), now())
ON CONFLICT (name) DO UPDATE
SET holder = EXCLUDED.holder,
epoch = CASE WHEN l.holder = EXCLUDED.holder AND l.expires_at > now()
THEN l.epoch ELSE l.epoch + 1 END,
expires_at = EXCLUDED.expires_at,
renewed_at = now()
WHERE l.holder = EXCLUDED.holder OR l.holder IS NULL OR l.expires_at <= now()
RETURNING epoch`
// AcquireOrRenew returns the epoch if this holder is (still) the leader.
// A renewal keeps the epoch; a takeover increments it.
func AcquireOrRenew(ctx context.Context, db *sql.DB, name, holder string, ttl time.Duration) (int64, error) {
var epoch int64
err := db.QueryRowContext(ctx, acquireOrRenewSQL, name, holder, ttl.Seconds()).Scan(&epoch)
if errors.Is(err, sql.ErrNoRows) {
return 0, ErrNotLeader // the WHERE filtered the update: someone else holds it
}
return epoch, err
}
// Release ends the lease early so a standby does not wait for expiry.
func Release(ctx context.Context, db *sql.DB, name, holder string, epoch int64) error {
_, err := db.ExecContext(ctx,
`UPDATE leader_leases SET holder = NULL, expires_at = now()
WHERE name = $1 AND holder = $2 AND epoch = $3`, name, holder, epoch)
return err
}
// WriteFenced is the token check in the resource itself: one statement,
// no read-then-write. Use it when the resource lives in another database.
func WriteFenced(ctx context.Context, db *sql.DB, period, status string, epoch int64) error {
res, err := db.ExecContext(ctx, `
INSERT INTO invoice_runs (period, status, fence_epoch) VALUES ($1, $2, $3)
ON CONFLICT (period) DO UPDATE SET status = EXCLUDED.status, fence_epoch = EXCLUDED.fence_epoch
WHERE invoice_runs.fence_epoch <= EXCLUDED.fence_epoch`, period, status, epoch)
if err != nil {
return err
}
if n, _ := res.RowsAffected(); n == 0 {
return ErrStaleEpoch
}
return nil
}
// WriteUnderLease is strict fencing when the lease and the data share one
// database: FOR SHARE on the lease row blocks a takeover until we commit,
// and a missing row means we were deposed.
func WriteUnderLease(ctx context.Context, db *sql.DB, name, holder string, epoch int64, period, status string) error {
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
var ok int
err = tx.QueryRowContext(ctx, `
SELECT 1 FROM leader_leases
WHERE name = $1 AND holder = $2 AND epoch = $3 AND expires_at > now()
FOR SHARE`, name, holder, epoch).Scan(&ok)
if errors.Is(err, sql.ErrNoRows) {
return ErrNotLeader
}
if err != nil {
return err
}
if _, err := tx.ExecContext(ctx, `
INSERT INTO invoice_runs (period, status, fence_epoch) VALUES ($1, $2, $3)
ON CONFLICT (period) DO UPDATE SET status = EXCLUDED.status, fence_epoch = EXCLUDED.fence_epoch`,
period, status, epoch); err != nil {
return err
}
return tx.Commit()
}
// ClaimShard gives this worker one unowned or expired shard. SKIP LOCKED
// lets many workers claim in parallel without waiting on each other.
func ClaimShard(ctx context.Context, db *sql.DB, worker string, ttl time.Duration) (shard int, epoch int64, err error) {
err = db.QueryRowContext(ctx, `
UPDATE shard_owners SET owner = $1, epoch = epoch + 1,
expires_at = now() + make_interval(secs => $2)
WHERE shard = (
SELECT shard FROM shard_owners
WHERE owner IS NULL OR expires_at <= now()
ORDER BY shard
FOR UPDATE SKIP LOCKED
LIMIT 1)
RETURNING shard, epoch`, worker, ttl.Seconds()).Scan(&shard, &epoch)
if errors.Is(err, sql.ErrNoRows) {
return 0, 0, ErrNotLeader
}
return shard, epoch, err
}
// AdvisoryLeader holds a session-level advisory lock on a dedicated
// connection. Leadership lasts as long as that session: no TTL, no epoch.
// It breaks behind PgBouncer in transaction pooling mode, and a leader
// whose connection silently died keeps working until it notices.
func AdvisoryLeader(ctx context.Context, db *sql.DB, key int64) (*sql.Conn, bool, error) {
conn, err := db.Conn(ctx)
if err != nil {
return nil, false, err
}
var got bool
if err := conn.QueryRowContext(ctx, `SELECT pg_try_advisory_lock($1)`, key).Scan(&got); err != nil || !got {
conn.Close()
return nil, false, err
}
return conn, true, nil // keep conn open; pg_advisory_unlock($1) or Close to give up
}The Go angle
| Go feature | Use in leader election | Note |
|---|---|---|
k8s.io/client-go/tools/leaderelection | RunOrDie, NewLeaderElector, LeaderCallbacks, IsLeader, GetLeader | OnStoppedLeading is "always called when the LeaderElector exits, even if it did not start leading" |
k8s.io/client-go/tools/leaderelection/resourcelock | LeaseLock with LeaseMeta, Client, LockConfig.Identity | Endpoints/ConfigMap locks are legacy |
go.etcd.io/etcd/client/v3/concurrency | NewSession, WithTTL, NewElection, Campaign, Resign, Observe, Rev | Session.Done() fires when the lease is lost |
go.etcd.io/raft/v3 | Embed Raft (Config.PreVote, CheckQuorum, ReadOnlyOption) | Only if you are building a replicated system |
context.Context | Cancel the leader's work on loss of leadership | Every leader goroutine must observe it |
time.Time monotonic clock | Local lease timing immune to wall-clock jumps | Not immune to the process being paused |
database/sql + pgx stdlib | Lease rows, advisory locks on a pinned *sql.Conn | Advisory locks need a dedicated connection |
math/rand with a seed | Deterministic simulations | Different seeds explore different interleavings |
log/slog | Structured leader transition logs (identity, epoch) | Same fields in every log line |
Laravel
Before
Scheduler without onOneServer on three servers, withoutOverlapping mistaken for single-server, and an IS_LEADER flag:
<?php
// Before: the same routes/console.php is deployed to three servers, and each
// server's cron runs `php artisan schedule:run` every minute.
use App\Jobs\SyncPartnerCatalog;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Schedule;
// Runs three times every Friday: three reports, three e-mails to the CFO.
Schedule::command('reports:generate')->fridays()->at('17:00');
// withoutOverlapping() only stops a run that overlaps the previous run of
// the same task; it does not stop the other two servers from running it.
Schedule::job(new SyncPartnerCatalog)->everyFiveMinutes()->withoutOverlapping();
// A "singleton" worker started by Supervisor on every server, guarded by an
// environment flag that someone must remember to set on exactly one host.
// When that host dies, nothing takes over.
Artisan::command('billing:worker', function () {
if (env('IS_LEADER') !== 'true') {
return;
}
while (true) {
Artisan::call('billing:run-batch');
sleep(5);
}
});After
Scheduler: useCache('redis'), onOneServer() with withoutOverlapping(), named jobs and closures:
<?php
// After: per-run deduplication with onOneServer for scheduled tasks, and a
// lease-based singleton worker for continuous work.
use App\Jobs\CheckUptime;
use App\Models\User;
use Illuminate\Support\Facades\Schedule;
// The atomic locks live in one central store shared by every server
// (database, memcached, dynamodb or redis cache driver).
Schedule::useCache('redis');
// One server wins the per-minute lock for this run; the others skip it.
Schedule::command('reports:generate')
->fridays()
->at('17:00')
->onOneServer()
->withoutOverlapping(); // and never two runs overlapping in time
// Each permutation needs its own name so each gets its own lock.
Schedule::job(new CheckUptime('https://example.com'))
->name('check_uptime:example.com')
->everyFiveMinutes()
->onOneServer();
// Closures must be named, or they keep running on every server.
Schedule::call(fn () => User::resetApiRequestCount())
->name('reset-api-request-count')
->daily()
->onOneServer();
// Continuous singleton work is not a scheduled task: Supervisor runs
// `php artisan leader:billing` on every server; one leads, the rest wait.The lease: Cache::lock with owner-checked refresh(), a renew deadline on a monotonic clock, and a PostgreSQL epoch:
<?php
namespace App\Leadership;
use Illuminate\Cache\Lock;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Throwable;
/**
* A lease on top of Cache::lock (Redis SET NX EX + owner-checked Lua for
* refresh and release) plus an epoch from PostgreSQL for fencing.
*
* Rules, the same as client-go's leader elector:
* - renew every retry period; refresh() returning false means the lock
* expired or another owner holds it: stop leading at once;
* - if renewals keep failing (Redis unreachable), stop leading after
* renewDeadline seconds, which is shorter than the lock TTL;
* - every write made while leading carries epoch() and is fenced.
*/
final class LeaderLease
{
private ?Lock $lock = null;
private ?int $epoch = null;
private float $lastRenewAt = 0.0;
public function __construct(
private readonly string $name,
private readonly int $ttlSeconds = 15,
private readonly int $renewDeadlineSeconds = 10,
private readonly string $store = 'redis',
) {}
public function isLeading(): bool
{
return $this->lock !== null;
}
public function epoch(): int
{
return $this->epoch ?? throw new NotLeaderException("not leading {$this->name}");
}
public function tryAcquire(): bool
{
// The concrete Illuminate\Cache\Lock (RedisLock, DatabaseLock) has
// refresh(); the Lock contract does not declare it.
$lock = Cache::store($this->store)->lock("leader:{$this->name}", $this->ttlSeconds);
if (! $lock->get()) {
return false;
}
$this->lock = $lock;
$this->lastRenewAt = $this->monotonic();
$this->epoch = $this->bumpEpoch($lock->owner());
Log::info('leader elected', ['role' => $this->name, 'owner' => $lock->owner(), 'epoch' => $this->epoch]);
return true;
}
/**
* Returns false when leadership is lost; the caller must stop working.
*/
public function renew(): bool
{
if ($this->lock === null) {
return false;
}
try {
if ($this->lock->refresh()) {
$this->lastRenewAt = $this->monotonic();
return true;
}
$this->stepDown('lock expired or taken over');
return false;
} catch (Throwable $e) {
// Store unreachable: keep leading only until the renew deadline.
if ($this->monotonic() - $this->lastRenewAt >= $this->renewDeadlineSeconds) {
$this->stepDown('renew deadline exceeded: '.$e->getMessage());
return false;
}
return true;
}
}
/**
* Remaining safe time before the renew deadline; size work batches below it.
*/
public function secondsLeft(): float
{
return max(0.0, $this->renewDeadlineSeconds - ($this->monotonic() - $this->lastRenewAt));
}
/**
* Graceful step-down: the owner-checked release lets a standby take over
* on its next attempt instead of waiting for the TTL.
*/
public function release(): void
{
$this->lock?->release();
$this->stepDown('released');
}
private function stepDown(string $reason): void
{
if ($this->lock !== null) {
Log::warning('leader stepped down', ['role' => $this->name, 'epoch' => $this->epoch, 'reason' => $reason]);
}
$this->lock = null;
$this->epoch = null;
}
/**
* The epoch is ordered by PostgreSQL, not by lock acquisition. If a
* paused process bumps after a newer holder, it gets the higher epoch and
* the other one is fenced; its next refresh() then fails and it steps
* down. Writes stay single-writer either way; only liveness suffers.
*/
private function bumpEpoch(string $owner): int
{
$row = DB::selectOne(
'insert into leader_epochs (name, epoch, holder, updated_at)
values (?, 1, ?, now())
on conflict (name) do update
set epoch = leader_epochs.epoch + 1, holder = excluded.holder, updated_at = now()
returning epoch',
[$this->name, $owner],
);
return (int) $row->epoch;
}
private function monotonic(): float
{
return hrtime(true) / 1e9;
}
}<?php
namespace App\Leadership;
use RuntimeException;
final class NotLeaderException extends RuntimeException {}<?php
namespace App\Leadership;
use RuntimeException;
/**
* A newer leader has already written this resource.
*/
final class StaleEpochException extends RuntimeException {}Fenced, idempotent writes: the cursor update refuses lower epochs in the same statement; invoices are unique per customer and period:
<?php
namespace App\Leadership;
use Illuminate\Support\Facades\DB;
/**
* The storage side of fencing: the billing cursor remembers the highest
* epoch that wrote it and refuses lower ones in the same statement.
*/
final class FencedInvoiceRuns
{
public function cursor(string $period): int
{
return (int) DB::table('invoice_runs')->where('period', $period)->value('last_customer_id');
}
/**
* Invoice a batch and advance the cursor, atomically and fenced.
*
* @param list<array{customer_id: int, amount_cents: int}> $batch
*/
public function invoiceBatch(string $period, array $batch, int $epoch): void
{
DB::transaction(function () use ($period, $batch, $epoch) {
$advanced = DB::affectingStatement(
'insert into invoice_runs (period, last_customer_id, fence_epoch, updated_at)
values (?, ?, ?, now())
on conflict (period) do update
set last_customer_id = excluded.last_customer_id,
fence_epoch = excluded.fence_epoch,
updated_at = now()
where invoice_runs.fence_epoch <= excluded.fence_epoch',
[$period, max(array_column($batch, 'customer_id')), $epoch],
);
if ($advanced === 0) {
// Rolls back the whole batch: nothing from a stale leader lands.
throw new StaleEpochException("epoch {$epoch} is stale for run {$period}");
}
// Idempotent as well as fenced: unique (customer_id, period).
DB::table('invoices')->insertOrIgnore(array_map(fn (array $row) => [
'customer_id' => $row['customer_id'],
'period' => $period,
'amount_cents' => $row['amount_cents'],
'created_by_epoch' => $epoch,
'created_at' => now(),
], $batch));
});
}
}The singleton worker command (Supervisor runs it on every server; one leads, the others are hot standbys; SIGTERM triggers a graceful hand-off):
<?php
namespace App\Console\Commands;
use App\Leadership\FencedInvoiceRuns;
use App\Leadership\LeaderLease;
use App\Leadership\StaleEpochException;
use App\Models\Customer;
use Illuminate\Console\Command;
/**
* Supervisor starts this on every server. Exactly one holds the lease and
* works; the others retry every few seconds as hot standbys.
*/
final class RunBillingLeader extends Command
{
protected $signature = 'leader:billing {period} {--ttl=15} {--renew-deadline=10} {--retry=2}';
protected $description = 'Singleton billing worker with lease renewal and epoch fencing';
private bool $running = true;
public function handle(FencedInvoiceRuns $runs): int
{
$lease = new LeaderLease(
name: 'billing',
ttlSeconds: (int) $this->option('ttl'),
renewDeadlineSeconds: (int) $this->option('renew-deadline'),
);
$retry = (int) $this->option('retry');
$period = (string) $this->argument('period');
// Deploys send SIGTERM: finish the current batch, then hand over.
$this->trap([SIGTERM, SIGINT], fn () => $this->running = false);
while ($this->running) {
if (! $lease->isLeading() && ! $lease->tryAcquire()) {
sleep($retry + random_int(0, $retry)); // jitter: standbys do not stampede
continue;
}
if (! $lease->renew()) {
continue; // lost it: go back to campaigning, do not touch data
}
if ($lease->secondsLeft() < 3) {
continue; // not enough safe time left for a batch
}
$batch = Customer::query()
->where('id', '>', $runs->cursor($period))
->orderBy('id')
->limit(200)
->get(['id', 'monthly_fee_cents'])
->map(fn (Customer $c) => ['customer_id' => $c->id, 'amount_cents' => $c->monthly_fee_cents])
->all();
if ($batch === []) {
sleep($retry);
continue;
}
try {
$runs->invoiceBatch($period, $batch, $lease->epoch());
} catch (StaleEpochException $e) {
$this->warn($e->getMessage());
$lease->release(); // a newer leader exists; stop at once
}
}
$lease->release();
return self::SUCCESS;
}
}<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('leader_epochs', function (Blueprint $table) {
$table->string('name')->primary();
$table->unsignedBigInteger('epoch');
$table->string('holder');
$table->timestampTz('updated_at');
});
Schema::create('invoice_runs', function (Blueprint $table) {
$table->string('period')->primary();
$table->unsignedBigInteger('last_customer_id')->default(0);
$table->unsignedBigInteger('fence_epoch')->default(0);
$table->timestampTz('updated_at');
});
Schema::create('invoices', function (Blueprint $table) {
$table->id();
$table->foreignId('customer_id');
$table->string('period');
$table->unsignedInteger('amount_cents');
$table->unsignedBigInteger('created_by_epoch');
$table->timestampTz('created_at');
$table->unique(['customer_id', 'period']);
});
}
public function down(): void
{
Schema::dropIfExists('invoices');
Schema::dropIfExists('invoice_runs');
Schema::dropIfExists('leader_epochs');
}
};The Laravel angle
| Laravel 13 feature | Behaviour (docs and 13.x source) | Note |
|---|---|---|
->onOneServer() | Per-run lock named from the task's mutex name plus Hi (hour and minute), 3600 s | Dedup per run, not an elected server |
Schedule::alwaysOnOneServer() | Applies onOneServer to every task | Unnamed closures are excluded |
Schedule::useCache('redis') | Store used for the scheduler's atomic locks | Must be shared by every server |
->withoutOverlapping() | CacheEventMutex lock while the task runs | schedule:clear-cache clears stuck locks |
Cache::lock($name, $seconds)->get() | Redis: SET name owner EX seconds NX | Owner is a random string |
$lock->refresh($seconds = null) | Redis: owner-checked Lua; database: UPDATE ... WHERE owner = ? AND expiration > now | The Lock contract does not declare it; the concrete locks do |
$lock->release() / forceRelease() | Owner-checked delete / unconditional delete | Never forceRelease in a leader loop |
Cache::restoreLock($name, $owner) | Re-instantiate a lock in another process | Hand a lock to a queued job |
$this->trap(SIGTERM, ...) | Signal handling in Artisan commands | Graceful step-down |
Horizon MasterSupervisor | One per machine; name = hostname slug + random token | Not a cross-machine leader |
ShouldBeUnique jobs | One pending copy per unique id | Deduplication, not leadership |
DB::affectingStatement() | Returns affected rows for the fenced upsert | 0 rows = stale epoch |
Solving the classic problems
| Problem | Solution | How | Advantage | Cost / limitation |
|---|---|---|---|---|
| Scheduled task runs on every server | onOneServer() / lock per run | Shared cache lock per task and minute | One line in Laravel | Redis failover can duplicate; make the task idempotent |
| Continuous job must run once | Lease-based singleton worker | Acquire, renew every retry period, step down on failure | Automatic failover | Needs fencing and resumable state |
| Deposed leader still writes | Fencing tokens | Epoch on every write, storage rejects lower | Makes zombies harmless | Every resource must support the check |
| Leader change on every GC pause | Longer timeouts, smaller pauses | RenewDeadline above p99.9 pause; tune GC; smaller batches | Fewer false positives | Slower failover |
| Isolated node keeps deposing the leader | Pre-Vote + CheckQuorum | Enable in etcd raft / your product | Stable leader on flapping links | Slightly more messages |
| Deploys cause 15 s gaps | Graceful release | ReleaseOnCancel, Resign, release() after work stops | Hand-off in about one retry period | Must stop work first |
| One leader is a throughput bottleneck | Per-shard leaders | Partition the role; claim shards with SKIP LOCKED or use Kafka partitions | Linear scale-out | Rebalancing and hot shards |
| Leader lost on Redis failover | Use a consensus store or a DB lease | Kubernetes Lease, etcd, PostgreSQL row | Survives failover | One more dependency or more DB load |
| Standby takes long to become useful | Hot standby | Load config, open connections, warm caches before winning | Short effective failover | Resources held by idle replicas |
| Nobody knows who leads | Observability | Log and export identity, epoch, change rate | Faster incident response | A few metrics |
A deposed leader overwrites the new leader's work
The new leader's writes are correct; the old leader wakes up and writes stale results on top. Fix in storage, not in the leader: a conditional update with the epoch.
UPDATE invoice_runs
SET last_customer_id = $2, fence_epoch = $3, updated_at = now()
WHERE period = $1 AND fence_epoch <= $3; -- 0 rows: a newer leader has written; step downIn Go, pglease.WriteFenced returns ErrStaleEpoch; in Laravel, FencedInvoiceRuns::invoiceBatch() throws StaleEpochException and the command releases its lock. For writes to the same database as the lease, pglease.WriteUnderLease locks the lease row FOR SHARE so a takeover waits until the write commits.
Leadership flaps several times an hour
Look at the timeline of leader changes against GC logs, CPU throttling (Kubernetes CPU limits) and API-server or etcd latency. If pauses approach RenewDeadline, either reduce the pauses or raise both RenewDeadline and LeaseDuration (keeping the ratio). For Raft clusters, measure RTT and set --election-timeout to at least ten times it.
The job runs twice after a failover
Leadership hand-off is never perfectly clean. Make the job's effects idempotent: a unique key per (customer, period), an idempotency key on outbound payment calls (API Idempotency), and a persisted cursor so the new leader continues instead of restarting.
Nothing happens after the leader dies
Typical causes: a static IS_LEADER flag; a session advisory lock held by a connection that is half-open (the TCP connection survives on the database side until keepalive gives up); a ZooKeeper or Consul session without a TTL or health check; a lock without expiry (SETNX without PX). Fix: every leadership record must have an expiry tied to liveness, and the database connection must have TCP keepalives or idle_session_timeout set.
The scheduler leader is the only server that runs cron
A design where cron is installed only on "server 1" is static leadership: when that server is replaced, nothing runs. Install the same cron entry on every server and use onOneServer(), or run schedule:work in a singleton worker under a lease.
Two Kubernetes operator replicas fight over resources
Leader election is disabled (--leader-elect=false or LeaderElection: false in controller-runtime) or two deployments use different LeaderElectionIDs. Fix the ID, enable leader election, and set the process to exit in OnStoppedLeading.
Choosing
Which mechanism
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| Running on Kubernetes, controller or singleton service | client-go leaderelection with a Lease | Fence with leaseTransitions; exit on loss | Built in, no extra store |
| You already run etcd | concurrency.Election | Txn Compare(CreateRevision) or Rev() as epoch | Linearizable store, push notifications |
| Java ecosystem with ZooKeeper (Curator) | Ephemeral sequential recipe (Curator LeaderLatch/LeaderSelector) | zxid / znode version as token | Mature recipes |
| HashiCorp stack | Consul session + KV acquire | LockIndex as token; TTL and checks | Integrates with service discovery |
| Monolith or small fleet with PostgreSQL | Lease row with epoch | Fenced UPDATEs, FOR SHARE re-check | No new infrastructure |
| Laravel scheduled tasks | onOneServer() + shared Redis/database cache | Idempotent tasks | One line |
| Laravel continuous singleton | Lease worker (Cache::lock + refresh() + epoch) | Fenced writes, SIGTERM hand-off | Failover in seconds |
| Many shards, each needs an owner | Per-shard claims (SKIP LOCKED) or a partitioned log (Kafka) | Epoch per shard | Scales out |
| Building a replicated database or log | Raft library (go.etcd.io/raft/v3) | Pre-Vote, CheckQuorum, ReadIndex | Leader election is part of consensus |
| "Rarely running twice is fine" (cache warmers) | Redis SET NX PX | Short work units | Cheapest |
| Strict exactly-once side effects (payments) | Any of the above, never alone | Fencing + idempotency keys at the receiver | Election alone cannot guarantee it |
Which timeouts
| Environment | Election timeout / lease | Renew deadline | Retry / heartbeat |
|---|---|---|---|
| etcd in one data center (RTT about 1 ms) | 1000 ms default is generous | n/a | 100 ms |
| etcd across regions (RTT 100-400 ms) | Several seconds (at least 10 x RTT) | n/a | About RTT |
| Kubernetes controllers | 15 s | 10 s | 2 s (defaults) |
| JVM services with long GC | 30-60 s | Half of the lease | 2-5 s |
| Laravel singleton worker | Lock TTL 15-60 s | About two thirds of TTL | 2-5 s |
In architecture: from a single process to a distributed system
Monolith: one process, one database
With one process there is nothing to elect: the process is the leader. The problem appears the day you add a second instance for availability. The simplest correct step is a lease row in the database you already have, with the database clock deciding expiry and the epoch fencing writes. Example: a Laravel monolith moves from one VM to two behind a load balancer; scheduled tasks get onOneServer() with the database cache store, and the nightly export job becomes a lease worker.
Modular monolith: boundaries without the network
Several modules may each own a singleton role (billing run, search reindex, outbox relay). Give each role its own lease name and epoch row, so a slow search reindex never blocks billing leadership. Example: leader_leases rows billing, search-reindex, outbox-relay; each module's worker campaigns independently; the outbox relay's epoch fences its "last relayed id" cursor.
Microservices: every arrow is a decision
Each service that needs a singleton elects inside its own deployment, usually with the Kubernetes Lease. Other services should not need to know who the leader is; if they must send it requests, publish the leader's address (etcd Proclaim/Observe, Consul KV value, a Kubernetes Service selecting the leader Pod via a label the leader sets) through Service Discovery. Example flow: the payments service runs three Pods; the leader Pod runs the settlement loop with epoch 41 and calls the bank API with an idempotency key settlement-2026-11-26; after a failover the epoch-42 leader retries with the same key, and the bank returns the stored result instead of paying twice. Cross-service, election cannot give exactly-once; idempotency at the receiver does (Idempotent Consumers & the Inbox Pattern).
Distributed data: replicas, caches, regions
Inside data systems leadership is per shard and comes from consensus: Kafka partition leaders with leader epochs, CockroachDB leaseholders, TiKV Region leaders, a PostgreSQL primary chosen by Patroni through an etcd lease. Across regions, a single leader adds a cross-region round trip to every write and an election timeout must be several seconds; most designs keep a leader per region for regional data and one global leader only for rare global decisions (inference based on the timeout arithmetic above). Caches must not be the source of leadership: a Redis replica promoted during failover may not have the lock key. Clocks matter only for lease-based reads and lease expiry; terms do not.
Scaling path: 1x, 10x, 100x
| Load | Design | What changes |
|---|---|---|
| 1x (one or two servers) | Lease row in PostgreSQL or onOneServer() | Add fencing columns from day one |
| 10x (a Kubernetes deployment, several singletons) | client-go Leases per role; hot standbys; graceful release | Metrics on leader changes and fenced writes |
| 100x (one leader is a bottleneck) | Per-shard leaders: partitions claimed with SKIP LOCKED, Kafka partitions, or a Raft group per shard | Rebalancing, hot-shard handling, per-shard epochs |
Lab: elections, leases and zombies
- Run the tests (run on the host; all pass):
cd docs/snippets/system-design/leader-election/go
go test ./...
# ok academy/leader-election/fencing
# ok academy/leader-election/lease
# ok academy/leader-election/raftsim
go test -v ./lease/ | grep -- '---'
# --- PASS: TestValidationMatchesClientGo
# --- PASS: TestOneLeaderAndEpochs
# --- PASS: TestCrashedLeaderIsReplacedAfterLeaseDuration
# --- PASS: TestPartitionedLeaderStepsDownBeforeStandbyTakesOver
# --- PASS: TestClockRateSkewBeyondToleranceBreaksSafety
# --- PASS: TestGracefulReleaseHandsOverImmediately
# --- PASS: TestZombieLeaderIsFenced- Run the election simulator (single-process Go program, run on the host; output copied verbatim, 1 tick = 1 ms):
$ go run ./cmd/electionsim
== plain Raft: partition the leader away
-- at t=1200 nodes that believe they lead: [0 1]
t= 195 n1 term=1 candidate timeout 268 ticks, RequestVote to all
t= 200 n1 term=1 LEADER won with 3 of 5 votes
t= 400 network partition [[1] [0 2 3 4]]
t= 543 n0 term=2 candidate timeout 292 ticks, RequestVote to all
t= 549 n0 term=2 LEADER won with 3 of 5 votes
t= 1200 network healed
t= 1202 n1 term=1 step-down heartbeat from n0 in term 2
-- at t=1800 leaders: [0], terms: n0=2 n1=2 n2=2 n3=2 n4=2
-- election safety violations: 0
== Pre-Vote + CheckQuorum: same partition
-- at t=1209 nodes that believe they lead: [4]
t= 195 n1 term=0 pre-vote asks for term 1 without bumping its own
t= 199 n2 term=0 pre-vote asks for term 1 without bumping its own
t= 201 n1 term=1 candidate timeout 226 ticks, RequestVote to all
t= 205 n2 term=1 candidate timeout 195 ticks, RequestVote to all
t= 209 n1 term=1 LEADER won with 3 of 5 votes
t= 409 network partition [[1] [0 2 3 4]]
t= 570 n4 term=2 candidate timeout 281 ticks, RequestVote to all
t= 571 n3 term=2 candidate timeout 165 ticks, RequestVote to all
t= 575 n4 term=2 LEADER won with 3 of 5 votes
t= 658 n1 term=1 step-down check quorum: heard from 1 of 5
t= 1209 network healed
-- at t=1809 leaders: [4], terms: n0=2 n1=2 n2=2 n3=2 n4=2
-- election safety violations: 0What to read in it: in plain Raft two nodes believe they lead for 650 ms (n1 in term 1, n0 in term 2), yet no term ever has two leaders; with CheckQuorum the zombie window shrinks to 83 ms but is still not zero. Change DefaultConfig(42) to other seeds and set ElectionTimeoutMax = ElectionTimeoutMin to watch split votes repeat forever (the TestNoRandomizationMeansSplitVotesForever case).
- Kubernetes Lease (expected, not run; needs a cluster):
kubectl -n kube-system get lease kube-controller-manager -o yaml
# spec:
# acquireTime: "2026-11-26T08:00:01.000000Z"
# holderIdentity: cp-1_5b6f...
# leaseDurationSeconds: 15
# leaseTransitions: 3
# renewTime: "2026-11-26T09:41:12.500000Z"
kubectl -n kube-system get lease -w # watch HOLDER change while you cordon/drain the leader's node- etcd election from two terminals (expected, not run; needs etcd):
terminal 1 terminal 2
1 $ etcdctl elect billing worker-1
2 billing/694d9a1b2c3d4e5f $ etcdctl elect billing worker-2
3 worker-1 (blocks: worker-1 leads)
4 Ctrl-C (resign)
5 billing/694d9a1b2c3d4e7a
6 worker-2- PostgreSQL lease row from two sessions (expected, not run; schema from
pglease/schema.sql):
session A session B
1 INSERT ... ON CONFLICT ... RETURNING epoch; -> 1
2 same statement as 'web-2' -> 0 rows (held)
3 (wait 16 s without renewing)
4 same statement as 'web-2' -> 2
5 UPDATE invoice_runs ... AND fence_epoch <= 1; -> UPDATE 0 after B wrote with epoch 2- Laravel singleton worker on two servers (expected, not run):
server web-1 server web-2
1 php artisan leader:billing 2026-11 php artisan leader:billing 2026-11
2 [INFO] leader elected role=billing epoch=7 (retrying every 2-4 s)
3 kill -STOP <pid> (simulate a 30 s freeze)
4 [INFO] leader elected role=billing epoch=8
5 kill -CONT <pid>
6 epoch 7 is stale for run 2026-11 (keeps invoicing with epoch 8)
7 [WARN] leader stepped down reason=releasedCommon misconceptions
| Belief | Reality |
|---|---|
| Leader election gives exactly one leader | At most one per term or epoch; zombies exist until they learn the new term; fence their writes |
isLeader() before a write is enough | The process can pause between the check and the write; only the storage can check atomically |
| Shorter timeouts = more availability | Faster detection but more false elections; follow broadcastTime ≪ electionTimeout ≪ MTBF |
| Lease expiry timestamps can be compared across machines | Only clock rate is tolerated by client-go, not offset; candidates measure on their own clock |
onOneServer() elects a scheduler leader | It takes a lock per task per minute; any server may run the next run |
| Horizon elects one master for the cluster | One master supervisor per machine; queues coordinate the work |
| A Redis lock is as good as etcd | Async replication can lose it; no ordering token |
| Session advisory locks release when the app dies | They release when the database session ends, possibly much later, and break behind transaction poolers |
| The node with the highest ID or most data wins in Raft | The first to time out with an up-to-date log wins |
| Paxos avoids leaders | Multi-Paxos uses a distinguished proposer |
| Bully is a lightweight Raft | No partition safety; each side elects its own coordinator |
| A single leader cannot scale | Per-shard leaders (Kafka partitions, Raft groups) scale out |
| Release the lock on SIGTERM immediately | Stop the work first, then release; otherwise you create two leaders yourself |
| CheckQuorum removes the need for fencing | It shortens the zombie window; it does not close it |
Cheat sheet
| Topic | What to remember |
|---|---|
| Guarantee | At most one leader per term/epoch, never "exactly one at every instant" |
| Fencing | Epoch on every write; storage rejects lower; atomic with the write |
| Raft election | Random timeout (150-300 ms), term + 1, vote self, RequestVote, majority wins, heartbeats |
| Election restriction | Vote only for a log at least as up to date (last term, then index) |
| Pre-Vote / CheckQuorum | Stop term inflation by rejoining nodes / step down without a majority |
| Leader lease reads | Depend on bounded clock drift; ReadIndex does not |
| client-go defaults | LeaseDuration 15 s, RenewDeadline 10 s, RetryPeriod 2 s, jitter 1.2 |
| client-go safety | Tolerates clock offset, and clock-rate ratio up to LeaseDuration/RenewDeadline |
| etcd | NewSession(WithTTL) (default 60 s), Campaign, Resign, Observe, Rev() as epoch |
| ZooKeeper | Ephemeral sequential znodes, watch the predecessor, zxid epoch |
| Consul | Session + ?acquire=; LockIndex; LockDelay 15 s |
| Database | Lease row with expires_at + epoch, DB clock; SKIP LOCKED per shard; advisory locks need a dedicated session |
| Kafka | Partition leader + leader epoch; FENCED_LEADER_EPOCH 74, NOT_LEADER_OR_FOLLOWER 6; unclean election off by default |
| Laravel | onOneServer() per run; singleton worker = Cache::lock + refresh() + DB epoch + trap(SIGTERM) |
| Hand-off | Stop work, persist, release/resign, exit |
| Testing | Partitions, pauses, crashes, clock skew; check invariants (Jepsen style) |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Why does Raft guarantee at most one leader per term but not at most one node that believes it is leader? Important
Answer
Answer: A candidate needs votes from a majority, and each server votes once per term, so two majorities in one term would share a server that voted twice: impossible. A leader of an older term that is cut off does not receive the newer term until it communicates with someone who has it, so it keeps believing it leads in its own (older) term.
2 — What does randomizing the election timeout buy, and what did the Raft paper measure without it? Good to know
Answer
Answer: It makes it likely that one server times out first and wins before others start, so split votes are rare and short. Without randomness "leader election consistently took longer than 10 seconds" because of repeated split votes; 5 ms of randomness gave a median downtime of 287 ms.
3 — With client-go defaults, how long after a leader crashes does a standby take over, and why can it not be faster? Important
Answer
Answer: About 15 s plus up to one jittered retry period (up to 2.4 s). The standby must see the record unchanged for a full LeaseDuration on its own clock, because it cannot distinguish a crashed leader from a slow one.
4 — Why must RenewDeadline be shorter than LeaseDuration? Must-know
Answer
Answer: So that a leader that cannot renew stops acting before any standby is allowed to take over. The difference is the safety margin (5 s with defaults); the ratio is the tolerated clock-rate difference (1.5x).
5 — A leader checks IsLeader(), then is paused for 40 s, then writes. What prevents damage? Must-know
Answer
Answer: Only fencing: the write carries the old epoch, and the storage, which has already accepted a higher epoch from the new leader, rejects it in the same atomic operation.
6 — What problem does Pre-Vote solve, and what does CheckQuorum solve? Important
Answer
Answer: Pre-Vote stops a node that was isolated (and kept incrementing its term) from deposing a healthy leader when it rejoins. CheckQuorum makes a leader that cannot hear a majority step down after an election timeout, shortening the time a minority-side leader believes it leads.
7 — Name a fencing token source for each: Kubernetes Lease, etcd election, ZooKeeper, Kafka partition, your PostgreSQL lease row. Important
Answer
Answer: spec.leaseTransitions; Election.Rev() (the leader key's create revision); the zxid or znode version; the leader epoch; the epoch column incremented on takeover.
8 — Does onOneServer() make one server the scheduler leader? What does it do instead? Must-know
Answer
Answer: No. Every server runs schedule:run; for each due task the first server to get a cache lock named after the task and the current hour and minute runs it, and the others skip that run.
9 — Why is a session-level PostgreSQL advisory lock a risky leader lock? Important
Answer
Answer: It lasts as long as the database session, not the application's health: a frozen app keeps it, a half-open connection may keep it for a long time, transaction-mode poolers such as PgBouncer break session semantics, and it provides no epoch for fencing.
10 — Why does Kafka scale even though every partition has a single leader? Must-know
Answer
Answer: Leadership is per partition, so leaders are spread over all brokers; a broker failure only moves the leadership of its own partitions, each with a new leader epoch.
11 — Why is the bully algorithm not used in production clusters? Good to know
Answer
Answer: It assumes timeouts reliably mean "dead" and that the network does not partition; under a partition each side elects its own highest ID, which is split brain.
12 — A Laravel singleton worker receives SIGTERM during a deploy. What is the correct order of actions? Must-know
Answer
Answer: Stop starting new batches, let the current fenced batch commit, release the lock (owner-checked), and exit; the standby acquires on its next retry with a higher epoch and continues from the stored cursor.
Glossary
| Term | Meaning |
|---|---|
| Leader election | Choosing one node of a group to hold a role, and choosing again when it fails |
| Single leader | A role with at most one active holder per epoch |
| Split brain | Two or more nodes acting as leader for the same role at once |
| Zombie leader | A deposed leader that has not yet learned it was replaced |
| Fencing | Making a stale leader's actions ineffective by checking a token in the resource |
| Fencing token | Monotonically increasing number attached to each write |
| Epoch | Counter of leadership periods (ZAB, Kafka, your own column) |
| Term | Raft's epoch; a logical clock exchanged on every RPC |
| Leader epoch | Kafka's per-partition leadership counter, stamped on records (KIP-101) |
| Controller epoch | Counter of Kafka controller changes; old controllers get STALE_CONTROLLER_EPOCH |
| zxid | ZooKeeper transaction id: 32-bit epoch + 32-bit counter |
| Raft | Consensus algorithm with leader election, log replication and safety as separate parts |
| Randomized election timeout | Timeout drawn from a range (e.g. 150-300 ms) so one node usually starts first |
| RequestVote | Raft RPC a candidate sends to collect votes |
| Heartbeat | Periodic message from the leader (empty AppendEntries in Raft) that keeps followers from electing |
| Split vote | Election round where no candidate gets a majority |
| Election restriction | A voter only votes for a candidate whose log is at least as up to date |
| Pre-vote | A trial election that does not increment the term |
| CheckQuorum | Leader steps down if it has not heard from a majority for an election timeout |
| Leader lease | A leader serving reads locally for a bounded time, relying on bounded clock drift |
| ReadIndex | Linearizable read confirmed by a quorum heartbeat round |
| Leaseholder | CockroachDB replica that serves reads and proposes writes for a range |
| Paxos | Lamport's consensus protocol with numbered proposals |
| Multi-Paxos | Paxos for a sequence of values with a stable distinguished proposer |
| ZAB | ZooKeeper Atomic Broadcast: leader election + epoch-based broadcast |
| KRaft | Kafka's Raft-based metadata quorum replacing ZooKeeper |
| Lease | A time-limited claim with holder identity, renewed by the holder |
| TTL | Time to live of a lease, session or key |
| Renew | The holder extending its lease before it expires |
| Holder identity | The unique name of the current holder (holderIdentity) |
| Kubernetes Lease | coordination.k8s.io/v1 object used for leader election and node heartbeats |
| client-go leaderelection | Go package implementing Lease-based election (RunOrDie, callbacks) |
| LeaseDuration | How long candidates wait without seeing a change before taking over (default 15 s) |
| RenewDeadline | How long the leader retries renewing before giving up (default 10 s) |
| RetryPeriod | Wait between attempts (default 2 s), jittered by 1.2 |
| ReleaseOnCancel | client-go option to release the Lease when the context is cancelled |
| Coordinated Leader Election | Alpha Kubernetes feature: LeaseCandidate objects and a strategy choose the leader |
| etcd campaign | Election.Campaign: block until this session's key is the oldest under the prefix |
| Resign / Proclaim / Observe | etcd election calls: give up, update the value, watch leaders |
| ZooKeeper ephemeral node | znode deleted automatically when its session ends |
| Herd effect | Every client waking on one change; avoided by watching only the predecessor |
| Consul leader | Client-side election with a session and ?acquire= on a KV key |
| LockIndex | Consul counter of acquisitions of a KV lock |
| LockDelay | Consul delay before a released lock can be re-acquired (15 s default) |
| Bully algorithm | Highest live ID becomes coordinator after Election/Answer/Coordinator messages |
| Ring algorithm | Election message travels around a logical ring; highest ID wins |
| Advisory lock | Application-defined database lock (pg_try_advisory_lock, MySQL GET_LOCK) |
| Lease row | Table row with holder, expires_at and epoch, written with one conditional statement |
| SKIP LOCKED | FOR UPDATE SKIP LOCKED: skip rows locked by others; used for per-shard claims |
| Detection time | Time until standbys conclude the leader is gone |
| False positive | An election triggered while the leader was alive but slow |
| Step-down | A leader voluntarily giving up its role |
| Hot standby | A replica ready to take over immediately, with state loaded |
| Partition leader | Kafka broker leading one partition |
| ISR | Kafka in-sync replicas, the candidates for partition leadership |
| Unclean leader election | Kafka electing a non-ISR replica (unclean.leader.election.enable), risking data loss |
| Raft group | The replicas of one range/Region running their own Raft instance |
| Jepsen | Safety testing library and analyses using partitions, pauses and clock faults |
| onOneServer | Laravel scheduler option: one server per task run, via a shared cache lock |
| Horizon master supervisor | Horizon's per-machine parent process supervising worker supervisors |
| Singleton worker | Long-running process that only acts while holding the leadership lease |
| Cache::lock | Laravel atomic lock with owner, get, block, refresh, release |
| Chubby | Google's Paxos-based lock service used for master election |
References
- Diego Ongaro and John Ousterhout, In Search of an Understandable Consensus Algorithm (Extended Version), 2014, sections 5.1, 5.2, 5.4.1, 5.6, 8, 9.3; The Raft Consensus Algorithm website
- Leslie Lamport, Paxos Made Simple, 2001
- etcd: raft library (go.etcd.io/raft/v3) Config, etcd-io/raft README, Tuning (heartbeat interval, election timeout), Metrics, v3 concurrency API reference, go.etcd.io/etcd/client/v3/concurrency
- Kubernetes: Leases, Lease v1 API reference, Coordinated Leader Election; client-go leaderelection and its v0.33.4 source
- Apache ZooKeeper 3.9: Recipes: Leader Election, Internals (zxid, epochs, ZAB), Administrator's Guide (tickTime, session timeouts)
- HashiCorp, Consul: Application leader election
- Apache Kafka 4.1: Design (replication, ISR, unclean leader election), KRaft operations, Protocol error codes; KIP-101 Leader Epoch, KIP-595 A Raft Protocol for the Metadata Quorum
- Cockroach Labs, Replication Layer (Raft groups, leaseholders, Leader leases); PingCAP, TiDB Architecture (TiKV Regions, PD)
- Martin Kleppmann, How to do distributed locking, 2016 (fencing tokens); Designing Data-Intensive Applications, chapter 8-9 (book)
- Redis, Distributed Locks with Redis
- PostgreSQL: Explicit Locking: Advisory Locks, Advisory Lock Functions, SELECT: the locking clause (SKIP LOCKED)
- Jepsen, About and etcd 3.4.3 analysis, 2020
- Google Research, The Chubby lock service for loosely-coupled distributed systems, 2006
- Wikipedia, Bully algorithm (secondary source for Garcia-Molina 1982)
- Laravel 13: Task Scheduling (onOneServer, withoutOverlapping), Cache: atomic locks, Horizon, Artisan: signal handling
- Laravel 13.x source: CacheSchedulingMutex, CacheEventMutex, Lock, RedisLock, DatabaseLock; Horizon 5.x MasterSupervisor