Consensus Basics
20 min
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
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).
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).
Why does leader election require a MAJORITY of votes (more than half) rather than just the most votes among candidates?
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.