Skip to solution
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.

Nudge consolestandby

Stuck? Beam a request up — the console returns a conceptual nudge that guides your logic without spoiling the implementation.

03

Study the solution

Step 1: Outline use cases and constraints

Gather requirements and scope the problem. Ask questions to clarify use cases and constraints. Discuss assumptions.

Use cases

We'll scope the problem to handle only the following use cases

  • User needs to understand leader-election to make architecture d

Solution ready — 2 min read

Classified // press E to declassify

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.

Transmission complete // awaiting log

KEEP THE
STREAK ALIVE.

Dossier 47 of 99 decoded in the System Design track. One more won't hurt.

Back to track