Skip to main content

โš–๏ธ Why Consensus Is Hard

  • Network messages can be delayed, reordered, or lost.
  • Servers can crash and restart.
  • Without consensus, two servers might think they are the "truth," leading to data divergence.

Raft solves this by electing one leader and having all followers trust it.


๐Ÿ—๏ธ The Core Ideas of Raft

1. Leader Electionโ€‹

  • At any time, one server is the leader, others are followers.
  • Followers start an election if they donโ€™t hear from a leader within a timeout.
  • Votes are requested; the one with the majority becomes leader.
  • Guarantee: only one leader at a time.

2. Log Replicationโ€‹

  • Clients send requests (commands) to the leader.
  • The leader appends the command to its log and replicates it to followers.
  • Once a majority acknowledges, the leader commits the entry.
  • Followers also commit that entry.

โœ… This ensures that all nodes eventually have the same ordered log.


3. Safety Rulesโ€‹

  • Election restriction: Candidates must have the latest log to win leadership.
  • Log matching: If two logs have an entry at the same index and term, theyโ€™re identical before that point.
  • Commitment: Only entries known by a majority are committed.

๐Ÿ”„ Raft States

Each server cycles between 3 roles:

  1. Follower โ†’ passive, just waits for leaderโ€™s messages.
  2. Candidate โ†’ requests votes during election.
  3. Leader โ†’ handles client requests, replicates logs.

๐Ÿ“Š Timeline Example

Initial state: 5 servers, no leader
โ†“
Timeout (no heartbeat received)
โ†“
One follower becomes Candidate, requests votes
โ†“
Majority vote โ†’ Leader elected
โ†“
Client: "SET x=10"
โ†“
Leader appends log [SET x=10], replicates to followers
โ†“
Majority responds OK โ†’ Leader commits entry
โ†“
Followers commit entry โ†’ State is consistent

๐Ÿ› ๏ธ Where Raft Is Used

  • etcd (Kubernetes metadata store)
  • Consul (HashiCorp service discovery)
  • TiKV (Rust-based distributed KV store, uses raft-rs)
  • Databend (uses openraft)

๐ŸŽฏ Key Takeaways

  • Raft = Consensus via Leadership.
  • Only leader talks to clients.
  • Majority (quorum) ensures fault tolerance.
  • Handles crashes, restarts, partitions.
  • Simpler than Paxos, but equally powerful.