Raft: Understanding Consensus Through Leader Election and Log Replication

10 minute read

In the previous post, we saw why consensus is hard: machines crash, networks delay messages, and a slow node is indistinguishable from a dead one.

Raft is the algorithm most engineers actually meet in practice. It powers etcd (and therefore every Kubernetes cluster), Consul, CockroachDB, TiKV and Kafka’s KRaft controller.

Diego Ongaro and John Ousterhout designed Raft in 2013 with an unusual primary goal: understandability. Paxos had been the standard for decades, but it was notoriously hard to reason about and even harder to implement correctly. Raft provides the same guarantees while breaking the problem into pieces that can be understood separately.

In this article, we’ll walk through those pieces with Go code, then look at what goes wrong in production and how real implementations deal with it.

Raft protocol overview Image courtesy HashiCorp.

1. The goal: a replicated state machine

Raft doesn’t agree on a single value. It agrees on a sequence of commands, a log.

The idea is simple:

  • Every server holds a copy of the log.
  • Every server applies the log’s commands, in order, to a deterministic state machine (for example, a key-value store).
  • If every server has the same log, every server ends up in the same state.

So the entire problem reduces to keeping the logs consistent, even when servers crash and the network misbehaves.

Raft splits that into three sub-problems:

  1. Leader election: choose one server to manage the log.
  2. Log replication: the leader accepts commands and copies them to the others.
  3. Safety: make sure that a committed entry is never lost or overwritten, even across leader changes.

2. Terms and server states

Every server is in one of three states:

  • Follower: passive; responds to requests from leaders and candidates.
  • Candidate: trying to become leader.
  • Leader: handles all client requests and replicates the log.

Time is divided into terms, numbered with consecutive integers. Each term begins with an election, and at most one leader can win a given term.

Terms act as a logical clock. Every message carries the sender’s term, and two rules apply everywhere:

  • If a server sees a higher term, it immediately updates its own term and becomes a follower.
  • If a server receives a request with a lower term, it rejects it.

This is how stale leaders discover they’ve been replaced.

Here’s the state each node keeps:

type State int

const (
    Follower State = iota
    Candidate
    Leader
)

type LogEntry struct {
    Term    uint64
    Command []byte
}

type Node struct {
    mu    sync.Mutex
    id    int
    peers []int
    state State

    // Persistent state: must be on stable storage before
    // responding to any RPC.
    currentTerm uint64
    votedFor    int        // -1 if none
    log         []LogEntry // log[0] is a sentinel with Term 0

    // Volatile state.
    commitIndex   int
    electionReset time.Time

    // Leader-only state, reinitialized after each election.
    nextIndex  map[int]int
    matchIndex map[int]int
}

func (n *Node) becomeFollower(term uint64) {
    n.state = Follower
    n.currentTerm = term
    n.votedFor = -1
    n.persist()
}

func quorum(clusterSize int) int {
    return clusterSize/2 + 1
}

Note the comment on persistent state. currentTerm, votedFor and log must be durably written before a node replies to anyone. If a node votes, crashes, restarts with an empty votedFor and votes again in the same term, two leaders can be elected. Many real-world Raft bugs come down to exactly this kind of missing fsync.

3. Leader election

Leaders send periodic heartbeats (empty AppendEntries messages) to all followers. If a follower hears nothing for an election timeout, it assumes the leader has failed and starts an election.

func randomElectionTimeout() time.Duration {
    return 150*time.Millisecond +
        time.Duration(rand.Int63n(int64(150*time.Millisecond)))
}

The randomization is essential. If every follower used the same timeout, they would all become candidates at once, split the vote, time out together and repeat forever. With randomized timeouts, one node usually times out first and wins before the others even start.

To start an election, a node increments its term, votes for itself and asks every peer for a vote:

func (n *Node) startElection() {
    n.mu.Lock()
    n.state = Candidate
    n.currentTerm++
    n.votedFor = n.id
    n.persist()
    n.electionReset = time.Now()

    term := n.currentTerm
    lastIndex := len(n.log) - 1
    args := RequestVoteArgs{
        Term:         term,
        CandidateID:  n.id,
        LastLogIndex: lastIndex,
        LastLogTerm:  n.log[lastIndex].Term,
    }
    n.mu.Unlock()

    votes := 1 // our own vote; guarded by n.mu below

    for _, peer := range n.peers {
        go func(peer int) {
            reply, err := n.transport.RequestVote(peer, args)
            if err != nil {
                return
            }

            n.mu.Lock()
            defer n.mu.Unlock()

            if reply.Term > n.currentTerm {
                n.becomeFollower(reply.Term)
                return
            }
            // Ignore replies to an election we're no longer running.
            if n.state != Candidate || n.currentTerm != term || !reply.VoteGranted {
                return
            }

            votes++
            if votes == quorum(len(n.peers)+1) {
                n.becomeLeader()
            }
        }(peer)
    }
}

The n.currentTerm != term check matters. RPC replies can arrive late, after the node has already moved on to a newer election. Counting them would be a bug.

On the receiving side, a node grants its vote only if three conditions hold:

func (n *Node) HandleRequestVote(args RequestVoteArgs) RequestVoteReply {
    n.mu.Lock()
    defer n.mu.Unlock()

    if args.Term > n.currentTerm {
        n.becomeFollower(args.Term)
    }

    reply := RequestVoteReply{Term: n.currentTerm}
    if args.Term < n.currentTerm {
        return reply // 1. Stale candidate.
    }

    lastIndex := len(n.log) - 1
    lastTerm := n.log[lastIndex].Term
    candidateUpToDate := args.LastLogTerm > lastTerm ||
        (args.LastLogTerm == lastTerm && args.LastLogIndex >= lastIndex)

    // 2. One vote per term.  3. Candidate's log is at least as up to date as ours.
    if (n.votedFor == -1 || n.votedFor == args.CandidateID) && candidateUpToDate {
        n.votedFor = args.CandidateID
        n.persist()
        n.electionReset = time.Now()
        reply.VoteGranted = true
    }

    return reply
}

The third condition, the election restriction, is easy to overlook and is central to Raft’s safety. We’ll come back to it in section 5.

4. Log replication

Once elected, the leader accepts client commands, appends them to its own log, and replicates them with AppendEntries.

Each AppendEntries request includes the index and term of the entry immediately before the new ones. The follower accepts the new entries only if its log contains a matching entry at that position:

func (n *Node) HandleAppendEntries(args AppendEntriesArgs) AppendEntriesReply {
    n.mu.Lock()
    defer n.mu.Unlock()

    if args.Term > n.currentTerm {
        n.becomeFollower(args.Term)
    }

    reply := AppendEntriesReply{Term: n.currentTerm}
    if args.Term < n.currentTerm {
        return reply // Request from a deposed leader.
    }

    // There is a legitimate leader for this term.
    n.state = Follower
    n.electionReset = time.Now()

    // Consistency check: do our logs agree up to PrevLogIndex?
    if args.PrevLogIndex >= len(n.log) ||
        n.log[args.PrevLogIndex].Term != args.PrevLogTerm {
        return reply // Leader will retry with an earlier index.
    }

    // Append new entries, truncating any conflicting suffix.
    for i, entry := range args.Entries {
        idx := args.PrevLogIndex + 1 + i
        if idx < len(n.log) {
            if n.log[idx].Term == entry.Term {
                continue // Already have it.
            }
            n.log = n.log[:idx] // Conflict: discard it and everything after.
        }
        n.log = append(n.log, args.Entries[i:]...)
        break
    }
    n.persist()

    if args.LeaderCommit > n.commitIndex {
        lastNew := args.PrevLogIndex + len(args.Entries)
        n.commitIndex = min(args.LeaderCommit, lastNew)
    }

    reply.Success = true
    return reply
}

This check gives Raft its Log Matching Property: if two logs contain an entry with the same index and term, the logs are identical up to that point. By induction, a successful AppendEntries proves the follower’s whole log prefix matches the leader’s.

When a follower rejects a request, the leader decrements that follower’s nextIndex and retries further back, until it finds the point where the logs agree. Everything after that point on the follower is overwritten. Production implementations speed this up by having the follower return the conflicting term and its first index, so the leader can skip back a whole term at a time.

5. Commitment and safety

An entry is committed once the leader knows it is stored on a majority of servers. Only committed entries are applied to the state machine and acknowledged to clients.

func (n *Node) advanceCommitIndex() {
    for idx := len(n.log) - 1; idx > n.commitIndex; idx-- {
        // Only entries from the current term are committed by counting replicas.
        if n.log[idx].Term != n.currentTerm {
            break
        }

        count := 1 // the leader itself
        for _, peer := range n.peers {
            if n.matchIndex[peer] >= idx {
                count++
            }
        }

        if count >= quorum(len(n.peers)+1) {
            n.commitIndex = idx
            break
        }
    }
}

That Term != currentTerm check looks odd, and it is one of the subtlest parts of Raft.

An entry from an earlier term can be stored on a majority and still be overwritten later. Section 5.4.2 of the paper shows the sequence: a leader replicates an entry to a majority, crashes before committing it, and a different server with a newer term (but without that entry) wins an election and overwrites it. Being on a majority is not enough if the term is old.

So Raft only commits entries from the leader’s current term by counting. Once one of those is committed, every earlier entry is committed with it, thanks to the Log Matching Property. This is why new leaders immediately append a no-op entry: it lets them commit everything left over from previous terms.

Now the pieces fit together:

  • A committed entry is on a majority.
  • A candidate needs votes from a majority.
  • Those two majorities overlap, and the overlapping voter refuses any candidate whose log is less up to date than its own (the election restriction).

So every new leader already holds every committed entry. Raft calls this the Leader Completeness Property, and it’s the core of the safety argument.

6. What breaks in production

The paper’s core algorithm is correct. Running it on real networks exposes problems the core algorithm doesn’t address.

Stale reads from a deposed leader

A leader cut off in a minority partition can’t commit writes, but it may still think it’s the leader and serve reads from its local state. Those reads can be stale. Solutions:

  • ReadIndex: before serving a read, the leader confirms with a round of heartbeats to a majority that it’s still the leader.
  • Lease reads: the leader serves reads locally while its lease is valid. This is faster, but it depends on bounded clock drift.

etcd supports both, and uses ReadIndex for linearizable reads by default.

Disruptive servers

A node that keeps getting partitioned away keeps timing out, incrementing its term and starting elections. When it rejoins, its high term forces the healthy leader to step down. PreVote fixes this: a node first asks whether it could win before incrementing its term. CheckQuorum makes a leader step down on its own if it can’t reach a majority.

Timeout tuning

Raft needs broadcast time ≪ election timeout ≪ mean time between failures. A slow disk or a long GC pause on the leader can exceed the election timeout and trigger spurious elections. Watch leader-change metrics and disk fsync latency together.

Unbounded logs

Logs grow forever unless they’re compacted. Real implementations periodically snapshot the state machine and truncate the log. They then need an InstallSnapshot RPC for followers that fall too far behind.

Membership changes

Switching directly from an old configuration to a new one can briefly produce two disjoint majorities. Raft handles this with joint consensus, or more commonly by adding or removing one server at a time, which guarantees that old and new majorities always overlap.

7. What this means for production systems

  • Use a battle-tested library. etcd-io/raft and hashicorp/raft are used in production at very large scale. Implementing Raft yourself is a great learning exercise and a risky production decision.
  • Durability is part of correctness. If your storage acknowledges writes before they’re durable, Raft’s guarantees disappear.
  • Decide your read semantics explicitly. Linearizable reads cost a round trip; serializable reads are faster but may be stale.
  • Keep consensus groups small (3 or 5 voters). Scale out by running many groups over partitioned data, not by making one group bigger.

Conclusion

Raft’s success comes from structure. Leader election, log replication and safety can each be understood on their own, and a few precise rules connect them: terms order everything, the log-matching check keeps logs consistent, the election restriction keeps committed entries alive across leader changes, and leaders only commit entries from their own term.

The core algorithm is surprisingly small. The hard engineering lives around it: durability, read semantics, snapshots, membership changes and timeouts tuned to the real behaviour of disks and networks.

What’s next?

Raft gets a group of replicas of the same data to agree. A different problem appears when a single operation must update different systems atomically. We’ll cover that in:

Two Phase Commit Protocol


Further reading:

Comments