Implementing Leader Election

1. Understanding Leader Election Algorithms

AlgorithmMechanismUse
BullyHighest ID winsSmall clusters
RingToken passes around ringLogical ring topology
Lease-basedTTL on lock holderCloud (etcd, ZooKeeper)
Raft / PaxosQuorum vote per termStrongly consistent stores
Random + heartbeatRandomized timeout (Raft)Modern default

2. Implementing Bully Algorithm

StepAction
1Node detects leader failure (no heartbeat)
2Sends ELECTION to higher-ID nodes
3If no response, declares itself COORDINATOR
4If response, waits; loser concedes
CostO(N²) messages worst case

3. Implementing Ring Algorithm

StepAction
1Initiator sends ELECTION with own ID around ring
2Each node appends ID
3Initiator picks max ID, sends COORDINATOR
CostO(N) messages

4. Implementing Lease-Based Leader Election

Example: etcd lease lock

cli, _ := clientv3.New(clientv3.Config{Endpoints: endpoints})
session, _ := concurrency.NewSession(cli, concurrency.WithTTL(10))
election := concurrency.NewElection(session, "/svc/leader")

ctx := context.Background()
if err := election.Campaign(ctx, hostname); err != nil { panic(err) }

// I am leader as long as session is alive
defer election.Resign(ctx)
runLeaderWork(ctx)
PropertyValue
TTL5-30s typical
RenewalKeepalive every TTL/3
FailoverWithin TTL after leader crash

5. Using Consensus for Leader Election

SystemMechanism
RaftTerm + RequestVote
ZooKeeperEphemeral sequential znode; lowest wins
etcdLease + compare-and-swap on key
KubernetesLease object via coordination.k8s.io API

6. Handling Leader Failures

StepAction
DetectHeartbeat / lease expiration
ElectNew leader chosen via algorithm
Fence old leaderIncrement epoch / fencing token
Recover stateNew leader replays log to latest
Resume trafficNotify clients / update routing

7. Implementing Fencing Tokens

PropertyDetail
DefinitionMonotonic id assigned at lock acquisition
UseResource server rejects ops with token < max_seen
SourceLock service version (etcd revision, ZK zxid)

Example: Resource server rejecting stale fencing token

public class StorageServer {
    private long maxToken = 0;

    public synchronized void write(long token, byte[] data) {
        if (token < maxToken) {
            throw new IllegalStateException("Stale leader; rejected");
        }
        maxToken = token;
        persist(data);
    }
}

8. Understanding Split-Brain Prevention

TechniqueDetail
QuorumMajority required to elect / commit
Fencing tokensDetect stale leaders
STONITHHardware/IPMI power-off losers
Witness / arbiterTie-breaker node in 3rd AZ

9. Implementing Leader Heartbeat Mechanisms

AspectTuning
Heartbeat interval50-150ms (Raft default 50ms)
Election timeout10× heartbeat (150-300ms randomized)
Cross-AZ adjustmentIncrease to absorb network jitter
Pre-voteProbe before disrupting (etcd PreVote)

10. Understanding Leader Election Trade-offs

ChoiceTrade
Short timeoutsFast failover; false positives
Long timeoutsStability; longer outages
Strong (Raft) vs leaseStronger guarantees vs simpler ops
No leader (leaderless)Higher availability; conflict resolution overhead