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.
(a) request lost client server timeout f did not run (b) reply lost client server f runs timeout f ran once (c) server slow client server f runs timeout f runs late what the client sees in all three: request sent, no reply before the timeout
Figure 1. The three explanations of a missing reply. A cross marks a lost message; a dashed arrow is a slow one. Until its timeout fires, the client has observed exactly the same thing in all three executions, yet the function ran zero times, once, or will run later.

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.

This one picture introduces a large part of the course.

What the picture forcesWhere it is treated
a timeout cannot tell a crash from slownessfailure detectors, Definition 5.1, Proposition 5.2; FLP, Theorem 4.16
the client must decide whether to retryretry semantics, Definition 3.2
case (b): a retry can run twiceidempotence and deduplication, Definition 3.3, Proposition 3.5
case (c): an old request can act lateterms and ballots, Definition 5.4; delayed requests in Modules 7 and 9
what may fail at allsystem 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.

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

  1. fair loss: if and are correct and sends to infinitely often, then receives infinitely often;
  2. finite duplication: if sends to finitely often, then receives finitely often;
  3. 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.

layer adds (+) and loses (-) state machine / application applies commands, keeps client table + exactly-once effect per client command - only if the table survives crashes consensus or broadcast Raft, Paxos, reliable/FIFO broadcast + agreement and order despite crashes - liveness needs timeouts (GST) messaging layer send/deliver, or RPC stubs + ids, retries, dedup end to end - a timeout cannot tell lost from slow transport UDP datagrams or TCP byte streams + TCP: ordered bytes, one connection - ends at reset, crash or give-up IP best-effort packets + routing between hosts - drops, duplicates, reorders, delays
Figure 2. The layers underneath a consensus protocol. Each layer uses the one below; the right column says what the layer adds and where that guarantee stops. The only guarantees that survive a crash, a reconnect or a partition are the ones the upper three layers build themselves.

How do the real transports compare with the link models?

TransportClosest link modelWhat it addsWhat it does not give
IP, UDPfair-loss, if the path eventually worksports and a checksum (UDP)retransmission, deduplication, order
TCPreliable FIFO, per connectionsequence numbers, acks, retransmission, flow controlanything across a reset, a crash or a new connection
TLS over TCPturns an arbitrary link into TCP’sintegrity, authenticity, no replay inside a sessionprotection 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.

  1. 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.
  2. 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.
  3. 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.
  4. 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.

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
LineWhy it is there
nextSeq never reusedthe 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 duplicatesthe first ack may be lost; without a new ack the sender would retransmit forever
received checkthe receiver delivers each (sender, seq) once, however many copies arrive

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.

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

  1. termination: in every execution, both processes decide within finite time;
  2. agreement: in every execution, both decide the same value;
  3. validity: if , both decide retreat; if and no message is lost, both decide attack.

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
LineWhy it matters
same req on every retrythe identifier names the logical call, not the copy
retries exhaustedwith it: at-most-once from the caller’s view; without it: at-least-once
s < lastSeq[c]: dropthe client has one outstanding call, so it already has this reply
s == lastSeq[c]: replaycase (b) of Figure 1; the retry gets the old result, does not run
atomicallya crash between running and recording would make the retry run again
stable storagea 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 lastSeq and lastReply. Then every call is executed exactly once, and the client receives the reply of that execution.

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 styleMessage passing
shapeone caller, one callee, one replysend and receive; replies are just more messages
the callerblocks until the reply or a failurecontinues; handles replies as events
fitsclient and serverbroadcast, gossip, protocol rounds
in these notesclients of Raft and Paxosbroadcast (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
LineWhy it matters
no wait anywhereeach handler runs to completion; a crashed or slow follower costs only its own requests
timer re-sends after Rthe same request is a heartbeat and a retry; it repeats forever while the leader leads
fresh request from the current loga retry carries the latest entries and commitIndex, so an old request is never needed again
term != currentTerma 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.

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 "" case in the proofs of Theorem 7.4 and Lemma 7.6, where a delayed request of the committing leader arrives after the entry was committed.

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:

  1. never decreases;
  2. 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.

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).

  1. 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.
  2. 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.

One detail of the Module 8 pseudocode follows from part 1. A duplicated Prepare is answered with Nack where , because the acceptor’s test is strict. The proposer’s Nack handler would abandon ballot . Safety is not affected, but a proposer should ignore a Nack whose reported ballot equals its own.

The real link, in one table. Each fact about a real network is answered by a design rule in the protocols.

Fact about the linkDesign ruleWhere
a reply may be losthandlers idempotent, retries safeProposition A.10, Proposition A.12
a slow server looks deadelections can be wrong; terms and ballots make a stale leader harmlessModules 5, 7, 9
timeouts cannot be trustedsafety must not depend on timing, only livenessTheorem 4.16, Raft §5.6
a request may run latea delayed AppendEntries or p2a after a newer leader must be harmlessModule 7 (), Module 9 worked example, step 6

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 and the client table of §8.

Initially every log holds one committed and applied entry, = (term 1, SET y 0, client c, serial 3). So everywhere, every client table says “c: last serial 3”, every commitIndex is 1, and on A, and . Client c now sends INC y with serial 4, a command that is not idempotent. We write and for log entries of term 1 that both carry (INC y, c, 4).

StepEventLogs A / B / COn A: match B, C; commitState machines
1A appends ; AE(prev 1, , commit 1) to B and C / / 1, 1; 1
2B appends , replies (1, true, 2); the A-B connection resets, reply lost / / 1, 1; 1
3client times out, resends (INC y, c, 4); A appends ; AE(prev 1, , commit 1) to B (new connection) and C / / 1, 1; 1
4B: index 2 matches, appends , replies (1, true, 3); A commits 3, applies 2 and 3 / / 3, 1; 3A:
5C (slow) processes both AEs in order; replies (1, true, 2), (1, true, 3)all 3, 3; 3A:
6heartbeat AE(prev 3, [], commit 3); B and C commit 3, apply 2 and 3all 3, 3; 3all:

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 on A, and step 6 would set on B and C: consistent replicas, all wrong. Replication alone does not deduplicate; it faithfully replicates the duplicate.

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).
1.
Birrell AD, Nelson BJ. Implementing Remote Procedure Calls. ACM Transactions on Computer Systems. 1984;2(1):39–59.
2.
Kleppmann M. Distributed Systems: Lecture Notes [Internet]. University of Cambridge, Computer Science Tripos Part IB; 2021. Available from: https://www.cl.cam.ac.uk/teaching/2122/ConcDisSys/dist-sys-notes.pdf
3.
Ongaro D, Ousterhout J. In Search of an Understandable Consensus Algorithm. In: Proceedings of the USENIX Annual Technical Conference (ATC). 2014. p. 305–19.
4.
van Renesse R, Altinbuken D. Paxos Made Moderately Complex. ACM Computing Surveys. 2015;47(3):42:1-42:36.
5.
Ongaro D. Consensus: Bridging Theory and Practice [phdthesis]. Stanford University; 2014.
6.
Chandra TD, Toueg S. Unreliable Failure Detectors for Reliable Distributed Systems. Journal of the ACM. 1996;43(2):225–67.