Skip to the content.

Raft Consensus Algorithm

Overview

Raft is a consensus algorithm designed to manage a replicated log in distributed systems, ensuring that multiple nodes agree on a single sequence of commands.
Raft emphasizes understandability and is widely used in systems like etcd, Consul, and CockroachDB.


1. Key Concepts

Term Description
Leader Node responsible for handling client requests and replicating log entries.
Follower Passive nodes that replicate logs from the leader and respond to requests.
Candidate Node that requests votes to become a leader during elections.
Term Logical time period in Raft, incremented during elections.
Log Entry Client command stored in the replicated log along with the term.
Commit Index Index of the highest log entry known to be committed.
Snapshot Compressed state of the log to avoid replaying long histories.

2. Raft Overview

Raft breaks down consensus into three subproblems:

  1. Leader Election – Selecting a single leader to coordinate log replication.
  2. Log Replication – Ensuring that all followers’ logs match the leader’s log.
  3. Safety – Ensuring that committed entries are never lost or overwritten.

3. Raft Roles and State

3.1 Leader

3.2 Follower

3.3 Candidate


4. Raft Protocol Steps

4.1 Leader Election

  1. Follower timeout triggers election.
  2. Follower becomes candidate, increments current term.
  3. Candidate requests votes from other nodes.
  4. Candidate wins if it gets a majority; otherwise, retries in next term.

4.2 Log Replication

  1. Leader receives a client command and appends it to its log.
  2. Leader sends AppendEntries RPCs to followers.
  3. Followers append entries to their logs.
  4. Once a majority acknowledges, leader marks entries as committed.
  5. Followers update their commit index and apply commands to their state machines.

4.3 Safety


5. Raft Example

Scenario: Cluster with 3 nodes (A, B, C)

  1. A becomes leader in term 5.
  2. Client sends Set(x=10) to A.
  3. A appends entry (term=5, command=Set(x=10)) to its log.
  4. A replicates to B and C.
  5. Once 2/3 nodes (majority) confirm, entry is committed.
  6. Followers apply the entry to their state machine.

6. Advantages of Raft


7. Raft vs Paxos

Feature Raft Paxos
Understandability Easy to understand and implement Conceptually harder
Leader Election Explicit leader No explicit leader (leaderless Paxos)
Log Replication Built-in log replication Focuses on consensus on single values
Performance Efficient with a stable leader Can be slower for repeated proposals
Use Cases etcd, Consul, CockroachDB Chubby, Zookeeper

8. Use Cases


9. Raft Best Practices


10. Summary


References