Sub topic 1
Why consensus: replicated state machines
Prerequisites
This chapter assumes you know the following:
- Basic distributed systems ideas: nodes, messages, and network partitions.
- Remote procedure calls (a request message and a response message).
- How to read short Python code.
- What an append-only log is: a list where you only add entries at the end.
No Raft knowledge is needed. This chapter explains the problem Raft solves, and later chapters cover the protocol itself.
The problem: one server is a single point of failure
Suppose you run a service that stores state, such as a key-value store, a lock service, or a table of configuration. If it runs on one server, a crash makes it unavailable. If the disk is lost, the data is lost.
The obvious fix is to run several copies. That creates a new problem. The copies must agree on what the state is. If one copy accepts x = 1 and another accepts x = 2 at the same time, clients get different answers depending on which server they ask.
Consensus is the problem of getting a group of servers to agree on a value, or on a sequence of values, even when some servers crash and messages are delayed or lost. Raft is a protocol that solves it.
The replicated state machine model
A state machine is a program that holds some state and changes it by applying commands, one at a time. Here is a small one in Python:
class KeyValueStateMachine:
def __init__(self):
self.data = {}
def apply(self, command):
op, key, *rest = command
if op == "set":
self.data[key] = rest[0]
elif op == "delete":
self.data.pop(key, None)
return self.data.get(key)
log = [("set", "x", 1), ("set", "y", 2), ("delete", "x")]
a = KeyValueStateMachine()
b = KeyValueStateMachine()
for command in log:
a.apply(command)
b.apply(command)
print(a.data == b.data) # True
print(a.data) # {'y': 2}The key property is determinism. Given the same commands in the same order, every copy ends in the same state. So replicating the state reduces to replicating the sequence of commands. That sequence is the log.
Each server in the cluster keeps its own copy of the log and its own state machine. If all servers hold the same log and apply it in order, all servers have the same state. This design is called a replicated state machine.
What the consensus module does
The consensus module is the part of each server that keeps the logs identical. It has three jobs:
- Accept commands from clients.
- Exchange messages with the other servers so that every log holds the same commands in the same order.
- Tell the local state machine when a command is safe to apply.
The state machine itself knows nothing about replication. This separation is useful. You can put any deterministic state machine on top of the same consensus layer.
What "agree" must mean
Consensus protocols are judged against a few properties. A correct protocol for a replicated log must provide these:
- Safety: The servers never return an incorrect result. Once a command is chosen for a position in the log, no server ever applies a different command at that position.
- Availability: The system keeps working as long as a majority of servers are running and can talk to each other.
- Timing independence: Safety must not depend on clocks or on message delays. Slow networks may hurt availability, but they must never cause wrong answers.
The second property depends on majorities. The next chapter covers why a majority is the right threshold.
Why not just copy data to all servers?
A simple scheme is for one server to send every update to the others. It fails in several ways:
| Approach | What goes wrong |
|---|---|
| Clients write to any server | Two servers can accept conflicting updates, and nothing decides which one wins. |
| One fixed primary, no failover | If the primary crashes, the service stops. |
| One primary, manual failover | An operator must pick a new primary, and may pick a stale server that is missing updates. |
| Automatic failover by timeout | A slow primary looks dead. A second primary starts, and now two servers accept writes (split brain). |
The last row is the hard one. A timeout cannot tell a crashed server from a slow one or from one cut off by a partition. A consensus protocol must pick a leader automatically while guaranteeing that two servers never both act as leader and make conflicting decisions.
How Raft approaches the problem
Raft splits consensus into three parts. Each gets its own chapters:
- Leader election: The cluster chooses one leader. Only the leader accepts new commands.
- Log replication: The leader copies its log to the other servers and forces them to match it.
- Safety: Rules that ensure a committed entry is never lost, even across leader changes.
Using a single leader simplifies the problem. Commands flow in one direction, from the leader to the followers, so the leader alone decides the order of entries.
Common mistakes
- Treating replication as consensus. Copying data to several machines does not give agreement. Without a rule for ordering and for choosing a leader, replicas diverge.
- Using non-deterministic commands. If a command reads the local clock or a random number inside
apply, replicas can compute different states from the same log. Resolve such values before the command is put into the log. - Assuming a timeout means a crash. A timeout only means no response arrived. Protocol design must stay safe when this guess is wrong.
Exercise
A replicated state machine applies the log entry ("set", "t", time.time()) by calling time.time() inside apply on each server. What goes wrong, and how do you fix it?
Show answer
Each server reads its own clock at a slightly different moment, so the servers store different values for "t" and their states diverge. The fix is to read the time once, on the leader, before the command enters the log, so the log entry holds a fixed value such as ("set", "t", 1700000000.5). Then apply is deterministic.
Exercise
Why does a timeout-based automatic failover, with no other rule, risk split brain?
Show answer
A timeout cannot distinguish a crashed primary from a slow or partitioned one. If the old primary is only slow or cut off, it keeps accepting writes while the newly promoted primary does too. Two servers then make conflicting decisions. Raft avoids this with terms and majority votes, covered in later chapters.