Sub topic 1
Why consensus: replicated state machines
Prerequisites
This chapter assumes you know the following:
- Nodes exchange messages over a network that can delay, drop, or reorder them. A partition is a failure that splits nodes into groups that cannot talk to each other.
- You know what a remote procedure call (RPC) is: a request sent to another machine that returns a response.
- You can read short Python programs.
- You know what an append-only log is: a sequence of records where you only add to the end.
No Raft knowledge is needed. This chapter explains the problem Raft solves. Later chapters cover how Raft solves it.
The problem: one service, many machines
Suppose you run a service that stores configuration values, locks, or account balances. A single server is simple, but when it crashes the service stops. If its disk fails, the data is gone. The usual answer is to run several copies of the service on different machines.
Copies create a new problem. Clients send requests to different machines at the same time. Machines crash halfway through a request. Messages arrive late or out of order. If each copy applies requests in whatever order they arrive, the copies drift apart. One copy says the lock is held by Alice. Another says it is held by Bob. A client that reads from the wrong copy gets a wrong answer.
You want the group of machines to behave like one reliable machine. Consensus is the tool that gives you that. Consensus means that a group of servers agrees on a single value, or on a single sequence of values, even when some servers fail.
State machines and determinism
A state machine is a program with internal state. It takes commands as input, and each command moves it to a new state and may produce a result. A key-value store is a state machine. The state is the map of keys to values. The commands are set, delete, and get.
The important property is determinism. A deterministic state machine produces the same new state and the same result whenever it starts in the same state and receives the same command. If two deterministic state machines start empty and apply the same commands in the same order, they end in the same state.
class KVStateMachine:
def __init__(self):
self.data = {}
def apply(self, command):
op, key, *rest = command
if op == "set":
self.data[key] = rest[0]
return rest[0]
if op == "delete":
return self.data.pop(key, None)
if op == "get":
return self.data.get(key)
raise ValueError(f"unknown op: {op}")
log = [("set", "x", 1), ("set", "y", 2), ("delete", "x"), ("set", "x", 3)]
replica_a = KVStateMachine()
replica_b = KVStateMachine()
for command in log:
replica_a.apply(command)
replica_b.apply(command)
print(replica_a.data == replica_b.data, replica_a.data)This prints True {'y': 2, 'x': 3}. The two replicas never talked to each other. They agree because they applied the same commands in the same order.
Order matters. Two commands that touch the same key give different results when swapped:
first = KVStateMachine()
second = KVStateMachine()
for command in [("set", "x", 1), ("set", "x", 2)]:
first.apply(command)
for command in [("set", "x", 2), ("set", "x", 1)]:
second.apply(command)
print(first.data, second.data)This prints {'x': 2} {'x': 1}. The same two commands produced two different states. Replicating the commands is not enough. All replicas must agree on the order.
The replicated log
This observation gives the standard design, called the replicated state machine approach:
- Each server keeps a log, which is an ordered list of commands.
- Each server runs its own copy of the state machine.
- A consensus module on each server makes sure that all logs hold the same commands in the same order.
- Each server feeds its log, in order, into its state machine.
The state machine does not need to know anything about distribution. It only needs to be deterministic. All the difficulty lives in the consensus module, which is the part Raft defines.
A client does not get an answer as soon as its command is written to one log. The server answers only after the command is committed. A committed entry is one that the cluster has agreed on and that will not be lost or reordered, even if servers crash. The server then applies the entry to the state machine and returns the result. Raft's definition of committed comes later in the tutorial. For now, treat it as "safe to apply."
Keeping commands deterministic
The log must hold commands whose effect is the same on every replica. A command such as "set token to a random number" breaks this rule if each replica picks its own random number. Reading the local clock, generating IDs, or depending on the iteration order of an unordered collection cause the same trouble.
The fix is to resolve nondeterminism before the command enters the log. One server picks the random value or timestamp, and the log stores the chosen value.
import random
def make_set_token_command():
# The value is chosen once, here, and then stored in the log.
return ("set", "token", random.randint(0, 10**9))
command = make_set_token_command()
log = [command]
for replica in (KVStateMachine(), KVStateMachine()):
replica.apply(log[0])
print(replica.data)This uses the KVStateMachine class from the earlier example. Both replicas print the same token, because the random choice happened before replication, not during it.
What consensus must guarantee
Consensus protocols are described by safety and liveness properties.
Safety means that nothing bad ever happens. For a replicated log, safety includes these properties:
- Agreement: no two servers apply different commands at the same log position.
- Validity: every committed command was proposed by some client. The protocol does not invent commands.
- Durability of committed entries: once an entry is committed, every future leader and every future state machine state includes it.
Liveness means that something good eventually happens. The cluster keeps making progress, meaning clients get answers, as long as a majority of servers are up and can talk to each other.
The two kinds of properties get different treatment. Safety must hold under every failure: crashes, restarts, message loss, duplication, reordering, and arbitrary delay. Liveness is allowed to depend on timing. If the network is badly behaved, the cluster may stall. It must never give wrong answers while stalled.
There is a reason for this split. The FLP impossibility result shows that in a fully asynchronous network, where message delays have no upper bound, no deterministic protocol can guarantee both safety and termination if even one server may crash. Practical protocols, Raft included, keep safety unconditional and use timeouts and randomness to achieve liveness in practice. You will see that design directly in the election chapters.
The failure model here is crash-recovery. Servers may stop and later restart with their disk contents intact. They do not lie or send corrupted messages. Protection against servers that behave maliciously needs a different family of protocols, called Byzantine fault tolerant, and Raft does not provide it.
Why simpler approaches fall short
Several tempting designs look like they solve replication. Each fails in a specific way.
| Approach | How it works | Where it fails |
|---|---|---|
| Single primary, asynchronous copy | The primary applies a command, answers the client, and copies the command to backups later. | If the primary crashes before copying, the acknowledged command is lost. |
| Single primary, wait for all backups | The primary answers only after every backup has the command. | One crashed or slow backup blocks every write. Availability drops as you add servers. |
| Manual or external failover | An operator or a monitor promotes a backup when the primary seems down. | The monitor cannot tell a crash from a partition. Both sides can end up believing they are primary (split brain) and accept conflicting writes. |
| Clock-based ordering | Each server stamps commands with its local time and replicas sort by timestamp. | Clocks drift, and a command with an earlier timestamp can arrive after later ones were already applied. |
| Two-phase commit | A coordinator asks all participants to prepare, then to commit. | It needs every participant. If the coordinator fails at the wrong moment, participants block. |
Each failure comes from one of two mistakes. Either the design needs all servers, so it cannot tolerate a failure, or it lets a single server decide alone, so it cannot tell a real failure from a slow network.
Consensus protocols avoid both mistakes by using majorities. A decision counts once more than half of the servers have recorded it. Any two majorities overlap in at least one server, so a later decision cannot miss an earlier one. A cluster of five servers keeps working with two failures. A cluster of three keeps working with one. The next chapter covers the arithmetic and the fault model in detail.
Where Raft fits
Paxos was the dominant consensus algorithm for many years. It is correct but has a reputation for being hard to understand and hard to turn into a working system. Raft was designed in 2014 with understandability as an explicit goal. It reaches the same kind of guarantee as multi-decree Paxos, a replicated log with agreement, but it divides the problem into three parts that you can study one at a time:
- Leader election: the cluster picks one server to lead. Servers use numbered periods called terms, and at most one leader can win in each term.
- Log replication: the leader accepts commands from clients, appends them to its log, and copies them to the followers. Followers repair their logs to match the leader's.
- Safety: a set of rules, such as which candidates may win an election and when the leader may mark an entry committed, which together ensure that a committed entry is never lost.
Using one strong leader simplifies the design. Commands flow in one direction, from the leader to the followers. The leader decides the order, so followers never have to negotiate order among themselves. The cost is that the cluster has a short pause whenever the leader fails and a new one must be elected.
The rest of the tutorial follows the dependencies between these parts:
- Majority quorums and the fault model.
- Roles and terms, then leader election.
- Log replication and the rules that keep logs matching.
- Commitment and safety.
- Practical matters: election timing, persistence, client interaction, snapshots, and membership changes.
Common misconceptions
- "Consensus means every server has the same state at every instant." It does not. Servers apply entries at different times, and a follower can lag behind. The guarantee is that they apply the same entries in the same order.
- "The log is the database." The log is the record of commands. The state machine holds the current state derived from the log. Later chapters show how snapshots let you discard old log entries once their effect is captured in a snapshot.
- "Writing to a log means committed." An entry in one server's log is only a proposal. It becomes committed after the cluster agrees on it.
- "Any code can be a state machine." Code that reads the clock, calls an external service, or uses unseeded randomness will diverge across replicas. Side effects that leave the system, such as sending an email, also run on every replica unless you design around that.
Exercise
Two replicas of a counter service each apply the command "increment" three times, starting from 0, and one replica ends at 3 while the other ends at 2. Name two different things that could explain this in a replicated state machine design, and say which part of the design is responsible in each case.
Show answer
First, the replicas may not have applied the same commands. The second replica may simply be lagging and has not yet applied the third entry, which is normal and not a bug as long as it applies the same entries in the same order later. Second, the state machine may be nondeterministic or the logs may differ. If the second replica was given only two increments in its log, the consensus module failed to keep the logs identical. If both logs hold three increments but the states differ, the state machine itself is not deterministic. The first and second cases blame the consensus module, and the last case blames the state machine.
Exercise
A primary-backup system answers the client as soon as the primary has applied a command, and copies the command to the backups in the background. The primary crashes right after answering. Which safety property from this chapter does the system violate, and how does a majority-based protocol prevent the problem?
Show answer
It violates durability of committed entries. The client was told the command succeeded, but no other server may have it, so after failover the command is gone. A majority-based protocol answers the client only after the command is stored on a majority of servers. Any new leader must be elected by a majority, and any two majorities share at least one server, so the new leader's cluster includes a server that has the command.
Exercise
A command in the log is ("set", "created_at", time.time()), and each replica evaluates time.time() when it applies the command. What goes wrong, and how do you fix it?
Show answer
Each replica reads its own clock at a different moment, so each stores a different value, and the replicas' states diverge even though their logs match. The fix is to read the clock once, before the command enters the log (for example on the server that receives the client request), and put the resulting number in the command, as in ("set", "created_at", 1700000000.0). Then every replica applies the same literal value.