Consensus & Leader Election

Two Ways to Decide

Imagine you're holding the last Taylor Swift ticket. Alice and Bob both want it, and two servers receive their requests at the same time. Without coordination, you end up selling the same ticket twice, and Ticketmaster isn't thrilled about that.


The Real Question: How to Pick Leaders?


Best of Both Worlds

1. The Key Insight

Use slow consensus occasionally to enable fast leadership constantly.

2. Two-Phase Approach

3. The Result

Fast operations with reliable failover.


Quorum Sizes

Nodes Majority Tolerate Use Case
3 2 1 failure Dev/Test
5 3 2 failures Production
7 4 3 failures Critical

Formula: Majority = ⌊N/2⌋ + 1


Raft: How Machines Elect Leaders


Election Timeline


Key Takeaways

1. Core Problem

Split-brain kills distributed systems. Multiple nodes think they're the leader, leading to data inconsistency and corruption. The solution? Majority voting with more than 50% agreement.

2. The Raft Way

Three states: Follower → Candidate → Leader. An election is triggered by a timeout, with candidates requesting votes from the majority. Recovery time is about 200ms after a failure.