Goal
After this appendix you can explain why a missing reply has three possible causes that no client can tell apart, build a reliable link from a lossy one and prove it correct, state what TCP does and does not guarantee to a consensus protocol, prove the Two Generals impossibility, and show that Raft’s and Paxos’s handlers stay correct when their messages are lost, duplicated or delivered late.
Every protocol in these notes is written as handlers that “send” and “receive” messages. This appendix opens that box. Underneath the handlers sit a messaging layer (often a remote procedure call library), a transport protocol (TCP or UDP) and IP. We ask which guarantees each layer gives, where each guarantee is lost, and which properties the protocols of Modules 2 to 9 therefore have to provide for themselves.
The thread through the whole appendix is one picture: a client calls a function on a server and no reply comes back. The client cannot know whether the request was lost, the reply was lost, or the server is just slow. Almost everything in this course is a response to that picture: timeouts and failure detectors (Module 5), and the impossibility of telling a crashed node from a slow one that underlies FLP (Module 4); retry semantics, idempotence and deduplication (Module 3); and the system models with lossy links, crashes and partial synchrony. RPC teaches what can go wrong with one request and one reply. Consensus algorithms are what we build when we accept that this can happen to every message and we still need all replicas to agree.
The appendix follows lectures 01.01 and 01.02 (RPC and the Birrell-Nelson paper), 02.01 (Two Generals), 02.02 (system models) and 03.01 (failure detectors); the RPC paper of Birrell and Nelson (1); Kleppmann’s notes §1.3, §2.1, §2.3 and §4.3 (2); §5.1, §5.5, §5.6, §8 and Figure 2 of the Raft paper (3); and the channel assumptions of the PMMC paper (4).
RPC and the three explanations of silence
The question is what a remote procedure call promises, and what it cannot promise.
A remote procedure call (RPC) makes a call to a function on another machine look like a local call. Lecture 01.01 and Kleppmann’s slides 14 to 16 use an online shop that calls processPayment(card, amount) on a payment service. The shop’s code calls a local stub with the same signature. The stub marshals the arguments into a message, sends it, waits for the reply, unmarshals the result and returns it. On the server a matching stub unmarshals the request, calls the real function and sends the result back. Kleppmann calls the goal location transparency: the caller should not need to know where the function runs.
The goal fails as soon as something goes wrong. Suppose the client sends a request and waits; after a timeout it still has no reply. Figure 1 shows the three executions that end this way.
- (a) Request lost. The function
never ran. - (b) Reply lost. The function
ran; its effect is in the server’s state. - (c) Server slow. The function
has not run yet and will run later, after the client has given up waiting.
Try it: in the “Lost reply” scenario, f transfers 10 from a balance of 100. Keep “retry on timeout” on and “server deduplicates by request id” off, and step through: the retry “r1 #2” makes “times f ran” reach 2, “account” ends at 80, and the check “f ran at most once” turns red. Switch deduplication on and step again: the server reports a “cache hit”, replays “ok, bal 90” from its “reply cache”, and “account” stays at 90. The sandbox adds a “slow server” toggle and lets you click a message to drop it.
The claim that the client “cannot tell” is a precise statement about what a process observes, in the style of the indistinguishability arguments of Modules 4 and 5.
Proposition A.1 (A missing reply is ambiguous).Let a client send one request at time
and time out at time . There are executions , , of the three kinds in Figure 1 such that the client’s view (its own steps and the messages it has received) is identical in all three up to time . In the server never runs ; in it runs before ; in it runs after . Hence no client rule that acts at time can decide correctly in all three whether ran.
Proof
Construct the executions with the same client steps. In
the network drops the request. In the request arrives at time , the server runs and replies, and the network drops the reply. In the network delays the request until time ; the server runs then. Fair-loss links allow both drops (a message sent once may be lost), and an asynchronous or partially synchronous network before GST allows the delay (Definition 4.13). In all three, the client receives no message in . A deterministic client’s steps depend only on its initial state, the messages it receives and its local clock; these agree up to time , so by induction over its steps the client takes the same steps in , , up to . Any decision it makes at about whether ran is therefore the same in all three, and it is wrong in at least one: “ran” is wrong in (and, at time , in ), “did not run” is wrong in .
Intuition
A reply is the only evidence a client ever gets about the server. Silence is not evidence of anything: it is consistent with a dead request, a dead reply and a busy server. Asking again does not help either, because the second request and its reply can suffer the same three fates.
This one picture introduces a large part of the course.
| What the picture forces | Where it is treated |
|---|---|
| a timeout cannot tell a crash from slowness | failure detectors, Definition 5.1, Proposition 5.2; FLP, Theorem 4.16 |
| the client must decide whether to retry | retry semantics, Definition 3.2 |
| case (b): a retry can run | idempotence and deduplication, Definition 3.3, Proposition 3.5 |
| case (c): an old request can act late | terms and ballots, Definition 5.4; delayed requests in Modules 7 and 9 |
| what may fail at all | system models: lossy links, crash-stop or crash-recovery, timing (Definition 4.13) |
Exam trap: a timeout means the server crashed
“The RPC timed out, so the server is down and the operation did not happen.” Neither half follows. By Proposition 5.2 a timeout is only a suspicion, and in case (b) of Figure 1 the operation did happen. A system that acts on a timeout (elects a new leader, retries a payment) must be correct when the suspicion is wrong. In Raft and Paxos the timeout only starts an election or a new ballot; terms and ballots make the old leader harmless, so a wrong suspicion costs time, not safety.
Link models and real transports
The question is what the algorithms assume about the network, and how close real protocols come to it.
Lecture 02.02 and Kleppmann’s slide 33 describe three kinds of point-to-point link. The reliable link of Definition 2.1 has no loss between correct nodes, no duplication and no creation (Kleppmann allows reordering; FIFO is an extra property). The arbitrary link has an active adversary that may read, modify, drop, spoof and replay messages. In between is the model that matches a real network without an attacker.
Definition A.2 (Fair-loss link).A fair-loss link from process
to process provides and with
- fair loss: if
and are correct and sends to infinitely often, then receives infinitely often; - finite duplication: if
sends to finitely often, then receives finitely often; - no creation: if
receives from , then sent to . Messages may be lost, delayed for any finite time and reordered. Here
is the content of the message: two sends with the same content are two sends of the same .
Kleppmann’s informal version is “if you keep retrying, a message eventually gets through”. A partition that lasts forever violates fair loss; one that eventually heals does not.
The protocols in a real system are stacked as in Figure 2. Each layer adds a guarantee that the layer below does not give, and each guarantee has a boundary where it stops.
How do the real transports compare with the link models?
| Transport | Closest link model | What it adds | What it does not give |
|---|---|---|---|
| IP, UDP | fair-loss, if the path eventually works | ports and a checksum (UDP) | retransmission, deduplication, order |
| TCP | reliable FIFO, per connection | sequence numbers, acks, retransmission, flow control | anything across a reset, a crash or a new connection |
| TLS over TCP | turns an arbitrary link into TCP’s | integrity, authenticity, no replay inside a session | protection against dropping; anything about nodes |
UDP sends independent datagrams. Each may be dropped, duplicated or reordered, and the checksum only detects (most) corruption, after which the datagram is discarded, which is just another loss. Over a network that eventually delivers packets, UDP is a fair-loss link.
TCP builds a reliable, FIFO byte stream on top of IP with exactly the mechanism of the next section: sequence numbers, acknowledgements, retransmission and duplicate removal. Its guarantee has a scope, though: one connection, while it lives. A TCP acknowledgement says that the peer’s TCP layer received the bytes, not that the peer’s application read or processed them. If the connection is reset, if TCP gives up (Kleppmann notes a typical timeout of about a minute), or if either process crashes, the bytes that the sender wrote and has not seen answered by the application are in doubt. They may have been processed, received but not processed, or lost. The sender then opens a new connection, and TCP on the new connection knows nothing about the old one: it cannot filter a message that the application re-sends, and it cannot re-send one that the old connection lost.
TLS (Kleppmann §2.3) protects a connection against an active adversary who modifies, spoofs or replays traffic, so an arbitrary link becomes as good as the link underneath it. It cannot stop the adversary from dropping messages, and it says nothing about whether the nodes at either end behave correctly.
So “we use TCP, so the network is reliable” is false for the protocols in these notes, for four reasons.
- Three cases again. A request written to a TCP connection can be acknowledged by the server’s TCP layer and still not be executed (the server crashes); a reply can be lost with a reset connection. The client is back in Figure 1.
- Reconnects lose deduplication. After a reset the client must re-send the requests that are in doubt. The new connection delivers them as new data, so a request that did run runs again unless the application deduplicates it.
- Crash-recovery is outside TCP. A restarted process has lost its connections and their buffers. Raft and Paxos assume crash-recovery; their persistence rules (“persist before replying”) exist because transport state does not survive a crash.
- No FIFO across connections. TCP orders the bytes of one connection. A protocol in which copies of a message take different paths (relays in eager reliable broadcast, two connections before and after a reset) gets no order guarantee from TCP.
Lecture 04.04 (in Module 2) is right that real systems almost always run over TCP; the point is that retries and deduplication must still be done end to end, by the messaging layer or the protocol, on top of it.
Lecture correction: TCP and encryption do not make a perfect link
Lecture 02.02 says that by running TCP over a fair-loss network and encrypting the traffic “you can convert any sort of environment into a perfect environment where all your messages are being delivered”. Kleppmann’s notes (§2.3) are more careful, and correct: TCP retries and deduplicates only within a connection and gives up after a timeout, so long interruptions need a retry and deduplication mechanism of their own above TCP; TLS cannot prevent an adversary from dropping messages; and a sender that crashes while retransmitting may lose the message for good. The accurate statement: TCP plus TLS approximates a reliable link between two processes that stay up and stay connected; across crashes and reconnects the application must provide its own identifiers, retries and deduplication.
Exam trap: TCP makes idempotence unnecessary
“Raft runs over TCP, which never delivers a message twice, so the AppendEntries handler does not need to be idempotent.” Wrong. TCP removes duplicates only inside one connection. After a reset, the leader cannot know whether its last AppendEntries was processed and must send it again on a new connection; the Raft paper also has followers that crash after processing a request and before replying receive the same RPC again (§5.5). Idempotent handlers (Proposition A.10) are what make this harmless, with or without TCP.
From fair-loss to reliable links
The question is how retransmission and deduplication, the mechanism inside TCP and inside every RPC library, turn a fair-loss link into a reliable one, and what exactly that needs. The algorithm below is the “retry + dedup” arrow of Kleppmann’s slide 33.
// Reliable link from i to j over a fair-loss link. Sender side, at i:
nextSeq := 0 // next sequence number, never reused
unacked := {} // map seq -> message, not yet acked
on request to send m to j:
unacked[nextSeq] := m
send Data(i, nextSeq, m) to j // first copy right away
nextSeq := nextSeq + 1
on retransmission timer: // fires periodically, forever
for each (s, m) in unacked:
send Data(i, s, m) to j
on receive Ack(s) from j:
delete unacked[s] // no effect if already deleted
// Receiver side, at j:
received := {} // pairs (sender, seq) already delivered
on receive Data(i, s, m):
send Ack(s) to i // acknowledge every copy
if (i, s) not in received:
received := received + {(i, s)}
deliver m // the reliable link's receive event| Line | Why it is there |
|---|---|
nextSeq never reused | the pair (sender, seq) names exactly one send, so deduplication cannot merge two different messages |
retransmit until Ack(s) | fair loss only promises delivery for a message sent infinitely often |
| ack every copy, also duplicates | the first ack may be lost; without a new ack the sender would retransmit forever |
received check | the receiver delivers each (sender, seq) once, however many copies arrive |
Theorem A.3 (Retransmission and deduplication give a reliable link).Assume crash-stop processes and fair-loss links in both directions between
and (Definition A.2). Then the algorithm above implements a reliable link from to (Definition 2.1):
- reliable delivery: if
and are correct and sends , then eventually delivers ; - no duplication:
delivers each message sent by at most once; - no creation: if
delivers from , then sent to .
Proof
Each request to send gets the current value of
, and only increases. So distinct sends get distinct numbers , and the pair identifies one send; we write for its message. No creation. Suppose
delivers from . It does so on receiving some from the fair-loss link. By no creation of that link, sent . The sender sends only when or in the send handler, and is only ever set to the message of the request that received number . So , which was asked to send to . No duplication.
delivers in the step in which it inserts into , and only if was not there. never shrinks (crash-stop: the process never restarts), so every later copy of finds and is not delivered. Since identifies one send, each sent message is delivered at most once. Reliable delivery. Let
and be correct, let send , and suppose for contradiction that never delivers . Then never receives any copy of : at the first one it would find (by no creation and uniqueness of , no other message carries the pair ) and deliver. Hence never sends , because it sends only on receiving . By no creation on the link from to , never receives , so stays in forever. Since is correct, its retransmission timer fires infinitely often, so sends to infinitely often. By fair loss, receives it infinitely often; in particular at least once. Contradiction.
Intuition
Fair loss says “keep trying and you will get through”; the sender keeps trying until it has proof (an ack) that it got through. The price of keeping trying is duplicates, which the sequence number removes. The ack itself travels over a lossy link, which is why the receiver acknowledges every copy: the sender stops only after one ack has arrived, and that requires acks to be sent as long as copies keep arriving.
The theorem gives neither FIFO order nor any bound on time. FIFO order is obtained, as in TCP, by delivering in sequence-number order and holding back early arrivals; that is the FIFO algorithm of Module 2 (Theorem 2.7) applied to one link.
Remark A.4 (Crash-recovery needs stable storage of sequence numbers).The proof used crash-stop in two places, and both break if a process may restart with empty memory.
- If the sender forgets
, it reuses old numbers. The receiver then discards a new message as a duplicate of an old one with the same : a message is lost. The fix is to keep on stable storage, or to make the identifier include an incarnation number that changes on every restart. Birrell and Nelson do the latter with a conversation identifier derived from a clock (§3.2 of their paper). - If the receiver forgets
, a retransmission that arrives after its restart is delivered a second time. - If the sender forgets
, the messages in it are never retransmitted; a reliable link from a process that restarts must therefore persist them before reporting them as sent. The set
also grows forever. A common compression keeps, per sender, the largest such that all numbers up to have arrived, plus the few numbers above it; this is exactly what a FIFO receiver keeps anyway.
The Two Generals problem
The question is whether more acknowledgements could ever give both sides certainty. They cannot.
Lecture 02.01 and Kleppmann’s §2.1 (slides 22 to 24) tell the story: two armies must attack a city together; an army that attacks alone is destroyed; their messengers cross territory where they may be captured. General 1 proposes a time. If General 2 attacks on receipt, it risks attacking alone when General 1 never learns of the agreement; if it waits for an acknowledgement of its acknowledgement, the problem has only moved. Kleppmann attributes the problem to Gray (1978) and names the underlying obstacle as the lecture does: there is no common knowledge, because the only way to know something is to have it communicated.
Theorem A.5 (Two Generals impossibility).Two processes
, communicate over a link that may lose any message; nothing else fails (no crashes, no corruption, no creation). has an input , has none. Both run deterministic programs and each eventually outputs a decision. No protocol satisfies all of
- termination: in every execution, both processes decide within finite time;
- agreement: in every execution, both decide the same value;
- validity: if
, both decide retreat; if and no message is lost, both decide attack.
Proof
The view of a process up to time
is its input together with the messages it received before and their receive times. A deterministic process with the same view in two executions takes the same steps and makes the same decision at the same time. Call an execution good if and both decide attack, and let be the number of messages received in . There is a good execution with finitely many received messages. By validity, the loss-free execution with
is good. By termination, both processes have decided by some time . Change it into an execution in which every message that would be received after is lost instead. Views up to are unchanged, so both still decide attack by . Each process takes finitely many steps before , so finitely many messages are received. Among all good executions with finitely many received messages, pick one, , with minimal. Case
. No message is received in . Let have and lose every message, with the same timing. has no input and receives nothing in either execution, so its view is the same in and , and it decides attack in as in . Validity requires retreat in . Contradiction. Case
. Let be a message received last in , at time , by process from process ( ). Build : identical to before , except that is lost, and every message sent at or after is lost as well. In no message is received after except possibly others at time itself, which were sent before and are kept. So receives in exactly the messages it receives in , at the same times: its view is the same at all times, and decides attack in . By termination decides in , and by agreement it decides attack. So is good, with and (the message is no longer received, and no new message is). This contradicts the minimality of .
Intuition
Take the shortest successful run and delete its last message. The sender of that message cannot notice the deletion (nobody tells it), so it still attacks; then the receiver must attack too, so the run without the last message also succeeds. Repeating this deletes every message, and a
that heard nothing cannot know that wanted to attack. Each acknowledgement only moves the uncertainty to the other side.
Lecture correction: lower loss does not solve the Two Generals problem
Lecture 02.01 says the shop and payment example is solvable in practice “because our rate of loss is not as high” as in the story. No loss rate below 100% helps: the proof above loses only one message, the last one. Kleppmann (§2.1) gives the right reason: the real problem is a different one. The payment can be undone by a refund, and the shop can wait until the connection is restored and then ask the payment service for the status of the transaction. Neither side has to act at the same time as the other, and neither has to decide before the network cooperates.
Raft and Paxos solve consensus over the same lossy links. Why does this theorem not rule them out?
Remark A.6 (How consensus escapes the Two Generals argument).The proof used termination in an execution in which a message is lost:
must still decide. Consensus algorithms drop exactly this requirement.
- Termination is only eventual and conditional. Raft and Paxos must terminate only when links are fair-loss and, after GST, timely (Definition 4.13). If the last AppendEntries of a commit is lost, nothing obliges the leader to stop: it retransmits until a reply arrives. There is no “last message” to delete. In executions in which the network keeps dropping messages, the algorithms simply do not decide, which their liveness property allows (Theorem 4.16 says this price is unavoidable).
- Decisions are taken by a majority, not by both. A value is decided once a majority has stored it (Definition 7.1, Definition 8.3). A node that missed the messages has not decided something else; it has not decided yet, and it learns the decision later by catching up. Nobody needs to know that everybody knows.
- Nothing must happen simultaneously. Applying command 5 at one replica now and at another replica an hour later is fine; the state machines still agree on the sequence. “Attack together” is a requirement about time, and no amount of consensus provides it over a lossy network.
RPC semantics and how Birrell and Nelson implemented them
The question is what an RPC system can promise about how many times a call runs, and what mechanism keeps the promise.
Definition A.7 (Call semantics).Fix one logical call of procedure
: one invocation of the client stub, possibly sent as several copies. Let be the number of times the server executes for it.
- At-most-once:
in every execution. If the stub returns a result, ; if it reports failure, and the client is not told which. - At-least-once:
in every execution in which the client keeps retrying, the links are fair-loss and the server is eventually up; is possible. - Exactly-once effect: under the same assumptions,
, and every result the client receives for this call is the result of that one execution. These are the retry semantics of Definition 3.2, stated per call and with what the caller learns.
Exactly-once delivery, in the sense that the network hands each message to the server exactly once, is not achievable: the network may lose or duplicate any copy, and Proposition A.1 shows that the client cannot know which happened. What is achievable is the exactly-once effect: copies may arrive any number of times, but only one of them executes
Birrell and Nelson’s RPC system for the Cedar environment at Xerox PARC (1), the subject of lecture 01.02, still has the structure of most RPC systems. Its pieces:
- Stubs. Five pieces of code take part in a call: the user, the user-stub, the communications package RPCRuntime (one instance on each machine), the server-stub and the server. The stubs are generated from an interface module by a tool called Lupine; they pack and unpack arguments and results. RPCRuntime does retransmission, acknowledgements, routing and encryption.
- Binding. A server exports an interface; its RPCRuntime records it in a table of current exports with a fresh unique identifier, and registers the machine in the Grapevine distributed database. A client imports the interface: its RPCRuntime looks up an exporter in Grapevine and asks that machine for the identifier and table index, which the user-stub stores. Every call packet carries the identifier, and the server checks it on every call. Lecture 01.02 points out that binding happens at import time, so a call to an unknown procedure fails then rather than at call time.
- Its own transport. The authors had tried byte-stream protocols and rejected them. RPC traffic is short request-response exchanges, unlike the bulk transfers that byte streams are built for; the goals were low latency per call and little server state for many clients, without connection set-up handshakes. Their measurements suggested a factor of ten in performance from a protocol designed for RPC.
- Call identifiers. A call identifier is the calling machine, the calling process and a sequence number. The pair (machine, process) is an activity, and an activity has at most one outstanding call; its sequence numbers are monotonic. The server’s RPCRuntime keeps a table with the sequence number of the last call of each activity, and discards a call packet as a duplicate unless its number is larger. The identifier also lets the caller recognise that a result belongs to the current call and not to a much older one.
- Implicit acknowledgements. The sender of a packet retransmits it until it is acknowledged, but the result packet acknowledges the call, and the next call acknowledges the previous result. In the common case a call costs exactly two packets.
- Probes. For a long call, the caller sends periodic probes, which the server’s RPCRuntime acknowledges. As long as probes are answered the caller waits indefinitely, just as a local call has no timeout; when they stop, the caller raises the call failed exception.
- Server crash. A restarted server exports with a new unique identifier, so calls bound to the old incarnation are rejected: bindings break implicitly. The paper relies on this to detect duplicate call packets that a caller is still retransmitting to a server that crashed and restarted with an empty table.
The guarantee that results is at-most-once in the sense of Definition A.7. If the call returns, the procedure ran exactly once (“precisely once”, in the paper’s words); if an exception is reported, it ran once or not at all, and the client is not told which. The authors chose this deliberately, to stay close to local calls.
The two blocks below are a minimal modern version of the same design, with the reply cache made explicit. A client calls through a stub that numbers its calls and retries:
// Client stub. One outstanding call per client, as in Birrell-Nelson.
clientId := id of this incarnation of the client // new id after a restart
seq := 0
function call(f, args): // what the application calls
seq := seq + 1
req := Request(clientId, seq, f, marshal(args))
T := initial timeout
loop:
send req to server
wait until a Reply(clientId, seq, result) arrives or T elapses
if the reply arrived:
return unmarshal(result)
// timeout: request lost, reply lost or server slow: unknown
if retries exhausted: // omit this line: at-least-once
raise CallFailed // f ran once or not at all
T := min(2 * T, Tmax) // back off, then resend SAME req
on receive Reply(c, s, result) with s != seq:
ignore // late reply to an older call// Server dispatcher with a reply cache: one entry per client.
lastSeq := {} // clientId -> seq of the last executed call (stable storage)
lastReply := {} // clientId -> reply of that execution (stable storage)
on receive Request(c, s, f, args):
if c in lastSeq and s < lastSeq[c]:
return // older than the client's current call
if c in lastSeq and s == lastSeq[c]:
send lastReply[c] to c // duplicate: replay, do not re-run f
return
atomically: // execute and record as one step
result := f(unmarshal(args))
lastSeq[c] := s
lastReply[c] := Reply(c, s, marshal(result))
send lastReply[c] to c| Line | Why it matters |
|---|---|
same req on every retry | the identifier |
retries exhausted | with it: at-most-once from the caller’s view; without it: at-least-once |
s < lastSeq[c]: drop | the client has one outstanding call, so it already has this reply |
s == lastSeq[c]: replay | case (b) of Figure 1; the retry gets the old result, |
atomically | a crash between running |
| stable storage | a server that forgets the table falls back to at-least-once (Remark A.9) |
A copy that arrives while the first execution is still running is covered by the atomic step: copies are handled one at a time. A real server instead marks the call “in progress” and drops copies until it finishes, as Birrell and Nelson’s RPCRuntime does while it acknowledges probes.
Proposition A.8 (A reply cache gives an exactly-once effect).Assume that each client has at most one outstanding call and numbers its calls
; that the client stub retries without a limit; that links are fair-loss; and that the server eventually stays up, runs the dispatcher above, and never loses lastSeqandlastReply. Then every callis executed exactly once, and the client receives the reply of that execution.
Proof
Monotonicity.
lastSeq[c]changes only in the atomic step, where it is set toafter the checks have ruled out . So lastSeq[c]only increases, andlastReply[c]is always the reply of the execution with numberlastSeq[c].At most once. The server executes
for only in the atomic step, and only if (or is new). The same step sets . Afterwards forever, by monotonicity and because the table is never lost, so every later copy of takes one of the two early returns and does not execute . Old copies never block the current call. While the client waits for call
, all its calls numbered below have returned and it has sent nothing numbered above . So at all times during the wait, since lastSeq[c]takes only values of calls the client sent. Copies of older calls are dropped by the first check, which is safe because their replies were already received.At least once, and the right reply. The client sends
again after every timeout, so infinitely often unless a reply arrives. By fair loss, some copy reaches the server after it has stayed up. When it is processed, ; either and the server executes and replies, or and it replays , the reply of the unique execution of . Each later copy also triggers a reply, so the server sends the reply infinitely often while the client keeps retrying, and by fair loss on the reverse link one reaches the client. Every reply for that the server ever sends is at a time when , that is, the reply of the single execution.
Intuition
The table remembers, for each client, “the last thing you asked me and what I answered”. Because a client asks one thing at a time, that is all the server needs: anything older has been answered, anything newer has not been asked yet. This is why the table is bounded by the number of clients, unlike the set of all request identifiers in Proposition 3.5.
Remark A.9 (The reply cache must survive, or be bounded with care).The proposition needs the table to survive. Three ways in which real systems handle this:
- Lose it, and say so. Birrell and Nelson keep the table in memory. A restarted server has a new unique identifier, so retransmissions bound to the old incarnation are rejected with an exception instead of being executed again. The result is at-most-once, not exactly-once.
- Replicate it. In Raft (§8) the table is part of the replicated state machine. It is rebuilt from the log on every replica, so it survives any minority of crashes and any change of leader (worked example below).
- Expire it. A table entry can be dropped when no copy of that call can still arrive. Birrell and Nelson discard idle state after about five minutes, and the PMMC paper keeps duplicate-filtering information “for a certain amount of time” (§4.2). Both are timing assumptions: a copy delayed longer than the expiry would run again.
Exam trap: exactly-once delivery
“With TCP and a good RPC library, every message is delivered exactly once.” No protocol can achieve exactly-once delivery over a network that may lose and duplicate messages: by Proposition A.1 the sender cannot know whether a copy arrived, so it must either risk sending none (loss) or send another (duplicate). What can be achieved is the exactly-once effect: at-least-once delivery plus a deduplication table at the receiver, under the conditions of Proposition A.8.
Do the protocols use RPC?
The question is whether broadcast and consensus are “built on RPC”. The answer is: partly, and less than the word suggests.
| RPC style | Message passing | |
|---|---|---|
| shape | one caller, one callee, one reply | send and receive; replies are just more messages |
| the caller | blocks until the reply or a failure | continues; handles replies as events |
| fits | client and server | broadcast, gossip, protocol rounds |
| in these notes | clients of Raft and Paxos | broadcast (Modules 1, 2), Paxos (Modules 8, 9) |
Broadcast is message passing. The algorithms of Module 2 send copies and react to arrivals; nobody waits for a reply. Eager reliable broadcast re-sends on first receipt and expects nothing back.
Paxos is written as messages. Prepare/Promise and Accept/Accepted (Module 8), or p1a/p1b and p2a/p2b in PMMC (Module 9), are request and reply pairs, but a proposer sends to all acceptors and acts on the first majority of answers. The PMMC paper assumes that a message between correct processes is “eventually received (at least once)”, not necessarily in FIFO order, and that this can be implemented over fair links by retransmitting until acknowledged (§1, §3); duplicates are allowed by design.
Raft is described as two RPCs, which behave like messages. The paper says that Raft servers communicate by RPCs, RequestVote and AppendEntries, that servers retry an RPC if no response arrives in time, and that they issue RPCs in parallel (§5.1). The leader retries AppendEntries indefinitely, even after it has answered the client (§5.3), and “Raft RPCs are idempotent” (§5.5). So the leader never blocks on one follower: it sends to all in parallel, handles replies as they come, and re-sends whatever is unacknowledged. The block below writes this loop out; sendAppendEntries, the reply handler and advanceCommitIndex are those of Module 6.
// Leader of currentTerm: replication to every follower, never blocking.
// The common term rule of Module 6 runs first on every reply.
on becoming leader: // after becomeLeader() of Module 6
for each server j != self:
lastSent[j] := 0 // local time of the last request to j
on client request: // after appending it (Module 6)
for each server j != self:
sendAppendEntries(j); lastSent[j] := now
on timer tick: // e.g. every few milliseconds
for each server j != self: // a slow j delays nobody else
if now - lastSent[j] >= R: // R: heartbeat and retry interval
sendAppendEntries(j) // fresh request from the current log
lastSent[j] := now
on receive AppendEntriesReply(term, success, matchedUpTo) from j:
if state != leader or term != currentTerm:
return // reply to a request of an old term
if success:
matchIndex[j] := max(matchIndex[j], matchedUpTo) // never decreases
nextIndex[j] := matchIndex[j] + 1
advanceCommitIndex() // current-term rule of Module 6
else:
nextIndex[j] := max(1, nextIndex[j] - 1) // walk back
sendAppendEntries(j); lastSent[j] := now| Line | Why it matters |
|---|---|
no wait anywhere | each handler runs to completion; a crashed or slow follower costs only its own requests |
timer re-sends after R | the same request is a heartbeat and a retry; it repeats forever while the leader leads |
| fresh request from the current log | a retry carries the latest entries and commitIndex, so an old request is never needed again |
term != currentTerm | a reply to an older term’s request says nothing about this term |
max(matchIndex[j], matchedUpTo) | a late or duplicated reply cannot move matchIndex back (Proposition A.11) |
Three properties make it safe to send the same AppendEntries any number of times and to process replies in any order. They rest on Module 6’s handlers and on Log Matching.
Proposition A.10 (AppendEntries is idempotent).Let a follower
process an AppendEntries request with the receiver of Module 6, and then immediately process again. Then the second processing leaves , , and unchanged, and sends the same reply as the first.
Proof
Let
have term , , , entries of length and . Consider the first processing. If
, the receiver replies and changes nothing. The second processing finds the same state and does the same. Otherwise, after the common term rule
(the rule changes and only if is larger, and after the first processing it is not). The second processing therefore also passes the term test and changes neither variable; setting , and restarting the timer repeat the same values. If the consistency check failed the first time, the log was not modified and the reply was
. The second processing sees the same log, fails the same check and sends the same reply. If it succeeded, Lemma 6.5 says that afterwards
(if ) and for ; in particular . In the second processing the check passes again. In every loop iteration and the terms are equal, so neither the delete branch nor the append branch runs: the log is unchanged. is the same value, and after the first processing (if before, the max made it so; otherwise already). So the max in step 4 leaves unchanged, and the reply is the same.
Intuition
The second copy finds every entry it carries already in place, with the right terms, behind an entry that passes the check. Module 6’s receiver deletes only on a conflict, never merely because the log is longer than the request, and appends only what is missing. This is the paper’s own example of idempotence (§5.5): entries that are already present are ignored.
A copy can also arrive late, after later requests of the same leader. It then deletes nothing: its entries are copied from the leader’s log, which only grows (Proposition 6.7), so by Log Matching (Theorem 7.3) the follower’s log and the request agree on every index both hold, and the receiver finds no conflict. This is the "
Proposition A.11 (Stale and duplicated replies are harmless).Let
be leader of term and run the reply handler above. Then for every follower , during ‘s leadership:
never decreases; - whenever
, at some earlier time during term follower stored entries equal to those of . Consequently a stale, duplicated or reordered reply cannot make the commit rule (Definition 6.8) count a server that never stored the entry.
Proof
Claim 1.
is set to 0 when becomes leader and afterwards changes only by , which cannot decrease it. Claim 2.
takes a new value only from a reply , since replies with another term are ignored. A follower replies success with term only after processing an AppendEntries of term (the term test and the common rule make its equal to the request’s term). The only leader of term is (Theorem 5.10), so that request was sent by during term , possibly long ago and possibly a duplicate. Let it carry , , entries , so . By Lemma 6.5, right after processing it and . The values and were copied from when the request was sent, and by Proposition 6.7 they are still in at the same indices. So and hold entries with the same index and term at index , and Log Matching (Theorem 7.3) gives at that moment. Consequence. The commit rule counts
for index only if . By claim 2, stored ‘s entry at during term . This is the fact that Definition 7.1 and the proof of Leader Completeness use. A stale reply carries an older, smaller , which the max ignores; a duplicated reply repeats a true fact.
The failure branch is not protected by a max: a stale failure reply can lower nextIndex[j] once too often. That only costs traffic. The next request has a smaller prevLogIndex, passes the check, and re-sends entries the follower already has, which Proposition A.10 makes harmless.
Proposition A.12 (Paxos acceptors ignore repeats, proposers ignore old ballots).Consider the acceptor of Module 8 (Prepare and Accept handlers).
- If the acceptor processes a Prepare
or an Accept that it has processed before, at any later time, its state ( promised,acceptedBallot,acceptedValue) does not change.- A proposer running ballot
counts each acceptor at most once and only Promise replies for ; a learner counts each acceptor at most once per ballot. Hence duplicated replies and replies to older ballots cannot make a proposer or a learner believe that a majority answered when it did not. The same holds for the PMMC acceptor, scout and commander of Module 9.
Proof
By Lemma 8.6,
promisednever decreases.Prepare
repeated. The first processing either set or found ; either way afterwards , and this stays true. The second processing finds false and takes the Nack branch, which changes nothing. Accept
repeated. After the first processing . If at the second processing , the Nack branch runs and nothing changes. Otherwise , and the acceptor sets , , . These are the current values. Since the first processing the acceptor can only have accepted Accept requests with ballot at least , that is exactly , and a ballot is used by one proposer with one value (Definition 8.2), so still. Counting. The proposer waits for Promise
from a majority , a set of acceptors, so a duplicate adds no member, and a Promise for another ballot is not a Promise for . The learner adds to the set , so a repeated Accepted from changes nothing. In PMMC the acceptor’s acceptedis a set and a repeated p2a adds an element already present (the paper notes that an acceptor may accept a pvalue more than once); a repeated p1a changesballot_numonly if the ballot is higher, which it no longer is; scouts and commanders remove acceptors from the setwaitforand ignore replies whose ballot differs from theirs.
One detail of the Module 8 pseudocode follows from part 1. A duplicated Prepare
The real link, in one table. Each fact about a real network is answered by a design rule in the protocols.
| Fact about the link | Design rule | Where |
|---|---|---|
| a reply may be lost | handlers idempotent, retries safe | Proposition A.10, Proposition A.12 |
| a slow server looks dead | elections can be wrong; terms and ballots make a stale leader harmless | Modules 5, 7, 9 |
| timeouts cannot be trusted | safety must not depend on timing, only liveness | Theorem 4.16, Raft §5.6 |
| a request may run late | a delayed AppendEntries or p2a after a newer leader must be harmless | Module 7 ( |
Raft and broadcast over a real network
The question is what changes when the handlers above run over TCP connections between real machines.
Connections. A typical implementation keeps one long-lived TCP connection from each server to each peer and sends its RPCs over it; this is an implementation choice, not part of the paper. TCP then removes loss and reordering within the connection. When a connection breaks, requests in flight are in doubt, and the sender reconnects and continues. Raft does not try to find out what happened to them: the leader’s next AppendEntries is built from its current log, nextIndex and commitIndex, and the follower’s reply settles the matter. A fresh request is better than waiting for the reply of an old one, because the old one may carry an outdated leaderCommit and fewer entries, and because nothing about it needs to be learned (by Proposition A.10 its effect is contained in the effect of any later request).
Timing. The timing requirement of §5.6,
is about the messaging stack as a whole. broadcastTime includes writing to stable storage before replying (0.5 to 20 ms in the paper’s estimate) and also any TCP retransmission or reconnection delay. A connection that stalls for longer than the election timeout looks exactly like a dead leader (case (c) of Figure 1): followers start an election, terms advance, the old leader steps down. That costs availability, never safety.
Persist before replying. Figure 2 of the paper keeps currentTerm, votedFor and log[] on stable storage, “updated on stable storage before responding to RPCs”. A reply is a promise (a vote, a stored entry) that a crash must not erase. If the server crashes after persisting and before the reply leaves, the leader sees case (b) of Figure 1, retries, and the idempotent handler answers again (§5.5).
Clients. A client of Raft is an RPC client in the sense of the earlier section. If the leader commits a command and crashes before answering, the client retries with another server and the command would run twice. The paper’s fix (§8) is the reply cache: each client assigns unique serial numbers to its commands, and the state machine keeps the latest serial number processed for each client with its response, answering a repeated command without executing it again. Because the table lives in the replicated state machine, it is the same on every replica and survives a change of leader, which is exactly the condition of Proposition A.8. Note where the deduplication happens: a retried command can be appended to the log twice; it is filtered when it is applied.
Broadcast. Eager reliable broadcast (Theorem 2.2), like the other broadcast algorithms of Kleppmann’s §4.3, assumes only reliable point-to-point links, which Theorem A.3 builds from fair-loss links. Its own seen set is a deduplication table for the copies that arrive through different relays, which no transport can remove because they are different sends. The FIFO algorithm keeps its own sendSeq and delivered vector even over TCP, for two reasons. Copies of one sender’s messages reach a node over several connections (directly, and relayed by every other node), and TCP orders bytes only within one connection. And after a reconnect even a single path loses its order guarantee. FIFO is a property of the sender’s broadcast order, so it is enforced end to end, by the sequence numbers the sender itself assigns.
Gossip needs even less. A lost copy is just one copy fewer, and the redundancy of random relaying makes up for it, so gossip can run over plain datagrams without acknowledgements.
Remark A.13 (Gossip over a lossy network).In the model of Proposition 2.5, suppose each copy is lost independently with probability
. A copy now reaches a fixed uninformed node with probability at least , so the bound of the proof becomes per round, and for rounds. Loss acts like a smaller fanout ; for example costs about 11% more rounds.
Worked example: a retried command over TCP
We follow one client command through a 3-server Raft cluster, with a connection reset, a duplicated AppendEntries and a client retry. A is leader of term 1; B and C are followers; each server has a TCP connection to each other server. The state machine holds a counter
Initially every log holds one committed and applied entry, SET y 0, client c, serial 3). So commitIndex is 1, and on A, INC y with serial 4, a command that is not idempotent. We write INC y, c, 4).
| Step | Event | Logs A / B / C | On A: match B, C; commit | State machines |
|---|---|---|---|---|
| 1 | A appends | 1, 1; 1 | ||
| 2 | B appends | 1, 1; 1 | ||
| 3 | client times out, resends (INC y, c, 4); A appends | 1, 1; 1 | ||
| 4 | B: index 2 matches, appends | 3, 1; 3 | A: | |
| 5 | C (slow) processes both AEs in order; replies (1, true, 2), (1, true, 3) | all | 3, 3; 3 | A: |
| 6 | heartbeat AE(prev 3, [], commit 3); B and C commit 3, apply 2 and 3 | all | 3, 3; 3 | all: |
Checks:
- Step 2. From A’s side this is case (b) of Figure 1, so A cannot tell whether B got the request. It does not need to. It does not wait for B either: C’s request is already out, and in step 3 it sends B a fresh request on a new connection.
- Step 3. The client’s retry is a new message to A, so A appends the command a second time, at index 3. Raft deduplicates at apply time, not at append time. The new AE to B carries
again: that part is the duplicate. The AE to C is sent although C has not answered the first one; nothing waits for C. - Step 4. B passes the check at index 1. At index 2 it finds the same term, so it changes nothing (the idempotence of Proposition A.10 for the overlapping part), and it appends
. A sets . Index 3 is on A and B, two of three, with term 1 = currentTerm, so . A applies : serial 4 > 3, so it executes INC y,, and stores “c: serial 4, reply y = 1”. It applies : serial 4 is not above 4, so it skips execution and returns the stored reply. The client receives “y = 1” (twice; its stub ignores the copy that arrives after the call has returned). - Step 5. C’s two requests arrive over one connection, in order. If its replies had arrived in the other order (as they can after a reconnect), A would compute
for the late one: by Proposition A.11 cannot go back. The same holds if B’s reply from step 2 had been delayed instead of lost. - Step 6. B and C apply in log order with the same table:
runs INC y,is skipped. All three state machines end with and “c: serial 4”. The command reached A twice, appears twice in every log, and B received twice; yet each replica executed it exactly once.
Without serial numbers, step 4 would set
What breaks
- Byzantine nodes and corrupting networks. Every argument here assumes crash faults: a node either follows its handlers or stops. TLS stops an adversary from modifying, spoofing or replaying messages on the wire, but it authenticates a node, not its behaviour; a node that lies (a follower inventing acknowledgements, a server claiming a huge term) is beyond these protocols, and lecture 02.01’s Byzantine generals need
nodes. - Losing the deduplication table. If the reply cache is kept in volatile memory, a crash turns exactly-once into at-least-once (or, with Birrell and Nelson’s incarnation check, at-most-once). If a reliable link’s sequence numbers are not on stable storage, a restart can lose or duplicate messages (Remark A.4). Expiring table entries is safe only if delays are bounded.
- Unbounded delays. A network that delays or drops messages for long periods (a partition) stops elections, commits and broadcasts from completing. Safety is untouched; only liveness, which needs fair loss and eventually bounded delay, is lost.
- Clock-based leases. A leader that answers reads from a lease, without contacting a majority (Module 6), makes safety depend on bounded clock drift and bounded pauses. A process paused longer than its lease (a garbage-collection pause, a stalled TCP write) can serve a stale read after a new leader has been elected.
Why it matters
Every protocol in these notes runs over a network that loses, duplicates, reorders and delays messages, and TCP hides only part of that, inside one connection. This appendix showed what the protocols must therefore do themselves: number and retransmit messages, deduplicate them end to end, make every handler idempotent, ignore replies of old terms and ballots, and keep their promises on stable storage. Modules 2 and 3 use these mechanisms directly (reliable links, the deduplication table), Modules 5 to 7 rely on them for Raft’s RPCs, and Modules 8 and 9 for Paxos messages that may arrive any number of times. The Two Generals theorem and Proposition A.1 explain why no layer can remove the uncertainty, and why consensus settles for agreement with eventual, not guaranteed, termination.
Further reading
- Birrell and Nelson’s RPC paper, especially §1.4 (design decisions), §2 (binding) and §3 (the packet-level protocol) (1).
- Kleppmann’s notes §1.3 (RPC), §2.1 (Two Generals) and §2.3 (system models: links, nodes, timing) (2).
- The Raft paper §5.1, §5.5, §5.6 and §8 on RPCs, idempotence, timing and clients (3); Ongaro’s thesis, chapter 6, for client interaction in more detail (5).
- The PMMC paper §1 and §3 for the channel and liveness assumptions of Multi-Paxos (4).
- Chandra and Toueg on failure detectors, the formal side of “a timeout is only a suspicion” (6).