Lesson 4 of 14

Leader Election

Leader Election

Many distributed systems need a single coordinator — a leader — to make decisions, coordinate writes, or manage state. When the current leader fails, the remaining nodes must elect a new one.

The Bully Algorithm

The Bully Algorithm is one of the simplest election algorithms. Each node has a unique ID. When a node detects that the leader is down, it starts an election by contacting all nodes with higher IDs:

  • If a higher-ID node responds, it takes over the election.
  • If no higher-ID node responds, the current node declares itself leader.

The node with the highest ID always wins — hence "bully."

function bullyElection(nodes, failedLeaderId) {
  // Remove the failed leader
  const alive = nodes.filter(id => id !== failedLeaderId);
  if (alive.length === 0) return null;
  // The highest ID among alive nodes wins
  return Math.max(...alive);
}

The Ring Algorithm

In a ring topology, nodes are arranged in a logical ring. When a node starts an election, it sends an election message around the ring. Each node appends its ID. When the message returns to the initiator, the node with the highest ID is declared leader.

function ringElection(ring, startIdx) {
  // The ring is an array of node IDs in order
  // We simulate: collect all alive IDs and pick the max
  const seen = new Set();
  let maxId = -1;
  for (let i = 0; i < ring.length; i++) {
    const id = ring[(startIdx + i) % ring.length];
    if (!seen.has(id)) {
      seen.add(id);
      maxId = Math.max(maxId, id);
    }
  }
  return maxId;
}

Used By

  • Apache ZooKeeper — uses a leader election protocol based on Paxos.
  • Raft consensus — each term starts with an election; candidates request votes.
  • Kafka — a controller node is elected among brokers.
  • Kubernetes — controller-manager uses leader election via leases.

Your Task

Implement electLeader(nodes, failedId) that takes an array of node IDs and the ID of the failed node, removes the failed node, and returns the highest remaining ID as the new leader. Return null if no nodes remain.

JavaScript loading...
Loading...
Click "Run" to execute your code.