Sub topic 10
Clients, duplicate requests, and linearizable reads
This chapter assumes you know the AppendEntries and commit rules from the earlier chapters. It also assumes you can read short Python. Raft's log and commit rules decide what the cluster agrees on. They do not say what a client should do when a request times out, or how to read data safely. Both problems appear in every real deployment.
Finding the leader
Only the leader accepts commands. A client starts with a list of server addresses and sends its request to any of them. A follower either rejects the request and names the leader it last heard from, or forwards it. If the contacted server is unreachable, the client tries another one. The client remembers the last leader that worked and tries it first.
Why retries create duplicates
Suppose a leader appends your command to its log, replicates it, and commits it. Then it crashes before replying. Your client sees a timeout. The command did run, but the client cannot know that. If the client retries against the new leader, the command enters the log a second time. For put x=5 this is harmless. For increment counter or append to list it is a bug.
Raft cannot fix this inside the log, because the log faithfully stores both copies. The fix goes in the state machine:
- Each client registers and gets a unique
client_id. - The client numbers its commands with a
seqthat increases by one per new command. A retry reuses the sameseq. - The state machine keeps a session table that maps each
client_idto the lastseqit executed and the result. - When a command arrives with a
seqthe table has already seen, the state machine returns the saved result and does not execute it again.
The session table must be part of the replicated state machine. Every server updates it as it applies entries, so a new leader has the same table. It must also be included in snapshots, or a restored server will forget what it has already executed.
class CounterMachine:
def __init__(self):
self.counter = 0
self.sessions = {} # client_id -> (last_seq, last_result)
def apply(self, cmd):
client, seq = cmd["client_id"], cmd["seq"]
last = self.sessions.get(client)
if last is not None and seq <= last[0]:
# Duplicate: return the saved result and do not execute again.
return last[1]
self.counter += cmd["amount"]
result = self.counter
self.sessions[client] = (seq, result)
return result
sm = CounterMachine()
cmd = {"client_id": 1, "seq": 7, "amount": 1}
print(sm.apply(cmd)) # 1
print(sm.apply(cmd)) # 1, the retry does not increment againBecause a client has at most one outstanding command, keeping only the latest seq per client is enough. Servers also need a rule to expire old sessions, or the table grows without bound.
Linearizable reads
A read is linearizable if it reflects every write that completed before the read began. The simplest approach is to put reads through the log like writes. That is correct but slow, because each read costs a round of replication and a disk write.
Reading directly from the leader's state machine is faster, but it can be wrong. A leader may have been cut off by a partition while the other servers elected a new leader. The old leader still believes it leads and would return stale data. Two precautions fix this.
Commit a no-op at the start of each term. A new leader does not know which earlier entries are committed until it commits an entry from its own term. Appending a no-op entry on election lets it learn its true commit index before it serves reads.
Use the read-index protocol.
- The leader records its current commit index as the
read_index. - It sends a heartbeat round and waits for a majority to answer. This proves no newer leader exists.
- It waits until its state machine has applied entries up to
read_index. - It answers the read from its local state.
This adds one heartbeat round but no log entry and no disk write. Heartbeats for many pending reads can be batched.
Lease-based reads
A leader can skip the heartbeat round if it holds a lease. After a majority acknowledges a heartbeat, the leader assumes no other leader can be elected until the minimum election timeout has passed. During that window it serves reads locally.
The lease is only as safe as your clocks. If a leader's clock runs slow, or a process pauses for a long time, the leader may serve reads after its lease has really expired. Use leases only when you can bound clock drift. Otherwise use read-index.
| Approach | Extra cost per read | Depends on clocks |
|---|---|---|
| Read through the log | Replication and disk write | No |
| Read-index | One heartbeat round | No |
| Lease read | None | Yes |
Exercise
A leader is partitioned from the rest of the cluster but has not yet noticed. A client reads from it directly, with no heartbeat check and no lease. What can go wrong, and which step of the read-index protocol prevents it?
Show answer
The majority side may have elected a new leader and committed new writes. The old leader would return stale data, so the read would not be linearizable. Step 2 prevents this. The leader must get heartbeat responses from a majority, which it cannot do while partitioned, so it never answers the read.