Latticework

Command Palette

Search for a command to run...

Distributed Systems Fundamentals

Consensus Basics

20 min

Explanation

When multiple nodes in a distributed system need to agree on something — who's the leader, what the next value in a replicated log is — they run a consensus protocol (Raft, Paxos, and friends all solve this same core problem). The foundation of most of these protocols is majority voting: a candidate only wins if strictly more than half the nodes vote for it, which mathematically guarantees no two different candidates can both win in the same round.

def elect_leader(votes, total_nodes):
    majority = total_nodes // 2 + 1
    for candidate, count in votes.items():
        if count >= majority:
            return candidate
    return None
Try it

A split vote isn't a bug -- it's an expected outcome in real Raft too, and the protocol's answer is simply to time out and hold ANOTHER election round (usually with randomized timers per node so the same split doesn't just repeat forever).

Loading editor…
Exercise

Write `elect_leader(votes, total_nodes)`: `votes` maps candidate ID to vote count. A candidate wins if their count reaches a MAJORITY (`total_nodes // 2 + 1`). Return the winning candidate's ID, or `None` if no candidate has a majority (a split vote).

Quiz

Why does leader election require a MAJORITY of votes (more than half) rather than just the most votes among candidates?

Checkpoint

You can implement majority-vote leader election and understand why a strict majority (not just a plurality) is what prevents two nodes from both believing they're the leader.