Skip to main content

Lesson 24 of 26 · 12 min read

Distributed systems, unreliable networks, and RPC

Build reliable messaging abstractions over drop-prone networks, compare TCP vs UDP, and see how Remote Procedure Call (RPC) stubs serialize arguments and retry safely.

Four RPC concepts: Packet loss, Client stub, Timeout retry, and Idempotency.
RPC marshals parameters across unreliable networks, relying on timeouts, sequence IDs, and idempotency on retry.
Course syllabus · lesson 24 of 26
In this lesson

In a distributed system, a client can remain healthy while its server crashes, and both can remain healthy while the network between them drops traffic. A caller observing silence has to make progress with incomplete information.

The crux of the problem is how to build working software systems out of unreliable networks and partially failing machines — turning dropped, duplicated, or corrupted packets into clean abstractions like Remote Procedure Calls (RPC).

Client application calls local stub which marshals arguments and starts a retry timer over unreliable UDP to the Server stub, which deduplicates sequence IDs on retry after a lost reply.
Open full-size diagram
RPC hides network byte serialization behind local function syntax, yet timeouts, retries, and pointer limits expose distributed reality.

Trace an RPC with a lost reply

Caller call, Server idle, Client stub encode #42, Server stub waitingCallercallServeridleClient stubencode #42Server stubwaiting

Step 1 of 4

Marshal the request

The client stub serializes the arguments and attaches a request ID, 42 in this trace.

Unreliable networks -> Reliable layers

Networks drop packets when switch buffers overflow, flip bits over noisy links, reorder datagrams across routes, and deliver late duplicates. On raw UDP/IP, sendto() simply fires a best-effort packet with no promise it ever arrives:

  • Detecting corruption: A UDP checksum, when used, lets the receiver reject corruption it detects. It covers the UDP header and payload plus a pseudo-header derived from IP fields. Damage that preserves the check value can still pass.
  • Handling packet loss: Pair acknowledgments (ACKs) with timeouts and retries! If the sender sees no ACK within T milliseconds, it retransmits the packet.
  • Handling duplicates: What if the original packet arrived and ran, yet the ACK dropped on the return trip? Without a sequence number (seq = 42), a blind retry could execute a non-idempotent charge twice! Sequence counters let the receiver recognize already-completed sequence IDs.

For streaming byte pipes, TCP handles sequence numbers, flow control and congestion control, and ordered retries inside the OS kernel. For lightweight request/response workloads, systems frequently layer custom RPC retries straight over UDP or tuned TCP pools.

Delivery and execution need separate evidence

A message can cross several milestones. The sending process hands bytes to its local kernel. The receiver's transport accepts them. A server thread reads and validates the request. The handler may change durable state. Finally the reply reaches the caller. Each later milestone requires its own evidence. A successful local send only reports the first. A TCP acknowledgment shows receipt by the peer's transport and says nothing about whether a worker has executed the operation. A reply can report durability when the server implementation waits for it before replying.

For a simple reliable channel over datagrams, use one outstanding message and a sequence number. Send message 42 and start a timer. On first receipt the receiver delivers 42 to its consumer and acknowledges it. If the acknowledgment drops, the sender retransmits 42. The receiver acknowledges the duplicate without delivering it again. The next new message has a different number. For multiple outstanding messages, the receiver also needs a window or another way to admit valid out-of-order arrivals and distinguish them from old duplicates. Finite sequence numbers require a reuse rule so a sufficiently delayed packet cannot be mistaken for a new one.

A fixed timeout illustrates the latency tradeoff. With a 35 ms trip each way and 30 ms of service, an unloaded call could finish in 100 ms. A timeout of 80 ms triggers a needless retry while that call is finishing. A 200 ms timeout leaves more room for variation but waits longer to retry if the first request drops. A runtime can start with 200 ms and double the interval, sending at 0, 200, and 600 ms if nothing returns. With a 1-second application deadline, it stops waiting at 1,000 ms. Randomizing retry times helps a population of callers avoid sending synchronized bursts after an outage.

Remote Procedure Call (RPC): Making remote calls look local

Instead of forcing every developer to hand-pack raw byte buffers and sockets (Distributed Shared Memory fails poorly across page-fault networks), RPC (pioneered by Birrell & Nelson) lets client code invoke rc = remote_add(a, b) looking almost identical to a local function call!

An RPC runtime splits into two halves, usually generated automatically by a stub generator:

  1. Client Stub (Marshaling): Packages the procedure ID and serialized arguments (marshaling / encoding endianness and variable arrays into flat bytes), dispatches the request message, and waits with a retry timer until the reply returns and unpacks (unmarshals) the result.
  2. Server Stub + Thread Pool (Unmarshaling): Listens on a socket, dispatches incoming calls to a concurrent worker thread pool so workers can serve independent calls concurrently, invokes the real server function, and sends the serialized reply back!
Code exampleTrace
Client App -> Stub(marshal args, seq=101, start timer) -> UDP Packet
Server Stub(unmarshal) -> check reply cache(C, 101) -> run handler -> cache + ACK

The two stubs need a wire contract. One possible fixed request header contains a version, operation number, client epoch, sequence number, and payload length. A withdrawal payload can encode account 7 and amount 20 as two 32-bit integers in network byte order, yielding the eight data bytes 00 00 00 07 00 00 00 14. The server checks the version, the declared length, and the expected schema before dispatching. The client matches a reply to its pending call by the same request identity. Late replies for completed calls can be discarded.

The server's dispatch queue and worker pool put separate bounds on accepted and actively executing work. If all workers are busy, queue delay can exceed the retry interval even on a fast network. Counting requests and retries separately can expose this. A duplicate lookup before expensive work prevents duplicate execution, although parsing and receiving the retry still consume resources.

Four places RPC breaks the "local call" illusion

Even the cleanest RPC stub generator cannot pretend a network works just like local RAM:

  • Pointers fail completely: Passing a pointer like struct node *head passes a virtual address inside the client's RAM — meaningless on the server! Data graphs must be deep-serialized into flat byte messages.
  • No shared global state: Calling rpc() cannot reach across the network to read a client's global integer.
  • Partial failure semantics (At-Least-Once vs At-Most-Once): When a client times out, it cannot distinguish server crashed before running from server ran and the reply dropped. Retries without deduplication can execute a request more than once. An at-least-once execution guarantee requires retries to continue until some attempt reaches a working server. At-most-once execution allows zero executions and needs a retained record that prevents duplicate execution. A caller that reaches its deadline can still have an unknown outcome under either design.
  • Setting the timeout (TIP: BE CAREFUL SETTING THE TIMEOUT VALUE): Too short triggers duplicate retry floods against a slow server; too long leaves callers hung needlessly (exponential backoff + RTT estimation adapt dynamically).

Make the duplicate cache a state machine

Key each entry by client identity, a client incarnation such as a boot epoch, and the call's sequence number. Retrying keeps the full key and arguments. Restarting a client that resets its counter needs a fresh incarnation so its first new operation cannot retrieve an old result. Reusing a key for different arguments is a protocol error. Suppression is useful both for lost replies and when several worker threads receive the same request concurrently.

  1. Absent. Claim the key atomically and create an in-progress entry before starting the handler. If both workers can observe an absent key and start the handler, caching completed replies cannot prevent the race.
  2. In progress. A duplicate can wait for the first worker's reply or receive a response that tells it to retry later. It must not enter the handler a second time.
  3. Complete. Publish the reply, then return it. A retry gets the original result even if later operations have changed the account. A cache hit returns the reply associated with this particular call.
  4. Retired. Bounded storage requires a retention contract. One design retains replies for the supported retry interval and rejects older requests once their result is evicted using a per-client watermark. Another waits for an acknowledgment that the client has advanced past the call. If forgetting an entry makes an old request look new, a sufficiently late retry can repeat the effect.

An in-memory cache survives retransmissions during one server lifetime. A persistent implementation can update the balance and store the deduplication record in the same transaction, so a crash preserves both or neither. Writing the balance first leaves a gap in which a retry can deduct twice. Writing the record first leaves a gap in which the server can report a result without applying the withdrawal. If the handler affects an external system outside that transaction, the external effect also needs an idempotency or reconciliation protocol.

Choose the retry rule from the operation

A request to read a file block can usually be sent again without repeating a mutation. It may yield newer data because another client wrote in the meantime. A fixed-value assignment can have the same final effect when repeated in isolation. An increment or append can change state each time it runs. To see the difference, start with a counter at 10 and issue two deliveries of the same request. Assigning 12 twice ends at 12, while adding two twice ends at 14. Even an assignment retry can overwrite a newer assignment by another client. A version precondition can make such a stale update fail instead.

Cancellation has its own race. The caller giving up can stop local work and possibly send a cancellation request, but the server might have completed the operation before cancellation arrived. If cancellation is part of the protocol, the server needs a defined point at which it can still abort and a reply that indicates whether it reached that point in time.

Worked trace: lost request vs. lost reply over UDP RPC

Trace Client C calling withdraw(acct=7, amount=20) with request seq = 101 over raw UDP:

  1. Case A (Request drops before reaching server): Client sets timer T = 200 ms, transmits (seq=101, acct=7, 20). Timer expires with no reply -> Client retransmits (seq=101, acct=7, 20). Server receives 101 for the first time, deducts 20, caches reply balance=80 under (C, 101), and sends reply! Total deduction = 20.
  2. Case B (Reply drops on return): Server receives (C, 101), deducts 20, and replies balance=80, which gets dropped on the wire! Client times out at 200 ms and resends (C, 101). Because the server sees (C, 101) already exists in its reply cache, it skips re-running withdraw() and returns the cached balance=80! Total deduction = 20 instead of 40!
  3. Change one input: What breaks in Case B if the server restarts/crashes after deducting 20 from persistent disk storage, losing its volatile in-memory (C, 101) reply cache before the client retries? Without persisting that deduplication log on disk alongside the balance update, the rebooted server runs seq = 101 a second time and deducts another 20, for a total deduction of 40.

If the deadline expires and the balance changes from 100 to 80, the client still cannot use that observed balance alone to prove which operation ran. Another caller could have changed the same account. Querying the result by the original request identity lets the service report a recorded outcome. Submitting a fresh request number represents another withdrawal.

Next, see how real distributed file systems (NFS and AFS) and virtual machine monitors (VMMs) use these primitives in distributed file systems and hypervisors.

Before you move on

Try it in your workspace

Trace an RPC call across an unreliable UDP network: client stub marshals arguments, sets a timeout, retries on packet loss, and relies on server-side reply/sequence tracking.

Keep a short note of what you tried, what passed, and what you still need to check.

Your practice record

0 of 3 checked.

Saved in this browser when storage is available. Uncheck any item to revisit it. This is your own record, not an assessment.