Sub topic 15
The alternative: consensus-based replication with Raft or Paxos
The earlier chapters built a leaderless design. Any replica in a key's preference list can accept a write, quorums tune consistency, and vector clocks expose conflicts that the application resolves. This chapter covers the other main design: replicas agree on one ordered log of operations through a consensus protocol, so no conflicting versions arise.
This chapter assumes you know the quorum arithmetic (R + W > N), the replication and preference-list model, and the CAP and PACELC trade-offs from earlier chapters.
What consensus gives you
Consensus is the problem of getting a group of nodes to agree on a value even when some nodes crash and messages are delayed or lost. Raft and Paxos solve it. Used repeatedly, they let replicas agree on an ordered sequence of commands, the replicated log.
If every replica starts in the same state and applies the same commands in the same order, every replica ends in the same state. This is a replicated state machine. For a key-value store, the commands are put(key, value) and delete(key). Because the log has one order, two writes to the same key are never concurrent. The later log entry wins, so the store needs no vector clocks, siblings, or merge logic.
How Raft works
Raft is the protocol most teams choose today because it was designed to be understandable. A Raft group has an odd number of members, usually 3 or 5. Each member is in one of three roles: leader, follower, or candidate.
Terms and leader election
Time is divided into numbered terms. Each term has at most one leader. A follower that hears nothing from a leader for a randomized election timeout becomes a candidate. It increments the term and asks the others for votes. A node grants at most one vote per term, and only to a candidate whose log is at least as up to date as its own. A candidate that gets votes from a majority becomes leader. The randomized timeout makes split votes rare and quick to resolve.
Log replication and commit
All client writes go to the leader. The leader appends the command to its log, sends it to the followers, and counts acknowledgements. Once a majority of the group has stored the entry, the entry is committed. The leader applies it to its state machine, replies to the client, and tells followers the new commit index so they apply it too.
A majority intersects every other majority. Any future leader must win votes from a majority, so at least one voter holds every committed entry. The up-to-date check on votes then ensures the new leader has all committed entries.
The commit rule in code
The leader tracks, for each member, the highest log index known to be stored there (match_index). The commit index is the highest index stored on a majority. Raft adds one safety rule: a leader only advances the commit index by counting replicas for an entry from its own current term. Older entries become committed indirectly when a newer one commits.
def commit_index(
match_index: list[int],
log_terms: list[int],
current_term: int,
current_commit: int,
) -> int:
"""Return the new commit index for a Raft leader.
match_index: highest replicated log index per member, leader included.
log_terms: term of each log entry; entry i (1-based) is log_terms[i - 1].
"""
majority = len(match_index) // 2 + 1
# The majority-th largest value is stored on at least a majority of members.
candidate = sorted(match_index, reverse=True)[majority - 1]
if candidate > current_commit and log_terms[candidate - 1] == current_term:
return candidate
return current_commit
# Five members; index 3 is on three of them and is from the current term.
print(commit_index([5, 5, 3, 2, 2], [1, 1, 2, 2, 2], 2, 0)) # 3
# Same replication, but entry 3 is from an old term, so it is not committed yet.
print(commit_index([5, 5, 3, 2, 2], [1, 1, 1, 2, 2], 2, 0)) # 0How Paxos relates
Paxos predates Raft and solves the same problem. Single-decree Paxos agrees on one value using proposers, acceptors, and numbered proposals in two phases: prepare/promise, then accept/accepted. Multi-Paxos runs many instances to build a log and usually elects a stable leader to skip the prepare phase. In practice, Multi-Paxos and Raft have similar message patterns and the same majority requirement. Raft specifies leader election, log repair, and membership change completely. Paxos descriptions leave more to the implementer, which is why real Paxos systems differ from each other more than Raft systems do.
Consensus applied to a key-value store
A single Raft group replicates one log, and every write passes through one leader. That does not scale past one machine's throughput. Systems like CockroachDB, TiKV, and Spanner therefore combine partitioning with consensus. They split the key space into ranges. Each range is its own Raft group of typically three or five replicas, with its own leader. Leaders are spread across nodes to balance load. This is often called multi-Raft.
Compare this with the consistent-hash ring. The ring maps a key to a preference list of N nodes. A range map does the same job, but each entry names a consensus group instead of a loose set of replicas. Range splits and moves replace virtual nodes as the way to rebalance.
Reads
Writes are linearizable by construction. Reads need care, because a deposed leader may not know it has been replaced.
- Log reads: send the read through the log like a write. This is correct but slow.
- ReadIndex: the leader records its commit index, confirms with a heartbeat round that a majority still follows it, and then serves the read from its state machine.
- Leader leases: followers promise not to elect a new leader for a lease period. The leader serves reads locally during the lease. This is fast but relies on bounded clock drift.
- Follower reads: faster and local, but they can return stale data unless the client accepts that.
Comparing the two designs
| Dimension | Leaderless quorum (Dynamo style) | Consensus (Raft or Paxos) |
|---|---|---|
| Write path | Any replica can coordinate | Leader orders all writes for a range |
| Consistency | Tunable, eventual by default | Linearizable by default |
| Conflicts | Possible, need vector clocks and resolution | None within a range, one log order |
| Minority partition | Can keep accepting writes with sloppy quorums | Cannot commit writes |
| Node failure | No pause in service | Pause for an election, typically sub-second to seconds |
| Latency | Wait for R or W of N replicas | Wait for the majority, plus a hop to the leader |
| Repair | Read repair, hinted handoff, Merkle trees | The leader replays or snapshots the log to a lagging follower |
| In PACELC terms | PA/EL | PC/EC |
Failure modes and gotchas
- Availability needs a majority. A 3-member group tolerates 1 failure and a 5-member group tolerates 2. Going from 3 to 4 members adds cost but tolerates no more failures, so use odd sizes.
- Leader failure causes a short unavailability window while an election runs. Setting the election timeout too low causes needless elections under load. Setting it too high lengthens outages.
- Cross-region groups pay wide-area latency on every commit, because the majority often includes a distant replica. Systems that span regions place replicas and leaders deliberately.
- Logs grow without bound. Members periodically take a snapshot of the state machine, truncate the log, and send the snapshot to followers that fall too far behind.
- Membership changes are risky. Changing the member set directly can create two disjoint majorities. Raft uses single-server changes or joint consensus to avoid this.
- Disk acknowledgements matter. A member must fsync an entry before acknowledging it. A disk that lies about durability can break the guarantee.
Choosing between them
Choose consensus when correctness of a single copy matters more than availability during a partition: configuration stores, locks, leader election, metadata, financial records, and general-purpose transactional stores. Choose leaderless quorums when the workload demands always-on writes, tolerates stale reads, and has a simple merge rule: shopping carts, session data, counters, and activity feeds.
Exercise
A key-value store has one Raft group of 5 members. Two members are down. A client sends a put and a get to the leader. Can the write commit, and what happens if a third member fails?
Show answer
With two members down, 3 of 5 remain, which is a majority. The leader can still commit writes and serve linearizable reads. If a third member fails, only 2 of 5 remain, which is not a majority. The leader cannot commit new writes, and reads that need a majority confirmation (ReadIndex) also stop. The group becomes unavailable until a third member returns. Unlike a sloppy quorum, no side set of nodes can accept writes in its place.
Exercise
Why does Raft refuse to advance the commit index by counting replicas of an entry from an earlier term, even if that entry is stored on a majority?
Show answer
An entry from an old term that sits on a majority can still be overwritten if a different node with a more up-to-date last entry wins a later election. Committing it could therefore lose acknowledged data. The leader only counts replicas for entries from its own term. Once such an entry is on a majority, all earlier entries in the log are committed along with it.