Sub topic 7
When an entry is committed, and why it is safe
This chapter assumes you have read the earlier chapters on terms, RequestVote, and AppendEntries. You should know that each log entry has an index and a term, and that a leader sends entries to followers with prev_log_index and prev_log_term. You should also be able to read short Python.
Replication alone does not make an entry safe. A leader can copy an entry to some followers and then crash. The entry is safe to apply to the state machine only once Raft guarantees that no future leader can lack it. That point is called commitment.
What "committed" means
An entry is committed when it is guaranteed to be present in the log of every future leader. A server may apply an entry to its state machine only after that entry is committed. A client can then be told the operation succeeded, because the result will never be undone.
Two related terms are easy to confuse:
- Stored on a majority is a fact about the current replication state. It can be true of an entry that is later overwritten.
- Committed is a promise about the future. It is only true if the safety rules make loss impossible.
Raft is built so that, under one extra condition covered below, "stored on a majority" implies "committed". The extra condition is the main subject of this chapter.
The leader's commit rule
The leader tracks match_index[i], the highest log index known to be replicated on server i. Its own entry in that array is its last log index. The leader may advance commit_index to N when both conditions hold:
- More than half of the servers have
match_index >= N. - The entry at index
Nhas the leader's current term.
def advance_commit_index(current_term, commit_index, log_terms, match_index):
# log_terms[i - 1] is the term of entry i (entries are numbered from 1).
# match_index has one value per server, including the leader's own last index.
cluster_size = len(match_index)
for n in range(len(log_terms), commit_index, -1):
replicated = sum(1 for m in match_index if m >= n)
if replicated * 2 > cluster_size and log_terms[n - 1] == current_term:
return n
return commit_indexThe loop starts at the end of the log and walks backward. It returns the highest qualifying index. It stops at commit_index because anything at or below that is already committed.
Committing index N also commits every earlier index. This works because of log matching: if two logs agree on the entry at index N, they agree on everything before it. So a majority holding entry N also holds the whole prefix.
The code applies the majority test replicated * 2 > cluster_size. In a 5-server cluster, 3 servers is a majority. In a 4-server cluster you need 3 as well, which is why even-sized clusters add cost without adding fault tolerance.
Why the current-term condition exists
The second condition looks odd. If an entry from an earlier term sits on a majority, why not commit it? Because a majority copy of an old entry does not stop a later leader from overwriting it. The following scenario shows this, using five servers S1 to S5.
- Term 2. S1 is leader. It appends an entry at index 2 and copies it to S2 only, then crashes.
- Term 3. S5 wins an election with votes from S3, S4, and itself. Its log is up to date enough for them, since none of those servers has the index 2 entry. S5 appends its own entry at index 2 (term 3) and crashes before replicating it.
- Term 4. S1 restarts and wins an election with votes from S2, S3, and S4. It continues replicating, and copies its term 2 entry at index 2 to S3. The entry is now on S1, S2, and S3, which is a majority.
- Danger. Suppose S1 treated that entry as committed and applied it. Then S1 crashes. S5 restarts and can win term 5: its last log term is 3, which is higher than the last term 2 on S2 and S3, and S4 has no index 2 entry at all. S5 gets votes from S2, S3, S4, and itself. It then overwrites index 2 on every server with its term 3 entry.
An entry that was on a majority and was applied to a state machine has now been replaced. That breaks safety.
| Step | Event | Index 2 on S1 | S2 | S3 | S4 | S5 |
|---|---|---|---|---|---|---|
| 1 | S1 leads term 2, replicates to S2 | T2 | T2 | none | none | none |
| 2 | S5 leads term 3, no replication | T2 | T2 | none | none | T3 |
| 3 | S1 leads term 4, copies to S3 | T2 | T2 | T2 | none | T3 |
| 4 | S1 crashes, S5 leads term 5 | T3 | T3 | T3 | T3 | T3 |
The rule stops this. In step 3, S1 sees the term 2 entry on a majority but refuses to count it, because it is not from term 4. S1 waits until it has stored a term 4 entry at a higher index on a majority. Once that happens, the term 2 entry is committed indirectly.
# Step 3 of the scenario, from the point of view of leader S1 in term 4.
# Log so far: index 1 (term 1), index 2 (term 2). Entry 2 is on S1, S2, S3.
log_terms = [1, 2]
match_index = [2, 2, 2, 1, 1]
print(advance_commit_index(4, 0, log_terms, match_index)) # 0: entry 2 is not from term 4
# S1 appends a term 4 entry at index 3 and a majority stores it.
log_terms = [1, 2, 4]
match_index = [3, 3, 3, 1, 1]
print(advance_commit_index(4, 0, log_terms, match_index)) # 3: commits 3, and 2 and 1 with itThe first call returns 0 even though three servers hold entry 2. The second call returns 3, and indexes 1 and 2 are committed along with it.
Why does this fix the problem? After entry 3 (term 4) is on a majority, any server that could win an election needs a log at least as up to date as a majority member. That means its last term must be 4 or more. A server whose last entry is term 3, like S5, can no longer collect a majority of votes. Any server with a last term of 4 or higher must have entry 3, and therefore, by log matching, entry 2 as well.
The election restriction
The commit rule only works together with a rule in the vote handler. A server grants a vote only if the candidate's log is at least as up to date as its own. "Up to date" compares the last entries: the higher last term wins, and if the terms are equal, the longer log wins.
def handle_request_vote(s, req):
# s.log[0] is a sentinel entry with term 0, so real entries start at index 1.
if req.term < s.current_term:
return (s.current_term, False)
if req.term > s.current_term:
s.current_term = req.term
s.voted_for = None
s.role = "follower"
last_index = len(s.log) - 1
last_term = s.log[last_index].term
# Compare last log term first, then last log index.
candidate_up_to_date = (req.last_log_term, req.last_log_index) >= (last_term, last_index)
can_vote = s.voted_for is None or s.voted_for == req.candidate_id
if can_vote and candidate_up_to_date:
s.voted_for = req.candidate_id
s.persist() # currentTerm and votedFor must be durable before replying
s.reset_election_timer()
return (s.current_term, True)
s.persist()
return (s.current_term, False)The tuple comparison (req.last_log_term, req.last_log_index) >= (last_term, last_index) implements the two-step rule in one expression. Python compares tuples element by element, so the term decides first and the index breaks ties.
Why does this guarantee that leaders have all committed entries? A committed entry is on a majority of servers. A winning candidate also got votes from a majority. Any two majorities share at least one server. That shared server holds the committed entry and would refuse to vote for a candidate whose log lacked it. So the winner's log is at least as up to date as the committed entry's holder, and by the log matching property, the winner contains the entry.
The properties Raft guarantees
The pieces above combine into the safety properties from the Raft paper:
- Election safety. At most one leader is elected in a given term, because each server votes once per term and a leader needs a majority.
- Leader append-only. A leader never overwrites or deletes entries in its own log. It only appends.
- Log matching. If two logs have an entry with the same index and term, the logs are identical up to that index.
- Leader completeness. If an entry is committed in some term, it is present in the logs of all leaders of higher terms.
- State machine safety. If a server has applied an entry at some index, no server will ever apply a different entry at that index.
State machine safety follows from the others. The commit rule and the election restriction together give leader completeness, and that is what keeps applied entries from being replaced.
How followers learn about commitment
Followers do not count replicas. They learn the commit index from the leader. Every AppendEntries request carries leader_commit. The follower handler applies the new value after its consistency check passes:
def handle_append_entries(s, req):
# s.log[0] is a sentinel entry with term 0, so real entries start at index 1.
if req.term < s.current_term:
return (s.current_term, False)
if req.term > s.current_term:
s.current_term = req.term
s.voted_for = None
s.role = "follower"
s.reset_election_timer()
# Consistency check: our log must contain the entry just before the new ones.
if req.prev_log_index >= len(s.log) or s.log[req.prev_log_index].term != req.prev_log_term:
s.persist()
return (s.current_term, False)
index = req.prev_log_index
for entry in req.entries:
index += 1
if index < len(s.log) and s.log[index].term != entry.term:
del s.log[index:] # drop the conflicting entry and everything after it
if index >= len(s.log):
s.log.append(entry)
if req.leader_commit > s.commit_index:
s.commit_index = min(req.leader_commit, index)
s.persist()
return (s.current_term, True)The follower sets commit_index = min(leader_commit, index). Here index is the index of the last entry that the request verified. Taking the minimum matters because a follower may have a log that is longer than the verified prefix, and extra entries beyond that prefix might not match the leader's log. The follower can only trust commitment up to the point where the leader's log has been confirmed to match its own.
Commit knowledge also spreads with a delay. A leader commits an entry first, and followers learn about it on the next AppendEntries or heartbeat. A follower's commit_index can therefore trail the leader's, and applying entries on followers is always slightly behind.
Common mistakes
- Counting replicas for old-term entries. This is the Figure 8 bug. Implementations that check only the majority condition pass simple tests and fail under crash and election sequences.
- Using a plain log length for the vote check. The comparison must look at the last term first. A longer log with an older last term is less up to date.
- Setting the follower commit index to
leader_commitdirectly. It must be capped by the last verified entry, or a follower may mark unverified entries as committed. - Telling clients "done" at majority storage. The leader should reply only after the entry is committed and applied. For an old-term entry, that may need a new current-term entry to be appended first.
- Not appending anything after an election. A new leader that has old-term entries uncommitted in its log needs a current-term entry to commit them. Many implementations append a no-op entry as soon as a leader is elected.
Exercises
Exercise
A 5-server cluster has leader S1 in term 6. The log terms by index are [1, 3, 3, 5, 6]. The matchindex values are [5, 5, 4, 2, 1] (S1 is first). commitindex is 1. What does advancecommitindex return, and why?
Show answer
It returns 5? No: only 2 servers (S1 and S2) have matchindex >= 5, which is not a majority. For n = 4, three servers (S1, S2, S3) have matchindex >= 4, which is a majority, but the term of entry 4 is 5, not the current term 6, so it cannot be committed by counting. For n = 3 and n = 2 the terms are 3, not 6. So the function returns 1, the unchanged commit_index. The leader must wait until a term 6 entry at index 5 reaches a third server.
Exercise
Why does a server compare the candidate's last log term before the last log index when deciding whether to vote?
Show answer
A log with a higher last term contains entries from a later leader, and those entries may have replaced others. A longer log whose last term is older can contain uncommitted entries that a later term has already overwritten elsewhere. Comparing terms first prevents such a log from winning, which keeps leader completeness true.
Exercise
A follower has log terms [1, 1, 2, 2] (indexes 1 to 4). It receives AppendEntries with prevlogindex 2, prevlogterm 1, no entries, and leadercommit 4. What should its commitindex become, starting from 0?
Show answer
The consistency check passes, because the entry at index 2 has term 1. There are no new entries, so index stays at 2. The follower sets commit_index to min(4, 2) = 2. It cannot trust indexes 3 and 4, because the request did not verify them against the leader's log.