Coordinate a cluster of identical nodes to agree on which single one performs a singleton-style duty.
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.
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.
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.
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.