Network Background
hub Distributed Systems

Who's in Charge?

Leader Election is the process by which a distributed system designates a single "coordinator" node to manage tasks, maintain order, and ensure data consistency across the cluster.

science Bully Algorithm Simulator

Simulates nodes electing a leader based on the highest ID. Click a node to crash/recover it.

Leader
Follower
Candidate
Crashed
ID:1 FOLLOWER
Click to Toggle Crash
ID:2 FOLLOWER
Click to Toggle Crash
ID:3 FOLLOWER
Click to Toggle Crash
ID:4 FOLLOWER
Click to Toggle Crash
ID:5 LEADER
Click to Toggle Crash

Simulation Controls

Event Log

[7:09:12] Node 5 is the new LEADER.
System started...

Why do we need a Leader?

In a distributed system where many computers work together, chaos is the default state. Without a coordinator, you face the "Split-Brain" problem where two parts of a system fight for control, leading to data corruption.

sync

Consistency

The leader acts as the single source of truth for write operations, ensuring all followers have the same data order.

schedule

Coordination

Instead of every node trying to schedule tasks (causing conflicts), the leader assigns work to available nodes.

Real-World Examples

Kubernetes

Kubernetes (etcd)

Uses Raft to elect a leader that manages the entire cluster state.

Kafka

Apache Kafka

Elects a Controller Broker to manage partition leaders and replicas.

MongoDB

MongoDB

Replica Sets elect a Primary node to handle all write operations.

Under the Hood

This is a simplified implementation of the Bully Algorithm. Click on the code lines to understand exactly what's happening at each step.

lightbulb Select a line

Click any line in the code block to see a detailed explanation of its logic.

bully_algorithm.py
class Node:
def __init__(self, node_id, peers):
self.id = node_id
self.peers = peers
self.state = 'FOLLOWER'
def check_leader(self):
if not self.receive_heartbeat():
self.start_election()
def start_election(self):
self.state = 'CANDIDATE'
higher_nodes = [p for p in self.peers if p.id > self.id]
if not higher_nodes:
self.become_leader()
else:
for p in higher_nodes:
p.send_message("ELECTION")
def receive_message(self, type, sender_id):
if type == "ELECTION" and self.id > sender_id:
self.send_message(sender_id, "OK")
self.start_election() # I am bigger, I take over
elif type == "VICTORY":
self.current_leader = sender_id
self.state = 'FOLLOWER'

Algorithm Showdown

sports_mma

Bully Algorithm

  • check Simple to implement.
  • check High ID always wins (Predictable).
  • close Generates lots of traffic (O(N^2)).
  • close "Ping-pong" effect if highest node is unstable.
how_to_vote

Raft Consensus

  • check Extremely robust and safe.
  • check Handles network partitions gracefully.
  • close More complex logic (Terms, Logs).
  • check Industry standard (Kubernetes, etc).