SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
  • Consensus Algorithms
  • Paxos
  • Raft
  • Leader Election
  • ZooKeeper and etcd
  • Distributed Locks
  • Fencing Tokens
  • Gossip Protocol
  • CRDTs
  • Operational Transformation
  • Distributed Unique ID Generation (Snowflake, UUID)
  • Two Generals Problem
  • Byzantine Fault Tolerance (BFT)
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Distributed Systems/Coordination and Consensus

Raft

Consensus made easier to understand: one leader, a replicated log, and elections.

⏱ 16 min readAdvancedMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

Raft is a way for a group of servers to agree on the same list of changes (a log), even when some servers crash. It was designed to be easier to understand than Paxos.

  • The servers elect one leader. Only the leader accepts new changes from clients.
  • The leader copies each change to the others. Once a majority has it, the change is committed and cannot be lost.
  • If the leader dies, the followers hold a new election. The cluster works as long as a majority of servers is alive.

02Concept: What is it?

Imagine three or five database servers that must all hold the same data. If two clients send different changes to different servers at the same moment, the copies would disagree. Raft solves this by making sure every server applies the same changes in the same order. This idea is called a replicated state machine.

Raft splits the hard problem into three smaller ones: leader election (who is in charge?), log replication (how does the leader share changes?) and safety (how do we never lose a committed change?).

Every server is always in one of three roles: follower (passive, answers the leader), candidate (asking for votes) or leader (sends changes and heartbeats). Time is cut into numbered terms. A term has at most one leader. A higher term always beats a lower one.

The three roles and how a server moves between them
😴Followerlistens to the leader
→↓no heartbeat: timeout
πŸ™‹Candidateasks for votes
→↓majority of votes
πŸ‘‘Leadersends changes + heartbeats
Candidate loses or sees a higher term: back to follower Leader sees a higher term: steps down
Most of the time the cluster sits happily in the leader and follower roles.
🧠Majority is the magic number
With 5 servers a majority is 3. Any two majorities share at least one server. That shared server is how a new leader always learns about every committed change.

03Real-Life Example

🍡A Class Teacher and the Class Notebook
A class of five students keeps one shared notebook of rules. Each student has a copy. The class picks one teacher's helper (the leader). Only the helper writes a new line. The helper reads the line aloud and says "write it down". Once at least three students answer "done", the line is official. If the helper goes home sick, the room goes quiet. After a few seconds one student says "I will be the helper, vote for me". A student only votes for someone whose notebook is at least as complete as their own. So the new helper never has an older notebook than the official one.
Class notebook
Raft
The helper who writes the lines
The leader
The other students with copies
Followers
Each line in the notebook
A log entry
Three or more students said done
Entry is committed (a majority has it)
The helper calls out every few seconds
Heartbeat
Silence for too long, a student volunteers
Election timeout, a candidate starts
Only vote for a notebook that is at least as complete
The log up-to-date check
The school year number
The term
How one change travels
πŸ“±Clientset x = 5
→↓1. send
πŸ‘‘Leader2. append to its log
→↓3. copy
πŸ–₯️Followers4. append, reply
→↓5. majority: commit
βœ…Reply OKto the client

04Why Do We Need It?

🀝Agreement
Several machines act as one reliable machine. Everyone applies the same changes in the same order.
πŸ›‘οΈSurvives crashes
A cluster of 2f + 1 servers keeps working when f of them fail. Five servers can lose two.
🧠Easy to understand
One leader, simple rules and clear roles. Teams can build and debug it with less pain than Paxos.
πŸ“’No lost commits
A committed entry is on a majority, and only servers that have it can win an election.
⚑Fast normal path
With a stable leader, a write is one round trip to a majority.
🧩A solid building block
Use it for config stores, locks, leader election and metadata that must never be wrong.
Raft turns a group of unreliable machines into one reliable log, as long as most of them are alive.

05Where Do We Use It?

πŸ—‚οΈetcd
The store behind Kubernetes keeps all cluster state with Raft.
πŸ”Consul
Service discovery and configuration use Raft for their servers.
πŸͺCockroachDB, TiDB, YugabyteDB
Each data range is a small Raft group that keeps its copies the same.
πŸ“¨Kafka (KRaft)
Newer Kafka versions keep their metadata with a Raft-based controller instead of ZooKeeper.
🧾RabbitMQ quorum queues
Replicated queues use Raft to stay in sync.
🧭Vault integrated storage
HashiCorp Vault can store its data in a Raft cluster.

06Types / Parts / How It Works

The three parts of Raft

Raft is easier because it is split up
1. Leader election
⏱️Election timeoutrandom, about 150 to 300 ms
πŸ—³οΈOne vote per termmajority wins
2. Log replication
βž•AppendEntriesleader sends new entries
πŸ’“Heartbeatsempty AppendEntries
3. Safety
πŸ“Up-to-date vote ruleonly fresher logs win
πŸ”’Commit rulecurrent-term entry on a majority
Each part has its own simple rules.

Leader election

  1. A follower hears no heartbeat before its election timeout. The timeout is random, so usually one server fires first.
  2. It adds 1 to its term, votes for itself and asks the others for votes.
  3. A server votes once per term, and only if the candidate's log is at least as up to date as its own.
  4. With votes from a majority, the candidate becomes leader and starts sending heartbeats. If votes split, the timeouts are random, so the next round usually works.

Log replication

StepWhat happensWhy
AppendThe leader adds the command to its own log with the current termThe leader decides the order
ReplicateIt sends AppendEntries to followers. Each follower checks that its previous entry matchesA mismatch means the logs differ, so the leader backs up and fixes it
CommitWhen a majority stores the entry, the leader marks it committedA majority can never be forgotten by a future leader
ApplyEach server applies committed entries to its state machine in orderAll servers end in the same state
Tell the clientThe leader replies after commitThe client knows the change is safe

Raft or Paxos?

RaftPaxos
Main ideaStrong leader and a replicated logAgree on one value at a time, leader is optional
UnderstandingBuilt to be teachableFamously hard to follow
Full systemThe paper describes the whole thing, including membership changesBasic Paxos leaves out much. Multi-Paxos is under-specified
Use in practiceetcd, Consul, CockroachDB, TiKVGoogle Chubby and Spanner (Multi-Paxos styles)
VisualizerA five-server Raft cluster: crash, elect and commitCrash the leader, then fire the election timer on a follower. Crash three servers and try to write. Restore an old server and see which servers are allowed to win.
Selected server
S1leaderterm 1
11
S2followerterm 1
11
S3followerterm 1
11
S4followerterm 1
11
S5followerterm 1
11

Each square is a log entry and the number is the term it was written in. Solid = committed (on a majority). Dashed = not committed yet.

Leader
S1
Current term
1
Servers up
5 / 5
majority = 3
Committed
2
log entries
Five servers, S1 is the leader in term 1. Try: crash the leader, time out another server, then send writes. Crash 3 servers and see what stops.

A simplified model: messages arrive instantly and election timers are fired by you (real servers use random timers of about 150 to 300 ms). The rules for voting, terms and commits follow the Raft paper.

07How to Use It / Steps / Implementation

Using Raft the sensible way

  1. 1
    Use a library or a product
    Writing Raft yourself is very hard to get right. Use etcd, Consul, or a tested library (for example hashicorp/raft or etcd/raft).
  2. 2
    Use an odd number of servers
    3 or 5 is typical. 3 servers tolerate 1 failure. 5 tolerate 2. Four servers still tolerate only 1, so the fourth adds cost with no extra safety.
  3. 3
    Spread them across failure zones
    Put the servers in different racks or availability zones, so one outage does not remove the majority.
  4. 4
    Keep the cluster small
    More servers means more messages and slower commits. Raft is for small control data, not for big traffic.
  5. 5
    Set timeouts to match your network
    The election timeout must be much larger than the heartbeat and the round-trip time, or you get needless elections.
  6. 6
    Use fast disks
    Every commit needs a durable write (fsync). A slow disk makes the whole cluster slow.
  7. 7
    Read carefully
    A plain read from a follower can be stale. For fresh reads use the leader, with a read index or a leader lease.
  8. 8
    Change membership safely
    Add or remove one server at a time, using the membership feature of your library. Never edit the server list by hand.
πŸ’‘Raft is for coordination, not for bulk data
All writes go through one leader. A single Raft group is a great place for metadata, locks and configuration. For huge data, split it into many small Raft groups (as CockroachDB does) or use other replication.
⚠️Losing the majority stops writes
If 3 of 5 servers are down, the two left cannot elect a leader or commit. Raft chooses consistency over availability (the C in CAP). Plan for that.

08Key Terms to Know

TermMeaning in easy words
Replicated state machineMany servers that apply the same commands in the same order and so end up identical
LogThe ordered list of commands each server keeps
TermA numbered period of time with at most one leader. A higher term wins
LeaderThe one server that accepts client changes and copies them to others
FollowerA passive server that answers the leader and votes
CandidateA server that is asking for votes to become leader
Election timeoutHow long a follower waits without a heartbeat before it starts an election
HeartbeatA regular message from the leader that says it is still alive
AppendEntriesThe message a leader uses to send new log entries (or an empty heartbeat)
Quorum / majorityMore than half of the servers. 3 of 5, or 2 of 3
CommittedAn entry stored on a majority. It will never be lost or changed

09Pros, Cons and Trade-offs

βœ… Pros
  • Easy to understand and teach
  • Strong guarantee: committed data is never lost
  • Clear leader makes the normal path fast and simple
  • Handles crashes and restarts well
  • Many good open-source implementations
⚠️ Cons
  • All writes go through one leader, so it does not scale writes
  • Needs a majority alive, else it stops
  • Slow when servers are far apart (every commit crosses the network)
  • Easy to implement wrongly (edge cases around membership and disks)
  • Does not handle malicious servers (not Byzantine fault tolerant)

Trade-offs

ChoiceWe gainWe lose
More servers (5 instead of 3)Survive more failuresMore messages and slower commits
Short election timeoutFast recovery from a dead leaderFalse elections when the network is slow
Long election timeoutCalm clusterA longer outage when the leader really dies
Read from followersSpread read loadPossibly stale data
Read through the leaderFresh dataMore load on one server
Spread across regionsSurvive a whole region failingEvery write pays the long distance

10Common Problems and Mistakes

Common mistakes

  1. Writing your own Raft. The paper is short, but the details (disk, membership, snapshots) are where bugs hide.
  2. Using two servers. Two servers need both alive for a majority. You get no fault tolerance and two things to break.
  3. Timeouts too tight. A busy server or a slow link causes constant elections and no progress.
  4. Reading from followers and expecting fresh data. A follower may be a little behind.
  5. Putting all servers in one rack or zone. One power failure removes the whole majority.
  6. Skipping fsync for speed. A crash can then lose entries that were already acknowledged.
  7. Storing big blobs in the log. The log and the leader become a bottleneck.

Things to watch

πŸŒ€Leader flapping
Elections happen again and again, often because of slow disks or an overloaded network. Check timeouts first.
πŸ—³οΈSplit votes
Two candidates tie. Random timeouts make the retry succeed, but it costs a moment.
πŸ“¦Log growth
Without snapshots and log compaction, the log grows forever and restarts get slow.
🧟Old leader still thinks it leads
A partitioned old leader cannot commit (no majority), and it steps down on seeing a higher term.

11Real-World Examples

☸️Kubernetes
Every cluster object lives in etcd, a Raft cluster of usually 3 or 5 servers.
πŸͺ³CockroachDB
Data is cut into ranges. Each range is its own Raft group with 3 copies.
πŸ”ŽConsul
Service catalog and key-value data are replicated by Raft among server agents.
🧰TiKV (TiDB)
A storage layer with Raft groups per region of data.
πŸ‡RabbitMQ quorum queues
Queues are replicated by Raft for safety over speed.
πŸ“‘Kafka KRaft
The metadata quorum replaced ZooKeeper in modern Kafka.
πŸ“Note
Raft was introduced by Diego Ongaro and John Ousterhout in 2014 in the paper "In Search of an Understandable Consensus Algorithm".
Mini case: three etcd servers lose one
πŸ‘‘etcd-1leader
πŸ–₯️etcd-2follower
πŸ’€etcd-3down
Commits with 2 of 3 Catches up when it returns
2 of 3 is still a majority, so the cluster keeps working.

12Related Topics to Read Next

Consensus Algorithms→

The family of problems Raft belongs to.

Paxos→

The older, harder algorithm that Raft was made to replace in teaching.

Leader Election→

Part of Raft, and a topic on its own.

Heartbeats→

How followers know the leader is alive.

Split Brain Problem→

The danger that the majority rule of Raft prevents.

CAP Theorem→

Raft picks consistency when the network breaks.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • βœ”What: servers agree on one replicated log, using one leader.
  • βœ”Roles: follower, candidate, leader. Time is split into terms.
  • βœ”Election: no heartbeat, random timeout, ask for votes, majority wins.
  • βœ”Vote rule: vote once per term, only for a log at least as up to date.
  • βœ”Commit: stored on a majority, then applied in order and safe forever.
  • βœ”Size: 3 or 5 servers. 2f + 1 servers survive f failures.
  • βœ”Cost: lose the majority and writes stop (consistency over availability).
  • βœ”One line: β€œOne leader, a log copied to a majority, and a vote rule that never loses a commit.”
← Previous
Paxos
Next β†’
Leader Election