Cloud · Scale & Traffic · DWG NO. 040

Leader Election

Coordinate a cluster of identical nodes to agree on which single one performs a singleton-style duty.

TypeScale/Traffic
ScopeA cluster of peer nodes
ComplexityHigh
Common inDistributed schedulers, cluster coordinators, active-passive failover

A cluster needs one coordinator, but any node could crash

A scheduled job (say, "clean up expired records every night") should run exactly once. Running it on every node in a cluster of five would run it five times; hard-coding one specific node as "the leader" means the whole system breaks the moment that node goes down.

Nodes race for a lease; the winner leads until it fails

Every node attempts to acquire a time-bound lease (often backed by a coordination service like ZooKeeper, etcd, or a database row with a lock). Whichever node wins becomes leader and performs the singleton duty, periodically renewing the lease. If it crashes and stops renewing, the lease expires and another node wins it.

Node ANode BNode CLease Store(coordination svc)Node B = leader(lease held)

A minimal time-bound lease election

Each node tries to claim the lease. Only one succeeds while it's held; if the leader stops renewing before it expires, any node can claim it next.

leader-election.js
class LeaseStore {
  #leader = null;
  #expiresAt = 0;

  tryAcquire(nodeId, leaseMs) {
    const now = Date.now();
    if (this.#leader && now < this.#expiresAt && this.#leader !== nodeId) {
      return false; // someone else currently holds the lease
    }
    this.#leader = nodeId;
    this.#expiresAt = now + leaseMs;
    return true;
  }

  currentLeader() { return Date.now() < this.#expiresAt ? this.#leader : null; }
}

const store = new LeaseStore();

console.log(store.tryAcquire("node-A", 1000)); // true — node-A becomes leader
console.log(store.tryAcquire("node-B", 1000)); // false — lease still held by node-A
console.log(store.currentLeader());            // "node-A"

// node-A stops renewing; once the lease naturally expires, node-B can win it.

Trade-offs