SWE Fundamentals #2: Distributed Consensus — How Raft Decides Safely

Every serious distributed system eventually hits the same wall: you have state that must survive the failure of any single machine, so you replicate it. The moment you replicate it, you face a question that has no casual answer — when two replicas disagree about what happened, who is right? Databases replicate their catalogs, schedulers replicate their task queues, lock services replicate their leases, and every one of them needs a mechanism that lets a cluster of unreliable machines agree on a single, ordered history of operations. That mechanism is distributed consensus, and it is arguably the most consequential algorithmic idea in systems engineering.

This post is the second in the SWE Fundamentals series, and it goes deep on the algorithm you are most likely to run into in practice: Raft. The goal is not to make you a consensus protocol implementer. The goal is a precise mental model of what happens inside a system like etcd or Consul when it elects a leader, replicates a write, and survives a partition — so that when you operate one in production, its behavior stops feeling like magic and starts feeling like arithmetic.

The problem consensus solves

The canonical use case is the replicated state machine. You have a service whose behavior is fully determined by a sequence of operations, and you want N copies of it to stay identical. The trick is to make all replicas execute the same operations in the same order; if they do, they stay in lockstep forever. The hard part is not executing — it is agreeing on that log, even while machines crash, restart with amnesia, and return, and the network delays, reorders, and drops messages.

Two properties define success. Safety: no two replicas ever decide differently on the same log position. Liveness: the cluster keeps making progress despite failures. A classic impossibility result shows you cannot have both, fully deterministically, in a purely asynchronous system where even one process may fail silently. Every practical consensus algorithm threads this needle by introducing timeouts — a dash of synchrony that breaks the deadlock. The price is that liveness is statistical, not guaranteed: under the right sequence of message delays, an election can fail repeatedly. Safety, however, is absolute.

The other failure mode worth naming is split-brain: two partitions of the cluster each believe they are the authority and start accepting divergent writes. If both later merge, one of them has to be wrong. Any correct consensus protocol must make split-brain impossible, not just unlikely.

Majorities: the whole trick in one idea

Raft — like Paxos before it — rests on a single mathematical observation: any two majorities of a cluster intersect. In a five-node cluster, every set of three nodes shares at least one member with every other set of three. This means two disjoint halves of the cluster cannot both gather a majority, so two leaders cannot both be legitimate, so split-brain is structurally impossible. The cluster can therefore survive the loss of a minority: f failures are tolerated with 2f+1 nodes.

This is also why odd cluster sizes are the norm. Three nodes tolerate one failure; five tolerate two; four tolerate only one, because losing two leaves no majority. It is also why consensus clusters belong across failure domains: three nodes in one datacenter behave like one machine with worse availability.

Raft in one picture

Raft organizes everything around terms, monotonically increasing logical epochs. Each term has at most one leader. Time is a sequence of terms; when a leader dies, nodes advance to a new term and hold an election. Terms are the versioning scheme that lets stale nodes recognize they are out of date: any message carrying an old term is rejected on sight.

The algorithm has three moving parts:

  • Leader election: nodes start as followers. If a follower hears nothing from the leader within an election timeout, it becomes a candidate, increments its term, and asks everyone for votes. A candidate that wins a majority becomes leader; the leader then sends heartbeats to suppress new elections.
  • Log replication: all writes flow through the leader. Each client request becomes a log entry; the leader replicates it to followers with AppendEntries; once a majority acknowledges it, the entry is committed and the leader notifies everyone to apply it to their state machine.
  • Safety: a set of rules guaranteeing that committed entries are never lost or contradicted, even across arbitrary leader changes.

Leader election, precisely

Election timeouts are randomized per node — say, 150–300ms — and that randomization is not a detail, it is the liveness mechanism. If every node timed out at exactly the same moment, they would all become candidates, split the vote, and retry in lockstep forever. Random jitter makes one node almost always time out first.

When a follower grants its vote to a candidate, it does so under two constraints, each lasting exactly one term. First, it votes for at most one candidate per term — this is what makes majorities a proof of legitimacy. Second, and more subtly, it only votes for candidates whose logs are at least as up-to-date as its own — comparing by (last log term, last log index), not by length. This is the election restriction, and it is the rule that prevents a node missing recent entries from winning an election and overwriting committed data. A majority always includes at least one node with every committed entry, so any candidate that wins a majority must have them too.

The vote handler is the whole safety argument in 30 lines

The best way to internalize these rules is to implement the voting logic. In Go, a follower’s handling of a RequestVote message looks like this:

type VoteRequest struct {
	Term         int
	CandidateID  int
	LastLogIndex int
	LastLogTerm  int
}

type VoteReply struct {
	Term        int
	VoteGranted bool
}

func (n *Node) handleRequestVote(req VoteRequest) VoteReply {
	reply := VoteReply{Term: n.currentTerm}

	// Stale candidate: reject and educate it about the current term.
	if req.Term < n.currentTerm {
		return reply
	}

	// Newer term: this node is behind. Step down and reset.
	if req.Term > n.currentTerm {
		n.currentTerm = req.Term
		n.votedFor = 0
		n.state = Follower
		reply.Term = req.Term
	}

	logOk := req.LastLogTerm > n.lastLogTerm ||
		(req.LastLogTerm == n.lastLogTerm && req.LastLogIndex >= n.lastLogIndex)

	// One vote per term, and only for an up-to-date log.
	if (n.votedFor == 0 || n.votedFor == req.CandidateID) && logOk {
		n.votedFor = req.CandidateID
		reply.VoteGranted = true
		n.resetElectionTimer()
	}
	return reply
}

Every safety rule from the previous section is visible here. The stale-term check at the top is why old leaders cannot resurrect. The one-vote-per-term check is why two candidates cannot both claim majorities. The logOk comparison is the election restriction that keeps a lagging node from destroying committed history. Notice also what is absent: there is no “prefer the node I like” logic, no tie-breaking by network proximity. The rules are minimal because each one carries a proof obligation.

Replication and the commit rule

Once elected, the leader serves writes by appending entries to its log and replicating them in parallel to followers. Two properties make this converge after leader changes. Log Matching: if two logs contain an entry with the same index and term, everything before that index is identical too. Followers accept an AppendEntries only if their log already has an entry at prevLogIndex with the matching term; otherwise they reject, the leader backs up one entry and retries — eventually discovering the exact point of divergence and overwriting the follower’s stale tail with its own authoritative entries.

An entry becomes committed when the leader stores it on a majority of nodes. Commitment is monotonic: once committed, an entry is in every future leader’s log — the election restriction guarantees it — and will eventually be applied everywhere. Followers learn about commitment indirectly, from the leaderCommit field piggybacked on heartbeats.

There is one genuinely subtle rule hiding in here, and it is the kind of thing that bites people who implement “Raft-like” protocols from scratch. A leader in term 5 cannot commit an entry replicated from term 3 merely by counting replicas. Raft solves this with a deliberately counterintuitive move: a leader may only commit entries from its own current term by counting; older entries get committed as a side effect, when a new-term entry is committed alongside them and drags them over the line. Before committing anything, a newly elected leader therefore appends a no-op entry. If you ever “optimize away” that no-op, you have just reintroduced a data-loss bug.

What consensus does not give you

Raft is a log-replication protocol, and developers routinely overestimate what that buys. Four gaps are worth knowing precisely:

  • Reading from the leader is not automatically linearizable. A newly elected leader might not yet know about entries committed by its predecessor. Production systems handle this with lease-based reads (the leader assumes it holds power for a bounded window) or ReadIndex reads (confirm quorum membership and continued leadership before answering).
  • Consensus is not durability of your application state. The log is safe, but the state machine applying it is yours. If your apply logic has a bug, the protocol will happily feed a perfectly consistent log into a broken machine.
  • Performance is bounded by the quorum round-trip. Every write is one network round trip to a majority, plus the cost of the replicated disk persistence if you require it. This is why consensus-backed stores handle coordination traffic well and bulk data throughput badly.
  • Membership changes are their own protocol. Reconfiguring a cluster safely is where most hand-rolled implementations break. Use a library that ships it.

That last point generalizes into practical advice: use a mature implementation. The official Raft site hosts the specification alongside visualizations that make election and replication dynamics concrete. etcd runs its battle-tested implementation under Kubernetes’ own control plane, hashicorp/raft gives Go applications the library form, and Consul shows the finished pattern: a small consensus core owning coordination metadata, with data planes kept deliberately outside.

Where you already depend on it

Consensus is invisible plumbing under most of the modern stack. Kubernetes’ consistent view of cluster state lives in etcd’s Raft log. CockroachDB and TiKV replicate ranges with Raft variants. Kafka’s KRaft mode replaced ZooKeeper with its own Raft implementation. Distributed lock managers, leader-elected schedulers, replicated message-queue logs — the pattern repeats because the problem repeats: a cluster needs exactly one truth about ordering, and majorities are the only known way to get it without trusting any single machine.

The takeaway hierarchy, in order of importance: majorities are the mechanism, terms are the versioning that makes majorities enforceable, randomized timeouts are the liveness trick, and the election restriction plus the current-term-only commit rule are the two subtleties that separate correct implementations from ones that quietly lose data. If you internalize only those five ideas, you can reason about every consensus-backed system you will ever operate — and the next time a production incident looks like split-brain, you will know exactly which invariant was supposed to prevent it.

Leave a Reply

Your email address will not be published. Required fields are marked *