In this lesson, you will learn how the Raft consensus protocol achieves a replicated state machine through a designated leader and a strictly ordered log.
The Foundation: Leader Election
Raft simplifies the complexity of consensus by electing a single "Leader" who manages the entire replicated log. Every node starts as a Follower. If a follower doesn't hear from a leader within a randomized timeout period, it transitions to a Candidate state and initiates an election by sending RequestVote RPCs to peers.
If the candidate receives votes from a majority (a quorum) of the cluster, it becomes the Leader. This term-based system ensures that at any given time, there is only one leader, preventing "split-brain" scenarios often found in basic replication.
Log Replication
Once a leader is established, it accepts client requests and appends them to its own log as new entries. These entries are initially "uncommitted." The leader then broadcasts AppendEntries RPCs to all followers.
The flow works like this:
- Append: The leader adds the entry to its local log.
- Replicate: The leader sends the entry to followers.
- Commit: Once the leader receives confirmation from a majority of followers, it considers the entry "committed" and applies it to its local state machine.
- Notify: The leader notifies followers that the entry is committed, and they apply it to their state machines as well.
Because Raft ensures that logs only move forward and never overwrite existing entries, it maintains strong consistency. If a follower’s log is inconsistent with the leader’s, the leader forces the follower to duplicate its log by finding the last point where they agreed and overwriting the follower's subsequent entries.
-- Conceptual logic of a log entry
CREATE TABLE RaftLog (
term INT,
index INT,
command TEXT, -- e.g., "SET key=value"
is_committed BOOLEAN
);
By concentrating authority in a single leader, Raft provides a clear, linear path for state updates, making it easier to reason about the consistency of distributed databases compared to more complex algorithms like Paxos.
Key Takeaway: Raft ensures distributed consistency by electing a single leader to serialize log entries, which are then committed only after a majority of the cluster acknowledges them.