What it is
Raft is a consensus algorithm for managing a replicated log, published by Diego Ongaro and John Ousterhout in 2014 ("In Search of an Understandable Consensus Algorithm"). It provides the same guarantees as Multi-Paxos but splits the problem into three parts that are easier to reason about: leader election, log replication and safety. A cluster of 2f + 1 servers keeps working with up to f of them down. Raft is used in etcd (and therefore Kubernetes), Consul, CockroachDB, TiKV, YugabyteDB, Kafka's KRaft metadata quorum, RabbitMQ quorum queues and many others.
Why it exists
State machine replication needs every replica to apply the same commands in the same order. Paxos solves this but is famously hard to understand and to turn into a complete system (membership changes, log compaction, client interaction). Raft was designed for understandability: one strong leader, a log that only flows from leader to followers, and a small number of rules that are easy to check.
How it works
Roles and terms. Each server is a follower, a candidate or the leader. Time is divided into terms, numbered with consecutive integers. Each term begins with an election; if it succeeds, one leader serves the rest of the term. Every message carries the sender's term. A server that sees a higher term adopts it and becomes a follower; a request with a stale term is rejected.
Persistent state. Each server stores currentTerm, votedFor and its log on stable storage before answering any RPC, so a restart cannot make it vote twice in a term or forget acknowledged entries.
Leader election. Followers expect periodic heartbeats (AppendEntries without entries). A follower that hears nothing for its election timeout, chosen at random (the paper uses 150–300 ms), becomes a candidate: it increments its term, votes for itself and sends RequestVote to all others. A server grants at most one vote per term, on a first-come basis, and only to a candidate whose log is at least as up-to-date as its own (see safety). A candidate with votes from a majority becomes leader and immediately sends heartbeats. If the vote splits, candidates time out and try again with new random timeouts. The paper's timing requirement is broadcastTime ≪ electionTimeout ≪ MTBF.
Log replication. The leader appends each client command to its log as an entry (index, term, command) and sends AppendEntries to every follower with the entries, the index and term of the entry just before them (prevLogIndex, prevLogTerm) and its leaderCommit. A follower accepts only if its log contains an entry at prevLogIndex with term prevLogTerm; it deletes any conflicting entries after that point and appends the new ones. Once an entry from the current term is stored on a majority, the leader marks it committed, applies it to its state machine and answers the client. Followers apply entries up to leaderCommit.
Repairing followers. The leader keeps a nextIndex and matchIndex per follower. When a consistency check fails, it decrements nextIndex and retries until the logs match, then overwrites the follower's divergent suffix. A follower that is too far behind (because the leader compacted its log) receives a snapshot via InstallSnapshot. Unanswered RPCs are simply retried.
Safety. The election restriction says a voter denies its vote if its own log is more up-to-date than the candidate's: a higher last term wins, and with equal last terms the longer log wins. Since a committed entry is on a majority and a winner needs a majority of votes, at least one voter holds every committed entry and refuses candidates without it. Hence every leader contains all committed entries (Leader Completeness). A subtle rule completes the picture: a leader only counts replicas to commit entries from its own term; older entries become committed indirectly when a newer entry after them commits. That is why a new leader commonly appends a no-op entry at the start of its term.
Clients. Clients send requests to the leader; a follower rejects them and names the leader it last heard from. Clients attach unique serial numbers to commands so the state machine can discard duplicates of retried requests. For linearizable reads the leader must confirm it is still leader (a heartbeat round to a majority, called ReadIndex in etcd/raft) or rely on a clock-based lease.
Membership changes use joint consensus or, as most implementations do, single-server changes, so the old and new configurations can never form disjoint majorities.
When to use it
- You need a strongly consistent replicated state machine: metadata stores, configuration, lock services, the replication layer of a distributed database.
- Leader election and fencing for a group of processes where correctness matters.
- Through a library: etcd's
raftpackage, HashiCorp'sraft, Apache Ratis, openraft, or by running etcd or Consul rather than embedding Raft yourself.
When not to
- High-volume data where async replication's small risk of losing the latest writes on failover is acceptable and latency matters more.
- Wide-area deployments with clients everywhere: every write pays a round trip from the leader to a majority, so a cluster spread over continents makes every write slow.
- When you can merge concurrent updates (CRDTs) and want the minority side of a partition to keep accepting writes.
Trade-offs
| Choice | You gain | You pay |
|---|---|---|
| Short election timeout | Faster failover after a leader crash | Spurious elections during GC pauses or network jitter, each pausing writes |
| Long election timeout | Stability under jitter | Longer write pause when the leader really fails |
| 5 servers instead of 3 | Survives 2 failures | Commits wait for the 3rd-fastest server; more replication traffic |
| Reads via the leader with ReadIndex | Linearizable reads | A majority round trip per read (batched in practice) |
| Lease-based leader reads | No round trip per read | Correctness depends on bounded clock drift |
| Follower reads | Spreads read load | Possibly stale unless the follower first asks the leader for the commit index |
Alternatives
- Multi-Paxos: the same guarantees; more flexible (for example, no requirement that the leader's log is complete) but harder to implement completely. Used in Spanner and Chubby.
- ZAB: ZooKeeper's protocol, also leader-based with epochs; very similar in spirit to Raft.
- Viewstamped Replication: predates both and shares many ideas with Raft.
- EPaxos and other leaderless variants: lower latency for geo-distributed clients when commands rarely conflict, at a large complexity cost.
- Primary–backup with an external coordinator: simpler data path, with only failover decisions going through consensus.
Failure modes
- Frequent elections: timeouts close to the real network or disk latency, long GC pauses or an overloaded leader cause churn, and every election pauses writes. The Pre-Vote extension (a candidate first checks it could win before incrementing its term) prevents a rejoining partitioned node from disrupting a healthy leader; CheckQuorum makes a leader step down when it cannot hear from a majority.
- Slow disks: commits wait for an fsync on a majority. A slow disk on the leader slows everything; on followers it is masked until too many are slow.
- Losing a majority: the cluster stops accepting writes; it does not lose committed data.
- Stale reads: serving reads from a deposed leader or a follower without ReadIndex or leases returns old data.
- Unbounded log growth: without snapshots and compaction, restarts replay the whole log and new followers take forever to catch up.
In production
etcd's defaults are a 100 ms heartbeat interval and a 1000 ms election timeout, tuned for typical data-centre latency including disk syncs; the etcd docs recommend raising them for high-latency networks. Run three or five members across zones, alert on leader changes and on proposal or commit latency, put the log on fast disks, and snapshot regularly. Clients should retry with idempotency keys, because a timeout does not tell them whether a command was committed. Most teams use Raft through etcd, Consul or a database that embeds it, rather than writing their own.
Common misconceptions
- "The leader waits for every follower." A majority suffices; the rest catch up later.
- "A crashed follower makes the cluster read-only." With five servers, two can be down and writes continue.
- "An old leader in a partition can commit writes." It cannot reach a majority, so nothing it appends commits.
- "The longest log wins the election." The last entry's term is compared first; length only breaks ties.
- "Committed means applied on every server." It means durable on a majority; followers apply when they learn the commit index.
Interview angle
Explain the three pieces: elections with terms and randomised timeouts, replication with AppendEntries and commit on a majority, and the election restriction that keeps committed entries. Be ready to walk through a leader crash (writes pause for roughly an election timeout, clients retry and are redirected) and a partition (the minority side cannot commit; the old leader steps down when it sees a higher term). Mentioning ReadIndex or leases for linearizable reads, Pre-Vote, snapshots and why clusters have 3 or 5 members shows real familiarity.
Model assumptions
This lesson is a scripted illustration, not a simulation: the simulator has no election, term or log model. Every RequestVote, AppendEntries and reply is a packet placed by hand, and each server's term, log and commit index are annotations and role tags. Packet colours stand for message types: request = RequestVote or a client command, ack = vote granted or AppendEntries success, error = vote denied or request rejected, replication = AppendEntries with entries, message = a heartbeat or a redirect hint. Timings are illustrative: 8–9 ms between the client and a server, 10–14 ms between servers, about 1 ms of processing, heartbeats every 50 ms and election timeouts in the paper's 150–300 ms range. Disk syncs, batching, pipelining, snapshots, Pre-Vote and membership changes are not shown.