Sub topic 10
Clients, Duplicate Requests, and Linearizable Reads
This chapter assumes you know how a Raft leader replicates and commits log entries with AppendEntries, and why a leader commits only entries from its current term by counting replicas. You should also be comfortable reading short Python. The earlier chapters made the cluster agree on a log. Here we look at the edge of the system, where real clients send requests, retry them, and expect reads to return current data.
What clients expect
A Raft cluster is usually wrapped around a service such as a key-value store. The service promises linearizability. Each operation appears to take effect atomically at one instant between the moment the client sent it and the moment the client received the reply. Every client then sees one shared, up-to-date history.
Raft's log gives you a total order of writes. It does not give you this promise by itself. Two gaps remain:
- Retries can run a command twice. A client that times out cannot tell whether its command was lost or only the reply was lost.
- A leader can be stale. A server that believes it is leader may have been partitioned away while a newer leader took over. If it answers reads from local state, it can return old data.
The rest of the chapter closes these gaps.
Finding the leader
Clients send commands to the leader. A client that does not know the leader can contact any server. A follower rejects the request and, if it knows, returns the leader's address as a hint. If the contacted server is unreachable, the client tries another one. The client should remember the last known leader so most requests go straight to it.
A leader that crashes after appending an entry but before replying leaves the client with no answer. The client times out and retries on another server. This is the situation that creates duplicates.
Duplicate requests
Suppose a client sends append("log", "x"). The leader replicates and commits it. The leader crashes before replying. The client retries with the new leader, which appends the command again. The log now holds two entries for one client intention, and the value becomes "xx". Raft committed both entries correctly. The problem is above Raft.
The standard fix is for each client to attach two fields to every command:
- A unique client ID, which identifies a session.
- A monotonically increasing sequence number, one per distinct command.
A retry reuses the same sequence number. The state machine keeps a table that maps each client ID to the highest sequence number it has applied and the result it produced. When it applies a command whose sequence number is not newer than the stored one, it skips the work and returns the saved result.
Where deduplication must happen
Deduplicate when the command is applied to the state machine, not when the leader receives it. Two reasons:
- The retry may reach a different leader that never saw the original request. Only the replicated log is shared by all leaders.
- The session table is part of the state machine, so it is updated by the same committed entries on every server. After a leader change, the new leader has the same table as the old one.
It follows that the session table must be included in snapshots. A server that restores from a snapshot without it will re-apply duplicates.
class KVStateMachine:
"""Key-value store with append, plus a session table for deduplication."""
def __init__(self):
self.data = {}
self.sessions = {} # client_id -> (last_seq, last_result)
def apply(self, command):
client_id = command["client_id"]
seq = command["seq"]
last = self.sessions.get(client_id)
if last is not None and seq <= last[0]:
if seq == last[0]:
return last[1] # duplicate: return the saved result
return None # older than the latest: the client moved on
key = command["key"]
if command["op"] == "put":
self.data[key] = command["value"]
result = "ok"
elif command["op"] == "append":
self.data[key] = self.data.get(key, "") + command["value"]
result = self.data[key]
else:
raise ValueError("unknown op")
self.sessions[client_id] = (seq, result)
return result
sm = KVStateMachine()
cmd = {"client_id": "c1", "seq": 1, "op": "append", "key": "log", "value": "x"}
print(sm.apply(cmd)) # x
print(sm.apply(cmd)) # x (the retry is not applied twice)
print(sm.data["log"]) # xThe second apply call returns the stored result and leaves data unchanged, so the duplicate log entry has no effect.
Limits of the session table
- One outstanding request per client. This design stores only the latest sequence number. If a client pipelines several requests, the table must remember a window of recent results, or the client must wait for each reply.
- Memory is bounded by expiring sessions. The table cannot grow forever. A common approach is to expire a session after a long idle time, using a timestamp the leader proposes through the log so that all servers expire the same session at the same log position. If a client returns after its session expired, the server must reject the request with an error. It must not silently re-execute it.
- The client ID needs to be unique. A leader can register sessions by committing a "register client" entry and using the entry's log index as the ID. Random 128-bit identifiers also work in practice.
The sequence below shows the retry path.
Linearizable reads
Reads do not change state, so it is tempting to answer them straight from the leader's local copy. That is unsafe. Consider a leader L in term 5 that is partitioned from the majority. The majority elects a new leader in term 6 and commits new writes. L has not heard about term 6 and still thinks it is leader. If a client reads from L, it gets data that misses writes that have already completed. That violates linearizability.
There are three safe approaches.
Option 1: put reads through the log
The leader appends the read as a log entry and answers when the entry is applied. Committing the entry requires a majority, which proves the leader was still the leader. This is simple and correct, but it costs a disk write and a replication round per read.
Option 2: ReadIndex
The leader avoids writing to the log but still checks that it is current:
- The leader must have committed at least one entry in its current term. A new leader does not know its true commit index until then, so it appends a no-op entry on election and waits for it to commit. Without this step, the leader's
commit_indexmay be behind what earlier leaders already committed. - The leader records its current
commit_indexas the read index. - The leader sends a heartbeat round and waits for acknowledgements from a majority (counting itself). This proves no newer term exists that it does not know about, so it was still leader when the read began.
- The leader waits until
last_applied >= read_index. - The leader executes the read against the state machine and replies.
This costs one heartbeat round and no disk write. Many reads that arrive together can share one heartbeat round.
class Leader:
def __init__(self, cluster_size, current_term, log_terms, commit_index, data):
self.cluster_size = cluster_size
self.current_term = current_term
self.log_terms = log_terms # log_terms[i - 1] is the term of entry i
self.commit_index = commit_index
self.last_applied = 0
self.data = data
def committed_in_current_term(self):
return (self.commit_index >= 1
and self.log_terms[self.commit_index - 1] == self.current_term)
def apply_committed(self):
# Stand-in for the apply loop; the state machine already holds the data.
self.last_applied = self.commit_index
def handle_read(leader, key, follower_acks):
"""follower_acks: number of followers that acknowledged the heartbeat."""
if not leader.committed_in_current_term():
return ("retry", None) # wait for the term's no-op to commit
read_index = leader.commit_index
if (follower_acks + 1) * 2 <= leader.cluster_size: # +1 counts the leader
return ("not_leader", None) # could not confirm leadership
while leader.last_applied < read_index:
leader.apply_committed() # in a real server: wait for the apply loop
return ("ok", leader.data.get(key))
leader = Leader(cluster_size=5, current_term=6,
log_terms=[5, 5, 6], commit_index=3, data={"a": "1"})
print(handle_read(leader, "a", follower_acks=2)) # ('ok', '1')
print(handle_read(leader, "a", follower_acks=1)) # ('not_leader', None)With five servers, the leader needs three confirmations. Itself plus two followers is enough, and itself plus one is not.
Option 3: leader leases
The leader treats each successful heartbeat round as a lease. No other server can win an election until the election timeout has passed since a majority last heard from this leader. During that time the leader can answer reads locally without any message exchange.
This is the fastest option, but it depends on clocks. It is only safe if clock drift between servers is bounded, and a long pause (garbage collection, a VM stall) can make the leader believe it still holds a lease after it has expired. Raft's safety for writes does not depend on timing. Lease reads add a timing assumption to the read path, so use them only if you can bound drift and pauses.
| Approach | Extra cost per read | Depends on clocks | Notes |
|---|---|---|---|
| Read through the log | Disk write plus a replication round | No | Simplest, slowest |
| ReadIndex | One heartbeat round, shareable across reads | No | Common default |
| Leader lease | None | Yes | Fastest, riskiest |
| Local read on a follower | None | No | Not linearizable, may be stale |
Reads from followers
A follower can serve a read safely if it asks the leader for a read index, waits until its own last_applied reaches that index, and then answers locally. This offloads work from the leader while keeping linearizability. A plain local read on a follower is only stale-tolerant. It is suitable for dashboards or caches, not for decisions that need the latest value.
Common errors
- Answering reads from a leader without any confirmation. This is the stale-leader bug described above. It rarely shows up in tests because partitions are rare.
- Skipping the current-term commit check. A new leader that serves a ReadIndex read before its no-op commits can use an outdated commit index and miss committed writes.
- Deduplicating on the leader only. After a failover the retry is applied twice.
- Leaving the session table out of snapshots. Restored servers forget which commands they have applied.
- Re-executing a request from an expired session. Return an error instead, so the client knows its guarantee no longer holds.
- Treating a timeout as failure. A timed-out write may have been committed. The client must retry with the same sequence number, never with a new one, unless it wants a new operation.
Exercise
A client sends append("log", "x") with seq 7 to leader A. A commits the entry and crashes before replying. The client retries seq 7 on new leader B. Explain why the value is still "x" and not "xx", and name the state that makes this work.
Show answer
B appends the retried command as a second log entry, but when the state machine applies it, the session table already holds client c1 with last_seq 7 from the first entry. Since 7 <= 7, the apply step skips the append and returns the saved result. The session table is replicated state, updated by committed entries on every server, so B has it even though it never handled the original request.
Exercise
A newly elected leader receives a read request before it has committed any entry in its own term. Why can it not safely answer using ReadIndex yet, and what does it do about it?
Show answer
Its commit_index may be behind entries that earlier leaders already committed, because a leader only learns the true commit point by committing an entry from its own term. Reading at that stale index could miss committed writes. The leader appends a no-op entry at election, waits for it to commit, and then uses the commit index as the read index.
Exercise
Why does a leader lease make reads faster than ReadIndex, and what extra assumption does it add?
Show answer
The leader answers from local state with no heartbeat round, because a recent majority acknowledgement guarantees that no other leader can be elected before the election timeout passes. The added assumption is bounded clock drift and no long pauses on the leader. If the leader's clock or process stalls, it may serve a read after its lease has expired, which can return stale data.