Leader Election in Replication
How replica sets elect a new leader after failure, and what happens to in-flight writes.
Leader Election
When the leader (master) crashes, the replicas must choose a new leader. That process is called leader election.
The new leader must be: 1. Alive 2. Most up-to-date 3. Accepted by majority = quorum
Rule of Leader Election
A crashes who will become the leader? split brain problem
Minimum number of nodes required to make a decision. In most systems: Quorum = floor(N/2) + 1
The cluster size is still 4. Majority is still calculated from total configured nodes. Majority = floor(4/2) + 1 = 3 But only 3 nodes are alive. So to elect a new leader: A candidate must get 3 votes.
if N = 3 Quorum = floor(N/2) + 1 = 2
leader will be considered in calculation it is crashed
if N = 4 Quorum = floor(N/2) + 1 = 3
if N = 5 Quorum = floor(N/2) + 1 = 3
B can become leader Alive updated - wal C can vote fot B
C and D can become leader Alive not updated but in majority B can vote note - B is updated but definitelty will lose votes
C,D and E can become leader Alive not updated but in majority B can vote note - B is updated but definitelty will lose votes
B and C can become leader Alive updated and in majority
B and C can become leader Alive updated - wal D,E can vote fot B,C
How Election Works
Message | Sent By | Meaning -----------------|---------------|-------------------------------- HEARTBEAT | Leader | "I'm alive, stay calm" VOTE_REQUEST | Candidate | "Please vote for me" VOTE_YES | Follower | "I vote for you" VOTE_NO | Follower | "I already voted for someone else" I_AM_LEADER | New Leader | "Election over, follow me now"
heartbeat - alive
A → B : HEARTBEAT { leader_id: A, term: 5 } - timeout - 300 A → C : HEARTBEAT { leader_id: A, term: 5 } - timeout - 330 A → D : HEARTBEAT { leader_id: A, term: 5 } - timeout - 310
B → C : VOTE_REQUEST { candidate_id: B, term: 6 } B → D : VOTE_REQUEST { candidate_id: B, term: 6 }
B → C : I_AM_LEADER { leader_id: B, term: 6 } B → D : I_AM_LEADER { leader_id: B, term: 6 }
B started the election
A → B : HEARTBEAT { leader_id: A, term: 5 } - timeout - 300 A → C : HEARTBEAT { leader_id: A, term: 5 } - timeout - 300 A → D : HEARTBEAT { leader_id: A, term: 5 } - timeout - 310