How it works
Many jobs need exactly one actor: one process compacting a log, or one scheduler assigning work. Leader election picks that actor, often by having candidates take a lease, a lock that expires unless renewed, from a service backed by a majority. Expiry matters because a crashed holder must not block everyone forever.
Expiry also sets a trap, because a process can be paused at any moment without noticing. Garbage collection, a VM migration, or a stalled disk can freeze it between any two instructions. Say P1 holds a 10-second lease and checks that 2 seconds remain. It then freezes for 15 seconds. The lease expires, and P2 acquires it and writes. P1 wakes, still trusting its check, and writes too, believing it is leader. Checking right before each write does not help, because the pause can fall just after the check. Longer leases only slow failover.
A fencing token closes the hole. Each grant returns a number that only increases, and every write carries it. The storage layer remembers the highest token it has seen and rejects anything lower. P1 got 71 and P2 got 72, so after P2’s write, P1’s write with 71 is refused. The check lives in the resource, which can judge staleness when the paused process cannot. etcd revisions and ZooKeeper’s zxid can serve as tokens.
The resource has to cooperate, storing the highest token and comparing on each write. A third-party API will not do that, so send it an idempotency key derived from the job, which makes a repeat harmless.
A compaction leader writes merged files to S3. After a long VM migration, two leaders uploaded different files under the same key, and readers picked up the stale one. S3 will not compare your tokens for you. What do you change?
Make the stale upload harmless. Each leader writes to a key containing its token, so uploads cannot overwrite each other, then publishes the result by updating a manifest in a store that can compare a token or version, such as your database. Readers follow only the manifest. A stale leader’s manifest update is refused and its file becomes garbage for a later cleanup. The cost is an extra indirection on reads and a cleanup job.
Use this as a guide for self review; written answers are not graded.Keep in mind
- A process cannot rule out a pause, so “I hold the lease” can be false by the time it acts.
- Fencing moves the decision to the resource, which rejects tokens below the highest it has seen.
- Resources that cannot compare tokens need idempotency keys instead.