hardSystem Design

What is leader election in distributed systems?

1.2k views
01

Understand the problem

Explain leader election.

leader-election
02

Attempt it yourself

Sketch your approach before reading the solution — that's what interviews test.

Stuck? AI Nudge Available

Get a conceptual hint to guide your logic without spoiling the final implementation.

03

Study the solution

The solution is waiting

Give it an honest attempt first — then compare your thinking with the full walkthrough.

04

Read the code

Majority-vote election (simplified)
Run Playground
class Node:
    def __init__(self, node_id):
        self.id = node_id
        self.term = 0
        self.voted_for = None

def elect(nodes, candidate):
    candidate.term += 1                 # start a new election term
    votes = 1                           # candidate votes for itself
    for n in nodes:
        if n is candidate:
            continue
        if n.term < candidate.term:     # grant vote for a newer term
            n.term = candidate.term
            n.voted_for = candidate.id
            votes += 1
    majority = len(nodes) // 2 + 1
    return votes >= majority, votes

nodes = [Node(i) for i in range(5)]
won, votes = elect(nodes, nodes[0])
print("node 0 won?", won, "with", votes, "/", len(nodes), "votes")
05

Join the discussion

Discussion (0)

Sign in to join the discussion.

No responses yet. Be the first to share what you think.