Back
+20 XP
Concept

Raft Consensus: Leader Election & Term States

Raft breaks distributed consensus into clean, verifiable states. A node begins as a Follower. If heartbeats lapse, it transitions to Candidate, increments its Term, and solicits votes. Winning a strict quorum majority ($\lfloor N/2 \rfloor + 1$) elevates it to Leader 🗳️👑.

python
class RaftElectionNode:
    def __init__(self, node_id, cluster_size):
        self.node_id = node_id
        self.cluster_size = cluster_size
        self.term = 0
        self.state = "FOLLOWER"
        self.voted_for = None

    def handle_vote_request(self, candidate_id, cand_term):
        if cand_term > self.term:
            self.term = cand_term
            self.state = "FOLLOWER"
            self.voted_for = candidate_id
            return True
        return False

node = RaftElectionNode("Node_B", cluster_size=3)
granted = node.handle_vote_request("Node_A", cand_term=1)
print(f"Vote granted to Node A: {granted} 🗳️")

# 40. Raft Consensus: Leader Election & Term States In distributed consensus (etcd, Kubernetes, CockroachDB), split-brain scenarios where two servers both believe they are the write master will corrupt your database beyond recovery 🛑. ```python # The Raft Node Lifecycle: # [Follower] --(election timeout)--> [Candidate] # [Candidate] --(receives majority votes)--> [Leader] # [Candidate] --(discovers newer term)--> [Follower] # [Leader] --(discovers newer term)--> [Follower] ``` ### The Quorum Invariant 1. **Terms as Logical Epochs**: Raft organizes time into discrete arbitrary epochs called **Terms**. Each term has at most one leader. 2. **Strict Majority ($\lfloor N/2 \rfloor + 1$)**: Any two majorities in a cluster of $N$ nodes MUST overlap by at least one node. Because a follower votes at most once per term, two candidates can NEVER both win a majority in the same term 👑. 3. **Randomized Election Timeouts**: Followers wait a randomized timeout (typically 150ms–300ms) before starting an election, preventing split-vote deadlocks where all candidates run at the exact same millisecond. --- ### Interactive Pop-Quiz 🧠 #### What mathematical quorum size is required for a Raft candidate to win an election in a cluster of $N$ nodes? - [ ] A strict majority: $\lfloor N/2 \rfloor + 1$ votes 👑 - [ ] Unanimous approval ($N$ out of $N$ nodes) - [ ] At least 1 vote from any non-partitioned node - [ ] Two-thirds of the nodes rounded down --- ### Practical Challenge 🎯 Implement `RaftNode` with `__init__(node_id, cluster_size)`, `start_election()`, and `vote_for(candidate_id, term)`. Create a 5-node cluster. Node 0 calls `start_election()`, requesting votes from nodes 1 through 4 for term 1. When votes reach strict majority (3), set `state = 'LEADER'`. Print Node 0's final state. <details> <summary>Solution</summary> ```python class RaftNode: def __init__(self, node_id, cluster_size): self.node_id = node_id self.cluster_size = cluster_size self.term = 0 self.state = "FOLLOWER" self.voted_for = None def start_election(self): self.state = "CANDIDATE" self.term += 1 self.voted_for = self.node_id return self.term def vote_for(self, candidate_id, term): if term > self.term: self.term = term self.state = "FOLLOWER" self.voted_for = candidate_id return True return False cluster = [RaftNode(f"N{i}", 5) for i in range(5)] term = cluster[0].start_election() votes = 1 for peer in cluster[1:]: if peer.vote_for("N0", term): votes += 1 majority = (5 // 2) + 1 if votes >= majority: cluster[0].state = "LEADER" print(cluster[0].state) ``` </details>

Checkpoint

What mathematical quorum size is required for a Raft candidate to win an election in a cluster of $N$ nodes? 🧠

Practice

Implement `RaftNode` with `__init__(node_id, cluster_size)`, `start_election()`, and `vote_for(candidate_id, term)`. Create a 5-node cluster. Node 0 calls `start_election()`, requesting votes from nodes 1 through 4 for term 1. When votes reach strict majority (3), set `state = 'LEADER'`. Print Node 0's final state. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks