Maps to: CMU 15-440/640 Spring 2026, learning outcome “communication and remote procedure call” — control semantics and language limitations; serialization and de-serialization. Project: P1 (Transparent Remote File Operations) — an RPC system in C with hand-written marshalling (“you will not be using an IDL or stub generator”; no XDR or other marshalling libraries). Problem set: PS1 includes a struct-layout and byte-order question; this lecture gives the method. Sources: the public course page and the P1 handout; A. D. Birrell and B. J. Nelson, Implementing Remote Procedure Calls (ACM TOCS 2(1), 1984); Tanenbaum & van Steen, Distributed Systems (3rd ed.), ch. 4; J. Waldo et al., A Note on Distributed Computing (1994); the System V i386/x86-64, AAPCS and Microsoft x64 ABIs as implemented by clang. The slides are not public; this is not a transcript. All numbers come from
code/lecture03/, run on the author’s machine (Apple M4 Pro, macOS, Python 3.13, Apple clang 21). Code:code/lecture03/. Reading time: ~80 minutes, plus ~25 to run the demos.
0. How to read this lecture
0.1 Learning goals
After this lecture you should be able to:
- Explain why RPC exists, and walk through the ten steps of one remote call: client stub, marshalling, transport, dispatcher, server stub, and back.
- Explain why sending a raw C struct between machines fails — byte order, type sizes, alignment and padding — and compute a struct’s layout on a given ABI.
- Design a marshalling format: self-describing vs schema-driven, fixed vs variable size, text vs binary, and how to make it robust to truncated or hostile input and evolvable across versions.
- Explain the language limitations of RPC: call-by-reference vs copy/restore (aliasing), pointer-linked data (sharing and cycles) and how flattening solves it, global state, performance, partial failure.
- Describe interfaces, stubs and IDLs, and binding (how a client finds a server).
- Reason about server threading and about the cost of an RPC, and choose between chatty and chunky interfaces.
0.2 Prerequisites and scope
- Prerequisites: Lectures 1–2 (partial failure; RTT; TCP has no message boundaries, so messages need framing). From 15-213: struct alignment, two’s complement, pointers, and library interposition (
LD_PRELOAD). - Scope: the mechanism of RPC when nothing fails. What happens when a message is lost or a server crashes mid-call — the call semantics — is Lecture 4.
0.3 Section → code map
| Section | Idea | Code in code/lecture03/ |
|---|---|---|
| §2 | anatomy of one call, bytes on the wire | 04_rpc_by_hand.py Part A |
| §3.1–3.3 | byte order, ABIs, why raw structs fail | 01_bytes_on_the_wire.py (+ abi_layout.py, clang-verified) |
| §3.4–3.6 | designing, testing and evolving a format | 02_marshalling.py (+ wire.py) |
| §4 | aliasing, sharing, cycles, flattening | 03_pointers_and_graphs.py |
| §5–6 | interfaces, stubs, binding | rpc.py, 04_rpc_by_hand.py Parts A–B |
| §7 | server threads | 04_rpc_by_hand.py Part D, 05_rpc_costs.py Part D |
| §8 | what a call costs; chatty vs chunky | 04_rpc_by_hand.py Part C, 05_rpc_costs.py Parts A–C |
Shared modules introduced here: abi_layout.py (C layouts on seven ABIs, verified with clang), wire.py (a hand-written binary marshalling format with framing) and rpc.py (interfaces, generated stubs, a threaded dispatcher, a registry). Lecture 4 reuses wire.py.
0.4 Notation
- ABI (application binary interface): the platform’s rules for type sizes, alignment, byte order and calling conventions. Named here by CPU and OS, e.g.
i386-linux,x86_64-windows. - ILP32 / LP64 / LLP64: which of
int,long, pointers are 32 or 64 bits. ILP32: all 32. LP64 (Linux, macOS 64-bit):longand pointers 64. LLP64 (64-bit Windows): only pointers (andlong long) 64. - Hex bytes are written
0a 0b 0c 0d, lowest address first.
1. Why RPC?
1.1 The problem: network code everywhere
With only sockets, every place a program needs a remote resource must build a message, send it, wait, parse the reply, handle errors — the same twenty lines, slightly different each time, sprinkled through the application. The P1 handout says it directly: it is tedious and inelegant to insert ad-hoc networking code every place software needs remote resources, so we use layering to hide the network behind a clean abstraction.
1.2 The idea: make a remote call look like a local one
Birrell and Nelson’s 1984 paper chose the most familiar abstraction in programming — the procedure call — on the grounds that programmers already understand it: arguments go in, a result comes out, control returns to the caller. If a call to a remote server looks exactly like a call to a local library, then distributed programs can be written, read and reasoned about like ordinary ones.
The trick is a stub: a local procedure with the same name and signature as the remote one, which impersonates it. The caller calls the stub; the stub does the network work; the caller never sees a socket. On the server, a matching piece of code receives the request and calls the real procedure, which never sees a socket either.
Intuition. A stub is like a travel agent. You ask the agent (locally, in your language) to book a hotel abroad. The agent translates your request into the hotel’s format, phones, waits, translates the answer back. To you it is one local request — until the phone line drops, which is exactly where the analogy (and RPC’s transparency) breaks (Lecture 4).
1.3 Where RPC is used
Almost every distributed system is built from it: NFS is defined as a set of RPCs; Java RMI (Project 2) is RPC on objects; gRPC/Protocol Buffers and Apache Thrift run most data-center microservices; a Paxos “Prepare” message (Lecture 20) is a remote call to an acceptor. Project 1 builds one by hand so that you see every piece.
2. Anatomy of one remote call
Here is what happens when a client executes result = calc.add(2, 3), in the order it happens:
CLIENT PROCESS SERVER PROCESS
caller ──(1) calc.add(2,3)──► client stub dispatcher ──(6) impl.add(2,3)──► implementation
(2) marshal args ▲ │
(3) send frame ───────(4)──┼── network ──► (5) receive, │
│ unmarshal │
caller ◄─(10) return 5 ─── client stub │ │
(9) unmarshal reply ◄──(8)─┴── network ◄── (7) marshal result
- The caller invokes the client stub like any function.
- The stub marshals the procedure name and arguments into bytes:
{"id": 1, "proc": "add", "args": [2, 3]}. - It frames the bytes (a length prefix, because TCP has no message boundaries — Lecture 2) and hands them to the OS.
- The network carries them.
- On the server, the RPC runtime reads exactly one frame and unmarshals the request.
- The dispatcher checks the procedure exists and has the right arguments, and calls the implementation.
- The result (or the exception) is marshalled into a reply carrying the same request id.
- The reply crosses the network.
- The client stub unmarshals it, checks the id matches, and
- returns the result to the caller — or raises the remote exception.
Demo 04_rpc_by_hand.py, Part A, runs this with the course’s rpc.py over real loopback sockets and prints the actual request frame — 74 bytes:
0: 00 00 00 46 08 00 00 00 03 05 00 00 00 02 69 64 length=70 | dict, 3 entries | str(2) "id"
16: 03 00 00 00 00 00 00 00 01 05 00 00 00 04 70 72 int 1 | str(4) "pr
32: 6f 63 05 00 00 00 03 61 64 64 05 00 00 00 04 61 oc" | str(3) "add" | str(4) "a
48: 72 67 73 07 00 00 00 02 03 00 00 00 00 00 00 00 rgs" | list, 2 items | int ...
64: 02 03 00 00 00 00 00 00 00 03 ... 2 | int 3
Everything in this lecture is about one of those ten steps. §3 is step 2/5/7/9 (marshalling), §4 is what marshalling cannot express, §5–6 are how the stub and the address come to exist, §7 is step 6 under concurrency, §8 is what the whole thing costs.
3. Marshalling: one external representation for every machine
3.1 Byte order
A multi-byte integer must be stored in some order of bytes in memory. Little-endian machines (x86, ARM in its usual mode) put the least significant byte at the lowest address; big-endian machines (PowerPC, SPARC, IBM Z mainframes, and by convention the Internet’s protocol headers — “network byte order”) put the most significant first. Demo 01_bytes_on_the_wire.py, Part A:
| value sent by a little-endian machine | bytes on the wire | read by a big-endian receiver |
|---|---|---|
| 1 | 01 00 00 00 | 16,777,216 |
| 258 | 02 01 00 00 | 33,619,968 |
| 1000 | e8 03 00 00 | 3,892,510,720 |
Neither order is “right”; the problem is only disagreement. The fix is to agree on one order on the wire — big-endian, by Internet tradition (htonl/ntohl in C convert host ↔ network order; on a big-endian host they do nothing).
3.2 Sizes, alignment and padding: one declaration, three sizes
Now a struct. C compilers place each field at an offset that is a multiple of its alignment, inserting padding bytes as needed, and round the total size up to the largest alignment (so arrays of the struct stay aligned). But the sizes and alignments themselves are decided by the platform’s ABI, and ABIs differ. Demo 01, Part B, lays out
struct Reading { char kind; double value; uint16_t sensor; long seq; };
on seven ABIs — and, if clang is installed, asks the real compiler to confirm each layout by compiling a file full of _Static_assert(offsetof(...) == ...) for each target (clang -target <triple> -fsyntax-only can type-check code for platforms it cannot run):
| ABI | byte order | sizeof | padding | offsets (kind, value, sensor, seq) | clang agrees |
|---|---|---|---|---|---|
| i386-linux (ILP32) | little | 20 | 5 | 0, 4, 12, 16 | yes |
| armv7-linux (ILP32) | little | 24 | 9 | 0, 8, 16, 20 | yes |
| x86_64-linux (LP64) | little | 32 | 13 | 0, 8, 16, 24 | yes |
| arm64-macos (LP64) | little | 32 | 13 | 0, 8, 16, 24 | yes |
| x86_64-windows (LLP64) | little | 24 | 9 | 0, 8, 16, 20 | yes |
| powerpc-linux (ILP32) | big | 24 | 9 | 0, 8, 16, 20 | yes |
| s390x-linux (LP64) | big | 32 | 13 | 0, 8, 16, 24 | yes |
(As a negative control, the demo also feeds clang a deliberately wrong table — “i386 aligns double to 8” — and clang rejects it, so the check is real.) Three separate facts vary:
- Type sizes:
longis 4 bytes on ILP32 and on 64-bit Windows, 8 on 64-bit Linux and macOS. - Alignment rules: on i386 Linux,
doubleinside a struct is aligned to only 4 bytes, sovaluesits at offset 4 instead of 8; on 32-bit ARM it is aligned to 8. - Byte order: PowerPC and IBM Z are big-endian.
The memory maps make the padding visible (k = kind, v = value, s = sensor, q = seq, . = padding):
i386-linux (20 bytes) x86_64-linux (32 bytes)
0: k . . . v v v v 0: k . . . . . . .
8: v v v v s s . . 8: v v v v v v v v
16: q q q q 16: s s . . . . . .
24: q q q q q q q q
3.3 What happens if you “just send the struct”
Part C plays out send(sock, &r, sizeof r, 0) twice on the sender and recv(sock, &r, sizeof r, 0) on a receiver of a different kind:
| sender → receiver | sizeof tx / rx | correct? | first struct as received |
|---|---|---|---|
| x86_64-linux → arm64-macos | 32 / 32 | yes | kind=1 value=21.5 sensor=7 seq=1 |
| i386-linux → x86_64-linux | 20 / 32 | no | value=−2.2×10²²⁶, seq=−4.6×10¹⁸ (it read 12 bytes of the next struct) |
| x86_64-linux → x86_64-windows | 32 / 24 | no | value and sensor fine, but seq = 0xEEEEEEEE — read from the sender’s padding |
| x86_64-linux → s390x-linux | 32 / 32 | no | sensor=1792, seq=2⁵⁶ (byte order) |
Three different failure modes, none of which raises an error: a size mismatch makes the receiver consume part of the next message (and every later message is misaligned too); a field read from padding returns whatever bytes were there; byte order scrambles every number. The two identical-ABI machines worked — which is exactly why this bug survives testing on one developer’s laptop and appears in production.
And a security note: real padding bytes contain whatever was in memory before (the demo fills them with 0xEE to make them visible). Sending raw structs can leak fragments of secrets, a known class of information-disclosure bugs.
3.4 The fix: marshalling into an agreed format
Marshalling (serialization) converts each value from the sender’s native representation into an external representation that both sides agree on, independent of any machine; unmarshalling converts back into the receiver’s native representation. Neither side ever sees the other’s memory layout.
wire.py is a small format written for these notes (in the spirit of MessagePack or CBOR):
| value | encoding (multi-byte numbers big-endian) |
|---|---|
None / False / True | one tag byte 00 / 01 / 02 |
| int | tag 03 + 8 bytes, two’s complement (range ±2⁶³) |
| float | tag 04 + 8-byte IEEE 754 double |
| str | tag 05 + 4-byte length + UTF-8 bytes |
| bytes | tag 06 + 4-byte length + raw bytes |
| list / tuple | tag 07 / 09 + 4-byte count + the elements |
| dict (str keys) | tag 08 + 4-byte count + key/value pairs |
Plus framing: each message on a TCP connection is a 4-byte length followed by the payload, written with one sendall (no Nagle penalty — Lecture 2).
Every marshalling format answers the same design questions, and real formats answer them differently:
- Self-describing or schema-driven?
wire.pyputs a type tag before every value, so a receiver can decode a message without knowing its type in advance (like JSON, MessagePack). Schema-driven formats (Sun’s XDR, Protocol Buffers, Thrift) rely on both sides having the same interface definition, so the bytes need not say “this is an int” — smaller, but useless without the schema. - Fixed or variable size?
wire.pyspends 9 bytes on every int; Protocol Buffers’ “varints” spend 1 byte on small numbers. Fixed is simpler and faster to parse; variable is smaller. - Text or binary? JSON is human-readable and universal, but bigger for numbers and cannot carry raw bytes.
Demo 02_marshalling.py, Part B, compares sizes:
| message | wire.py | JSON | pickle |
|---|---|---|---|
RPC request add(2, 3) | 70 | 34 | 51 |
| 1000 small ints | 9,005 | 3,891 | 2,760 |
| 1000 floats | 9,005 | 16,714 | 9,016 |
| a text record | 298 | 273 | 290 |
| 1 KB of binary data | 1,029 | n/a | 1,042 |
There is no universally best format: JSON wins on small ints written as short decimals, loses badly on floats (which need ~17 decimal digits each), and cannot carry bytes at all. (Python’s pickle is shown for comparison only: it is Python-specific and must never be used to decode untrusted input, because unpickling can execute code.)
3.5 Testing a format like an adversary
A marshalling library must satisfy one property — loads(dumps(v)) == v for every value it accepts — and must reject everything else loudly. Demo 02, Part A, checks the property on 3,000 random nested values (property-based testing), using an equality stricter than Python’s == (which would not notice -0.0 becoming 0.0 or True becoming 1): 3,000/3,000 round-tripped exactly, including NaN, ±∞, −0.0, 2⁶³−1, Chinese text and emoji. Values with no representation — 2⁶⁴, sets, dicts with integer keys, arbitrary objects — are rejected with an error rather than silently converted.
The receiver must also survive any byte string, because bytes from the network may be truncated, corrupted or malicious. Part C attacks the decoder:
- every one of the 93 truncations of a 93-byte message: all rejected;
- a “length bomb” — a string claiming to be 4,294,967,295 bytes long, followed by 2 bytes — rejected instantly, because every length is checked against the bytes actually present before allocating or reading;
- 5,000 random one-byte corruptions:
| outcome | count |
|---|---|
| rejected (MarshalError) | 3,008 |
| decoded to a different, perfectly valid message | 1,992 |
| decoded to the same value | 0 |
| crashed with another exception | 0 |
The first and last rows are the robustness we wanted: no corruption crashed the decoder. The second row is the sobering one: 40% of corruptions produced a valid message that says something else (a different amount, a different name). No amount of parsing strictness can detect that — it takes a checksum over the message, and Lecture 4’s end-to-end argument explains where that check must live.
3.6 Evolution: what happens when the interface changes
Systems are upgraded one machine at a time, so a new client will talk to an old server and vice versa. Part D: a v2 sender adds a currency field to a withdrawal message.
| what the v1 receiver gets | result |
|---|---|
| named fields, v1 message | withdraw amount=100 |
| named fields, v2 message | withdraw amount=100 (unknown field ignored) |
positional fields, v2 message [op, currency, amount] | withdraw amount='EUR' — silently wrong |
Named (or numbered) fields let old code skip what it does not understand; positional encodings break the moment a field is inserted. This is why Protocol Buffers identifies every field by a number that is never reused, and why interface definition languages have explicit rules for compatible changes.
4. What marshalling cannot express: the language limitations of RPC
The course lists “control semantics and language limitations” as an RPC learning outcome. The deepest limitation is the pointer: an address is meaningful only inside one address space. Whatever the stub sends, it cannot send “the caller’s object”.
4.1 Parameter passing: by reference, by value, copy/restore
A local call can pass a reference: the callee modifies the caller’s object. A remote call can pass only bytes. Two approximations exist:
- call by value: send a copy; changes made by the server are lost;
- copy/restore (value-result): send a copy, and in the reply send back the final value of each argument, which the client stub writes into the caller’s objects.
Copy/restore looks like call-by-reference — until two arguments are the same object (aliasing). Demo 03_pointers_and_graphs.py, Part A, calls bump_both(x, x), which adds 1 to each argument:
| how the call is made | x[0] afterwards (started at 0) |
|---|---|
| local call (by reference) | 2 |
| remote, call by value | 0 |
| remote, copy/restore | 1 |
On the server the one object has become two copies; each is bumped once; the client restores both, and the last write wins. No stub design can make this case behave locally without knowing about the aliasing.
4.2 Pointer-linked data: sharing and cycles
Linked structures — trees, graphs, lists — are a web of pointers. Marshalling by value follows each pointer and copies whatever it finds. Part B builds a DAG in which node k points twice to node k−1:
| depth | nodes in memory | by value: bytes | by value: nodes rebuilt | flattened: bytes | flattened: nodes rebuilt |
|---|---|---|---|---|---|
| 1 | 2 | 126 | 3 | 94 | 2 |
| 8 | 9 | 21,462 | 511 | 353 | 9 |
| 16 | 17 | 5,504,982 | 131,071 | 649 | 17 |
Marshalled by value, 17 nodes become 131,071 on the receiver — exponential in the depth — and identity is lost: what were two pointers to one node are now two independent copies. A cycle is worse: a doubly-linked list cannot be marshalled by value at all (the copy never ends; the demo stops at 60 levels).
4.3 The fix: flatten pointers into ids
Part C flattens the graph: every distinct object gets an integer id the first time it is met, each pointer is replaced by its target’s id, and the result is a table [[label, [child ids]], ...] plus the root’s id. The receiver rebuilds it in two passes (create all nodes, then wire the pointers). The 17-node DAG becomes 649 bytes and rebuilds into exactly 17 nodes with the sharing intact (8,482× smaller); the 100-node doubly-linked list round-trips with an identical structure. This “pointer swizzling” is how object databases, Java serialization and many RPC systems ship object graphs.
The third option is not to copy at all: send a remote reference — an id the server can resolve — and make further calls through it. Java RMI (Project 2) passes remote objects this way: the receiver gets a stub for the object, not a copy.
4.4 What else RPC cannot hide
Waldo, Wyant, Wollrath and Kendall (A Note on Distributed Computing, 1994) argue that local and remote calls differ in four ways no interface can paper over:
- Latency: a remote call is ~1,000× slower (§8) — so interfaces must be designed for it.
- Memory access: pointers and shared global variables do not cross address spaces (§4.1–4.3).
- Partial failure: a local call either returns or the whole program dies; a remote call can leave you not knowing whether it happened (Lecture 1, Lecture 4).
- Concurrency: the server is serving other clients at the same moment (§7).
The lesson is not “don’t use RPC”, but “don’t pretend it is local”: a good RPC interface makes remoteness visible where it matters — timeouts, error codes, batch operations, explicit ids.
5. Interfaces, stubs and IDLs
Client and server must agree on the interface: the procedures, their parameters and types. In rpc.py it is a dictionary:
CALCULATOR = rpc.Interface("Calculator", {
"add": ["a", "b"], "divide": ["a", "b"], "stats": ["values"], "count": [],
})
In production systems it is written in an interface definition language (IDL) — a .x file for Sun RPC’s rpcgen, a .proto file for gRPC, a Java interface extending Remote for RMI — and a stub generator compiles it into client stubs and server skeletons in each language, together with the marshalling code for every type. rpc.make_stub does the same thing at run time: for each procedure name it builds a closure that marshals its arguments, sends the request, waits and unmarshals, and attaches it to the stub object.
The interface lets both sides check calls. Demo 04, Part B:
| call | what the caller sees |
|---|---|
calc.divide(1, 0) | RemoteError(ZeroDivisionError): raised in the server, re-raised here |
calc.add(1) | TypeError before anything is sent (the stub knows add takes 2 arguments) |
calc.multiply(2, 3) | AttributeError: the stub has no such method |
a raw request for multiply | the server’s dispatcher replies NoSuchProcedure |
calc.stats([]) | RemoteError(ZeroDivisionError): the mean of an empty list |
Exceptions cross the network as values: the server catches them and puts the type and message in the reply, and the client stub raises an equivalent exception. (Note that the remote stats([]) error is reported as an exception type name: the client may not even have the server’s exception classes — another small leak of remoteness.)
Project 1 deliberately forbids IDLs and stub generators: you write each stub and its marshalling by hand, in C, for the eight file-system calls plus getdirtree. That is the best way to learn what a generator does — and §4.2 tells you why getdirtree, which returns a tree of pointers, is the interesting one.
6. Binding: how does the client find the server?
Before the first call, the client stub needs the server’s address. Options, from rigid to flexible:
- Compiled-in or configured address (host and port in a config file or environment variables — P1’s client reads the server’s address and port from environment variables). Simple; breaks when the server moves.
- A name server / registry: servers register “service name → address”; clients look names up at run time.
rpc.pyincludes one (aRegistryinterface withregister,lookupandnames, itself served by RPC — demo 04’sbind()uses it). Sun RPC uses a port mapper on a well-known port; Java RMI uses the RMI registry (Project 2 creates one on a given port); large systems use DNS plus service-discovery systems. - Late binding adds indirection, so a service can move, be replicated or be upgraded without changing clients. The price: the registry is now a dependency that must itself be available — the recurring pattern of distributed systems, where every solution introduces a new component that can fail.
7. The server is a concurrent program
A server serves many clients at once. rpc.RpcServer uses the simplest structure: one thread accepts connections, and each connection gets its own thread that loops “receive request → dispatch → send reply”. (Alternatives: a fixed thread pool, or an event-driven loop over many sockets with select/epoll — the 15-213 concurrency lectures compare them.)
Two consequences:
- Shared state needs synchronization. The calculator’s
count()procedure increments a counter shared by all clients. Demo 04, Part D, runs two clients that callcount()200 times each, concurrently: thanks to a lock in the implementation, together they received exactly the values 1..400, each once (and in our runs the two clients’ calls were interleaved in the server — how exactly depends on the OS scheduler). Without the lock, two threads could read the same old value and both return it. - Threads help when handlers wait, not when they compute. Demo
05_rpc_costs.py, Part D, measures total throughput with 1–8 concurrent clients:
| clients | add() calls/s (CPU-bound) | wait_io(1 ms) calls/s (handler waits) |
|---|---|---|
| 1 | 29,854 | 768 |
| 2 | 28,312 | 1,516 |
| 4 | 23,112 | 2,934 |
| 8 | 21,150 | 5,841 |
Python executes one thread’s bytecode at a time (the global interpreter lock), so CPU-bound handlers do not run in parallel — with 8 clients, throughput even fell to ~0.7× from contention. Handlers that wait (here sleep, standing for a disk read or a database query) release the lock, so their waits overlap: 8 clients give ~7.6×. Real servers mostly wait — on disks, other servers, databases — which is why threading (or asynchronous I/O) matters so much for them. (In C or Java, CPU-bound handlers also run in parallel on several cores.)
8. What an RPC costs, and why interface design matters
8.1 One small call
Demo 04, Part C: the same add(i, 1) costs ~26 ns as a local method call (median of batches of 10,000) and 25–30 µs as an RPC over loopback in three runs — about 1,000×. Demo 05, Part B, breaks one small call down:
| component | time (one run) |
|---|---|
full RPC stub.add(2, 3) | 26.6 µs |
| raw framed round trip of the same size, no marshalling | 16.0 µs |
all marshalling of one call with wire.py (pure Python): encode + decode request and reply | 8.5 µs |
… the same with json (implemented in C) | 3.4 µs |
… the same with pickle (implemented in C) | 1.4 µs |
Round trip plus marshalling (24.5 µs) accounts for nearly all of the call; the rest is stub and dispatch logic. In pure Python, marshalling is about a third of a loopback call — which is why production RPC systems generate specialized, compiled marshalling code. Across a real network the round trip dominates everything.
8.2 Bigger arguments
Part A: echo(data) takes 30.8 µs for 10 bytes, 33.7 µs for 1 KB, 37.3 µs for 10 KB, 93 µs for 100 KB and 433 µs for 1 MB. Small calls are dominated by fixed per-call costs; large ones by copying and marshalling bytes.
8.3 Chatty vs chunky
Part C fetches 1,000 items from the server three ways:
| interface | total time on loopback |
|---|---|
1,000 calls of get(key) | 33.5 ms |
10 calls of get_many(100 keys) | 1.8 ms |
1 call of get_many(1000 keys) | 1.3 ms |
On loopback the batched interface is ~25× faster. Across a WAN with a 40 ms RTT, the chatty version costs at least 1,000 × 40 ms = 40 seconds; the chunky one about 40 ms. This is the most important rule of RPC interface design: every call costs at least one round trip, so design interfaces that do a lot per call — batch operations, “get all the attributes at once”, whole-file transfer (AFS, Lecture 5; Project 2). Asynchronous calls (issue several, wait for all — futures/promises) and pipelining are the complementary tools when calls cannot be merged.
8.4 A preview for Project 1: interposition
How can an unmodified program, such as cat, use a remote file? By replacing the library functions it calls. On Linux, LD_PRELOAD=./mylib.so prog makes the dynamic linker resolve open, read, … to your library first; your versions are client stubs that make RPCs, and the program cannot tell the difference. (macOS needs a different mechanism, DYLD_INSERT_LIBRARIES with an __interpose section, because of its two-level namespace — the 15-213 linking lecture covers both.) Interposition is the design technique that makes RPC transparent to existing code; P1 is built on it. These notes do not provide its code.
Summary
- RPC hides message passing behind a procedure call: a client stub marshals the arguments and sends a request; a dispatcher unmarshals it, calls the implementation and returns the result or exception in a reply with the same id.
- Raw structs do not travel. One declaration was 20, 24 or 32 bytes on seven ABIs (all confirmed by clang), because type sizes (
long), alignment rules (i386’s 4-bytedouble) and byte order differ; between different ABIs the receiver read the next message, the sender’s padding, or byte-swapped numbers — silently. - Marshalling converts to an agreed external representation (here: tagged, big-endian, length-prefixed, framed). Formats differ in self-description, size and readability; none is best for everything.
- Decoders face hostile input: all truncations and a 4 GB “length bomb” were rejected, no corruption crashed the decoder — but 40% of single-byte corruptions decoded to a different valid message, which only a checksum can catch (Lecture 4).
- Named fields make interfaces evolvable; positional ones break silently when a field is inserted.
- Pointers do not cross address spaces: copy/restore differs from call-by-reference under aliasing (1 vs 2); marshalling by value explodes on shared nodes (17 → 131,071 nodes) and fails on cycles; flattening to ids preserves sharing and cycles; remote references avoid copying.
- Interfaces/IDLs let stub generators produce stubs and marshalling code; binding finds the server (configuration, registry, port mapper, DNS).
- Servers are concurrent programs: shared state needs locks; threads help when handlers wait (7.6× with 8 clients), not when they compute (Python: 0.7×).
- A loopback RPC costs ~1,000× a local call (~27 µs vs ~26 ns), about a third of it marshalling in pure Python; across a WAN the RTT dominates. Design chunky interfaces: 1,000 calls vs 1 batched call was 25× on loopback and would be ~1,000× across a WAN.
Common pitfalls
send(sock, &s, sizeof s, 0)across machines: different sizes, padding and byte order. Marshal field by field into an agreed layout.- Forgetting framing on TCP: one
recvis not one message (Lecture 2). Length-prefix every message and loop until it is complete. - Trusting lengths from the network: always check an announced length against a maximum and against the bytes available before allocating.
- Assuming strict parsing detects corruption: it cannot detect a changed digit; use checksums end to end.
- Positional message formats that break when a field is added; prefer named or numbered fields.
- Marshalling pointers by value for shared or cyclic structures: exponential blow-up or infinite recursion; flatten to ids.
- Ignoring aliasing with copy/restore semantics: the same object passed twice behaves differently than locally.
- Unprotected shared state in a multi-threaded server.
- Chatty interfaces (one call per item) over a WAN: every call pays a round trip.
Exercises
-
Byte order. A little-endian sender writes the 32-bit integer 258 (0x00000102) and a big-endian receiver reads the four bytes as its own integer. What value does it see? What do
htonlandntohldo on a big-endian machine?Answer
The bytes on the wire are `02 01 00 00`; read big-endian that is 0x02010000 = 33,619,968. On a big-endian host, host order already is network order, so `htonl`/`ntohl` return their argument unchanged — which is why code that forgets them "works" on big-endian machines and breaks on little-endian ones. -
Layout and reordering. For
struct P { int16_t a; int64_t b; char c; };compute the size and the offset of each field on i386-linux, armv7-linux and x86_64-linux. Then reorder the fields to minimize padding. (Check yourself withabi_layout.layoutandverify_with_clang.)Answer
i386-linux: a@0, b@4 (int64 aligned to 4 there), c@12, size 16 (5 bytes of padding). armv7-linux and x86_64-linux: a@0, b@8, c@16, size 24 (13 bytes of padding). Ordering by decreasing alignment — `int64_t b; int16_t a; char c;` — gives b@0, a@8, c@10, size 12 on i386 (1 byte of padding) and 16 on the others (5 bytes). Reordering helps memory, but it does *not* make raw structs portable: the sizes still differ across ABIs. -
Marshal by hand. Write out the bytes of
wire.dumps(["hi", 5])and count them.Answer
`07 00 00 00 02` (list, 2 items) · `05 00 00 00 02 68 69` (str of length 2, "hi") · `03 00 00 00 00 00 00 00 05` (int 5) — 5 + 7 + 9 = 21 bytes. -
Aliasing. A procedure
def f(a, b): a.append(1); b.append(2)is called asf(L, L)withL = []. What isLafterwards with (a) a local call, (b) call by value, (c) copy/restore where the stub restoresathenb?Answer
(a) `[1, 2]` — both parameters are the same list. (b) `[]` — the server modified copies. (c) The server's two copies become `[1]` and `[2]`; restoring `a` sets `L = [1]`, then restoring `b` sets `L = [2]`: the result is `[2]`, matching neither (a) nor (b). -
Designing an operation. A remote counter offers
read()andwrite(v). A client increments it withwrite(read() + 1). Give two reasons why a single remoteincrement()returning the new value is better.Answer
(1) Atomicity: between another client's `read` and `write`, two clients can read the same value and both write v+1, losing an increment; a single `increment` executes atomically in the server (under its lock, demo 04 Part D). (2) Cost: one round trip instead of two. (A third reason appears in Lecture 4: `write(v)` is idempotent but `read`+`write` as a pair is not safely retryable, whereas a single `increment` with a request id can be deduplicated.) -
Chatty vs chunky. A client must learn the sizes of 200 files on a server 30 ms away (RTT). (a) How long does it take with one
statcall per file, done sequentially? (b) With onestat_manycall? (c) Name two costs of the chunky interface.Answer
(a) At least 200 × 30 ms = 6 s. (b) About one RTT, ~30 ms, plus transfer and server time. (c) The client waits for *all* results before seeing the first (latency to first result); a single failure may fail the whole batch (error handling gets coarser); messages get large (memory, framing limits); the interface is less general. Concurrent (asynchronous) single calls are an intermediate design. -
Threads and waiting. Each request needs 2 ms of CPU on the server and then waits 8 ms for a disk. (a) What throughput does a single-threaded server achieve? (b) With many threads on one CPU core, what is the maximum? (c) What then is the bottleneck?
Answer
(a) One request per 10 ms = 100 requests/s. (b) The waits can overlap but the CPU work cannot (one core): at most 1 / 2 ms = 500 requests/s, reached with about 5 threads (each 10 ms request occupies the CPU for 2 ms). (c) The CPU — adding threads beyond that only adds queueing (Lecture 11's bottleneck law). -
Evolvable formats. Protocol Buffers identifies fields by numbers and its rules say a field number must never be reused after the field is deleted. Using §3.6, explain what could go wrong if a number were reused.
Answer
Old messages (or old senders) still carry the old field under that number. A new receiver would decode the old field's bytes as the *new* field — the same silent misinterpretation as the positional `withdraw amount='EUR'` case, but now between versions that look compatible. Never reusing numbers guarantees that a number always means the same field, so old and new code can coexist.
Related project and problem set (concepts only)
- Project 1 is this lecture made concrete in C: client stubs that interpose on the C library’s file calls, your own message formats (no XDR, no IDL, no stub generator), framing over TCP, a server dispatcher, and the marshalling of awkward types (byte buffers,
struct stat, directory entries, thegetdirtreetree). §3.2–3.3 (layout), §3.4–3.5 (format design and strict decoding), §4.2–4.3 (pointer-linked data) and §8.3 (round trips) are the relevant ideas; the design itself is your work and is not given here. - Problem Set 1 includes a struct-over-the-wire scenario: use §3.2’s method (sizes, alignment, padding, byte order, per ABI). Exercises 1–3 practise it on a different struct.
Further reading
- A. D. Birrell and B. J. Nelson, “Implementing Remote Procedure Calls”, ACM TOCS 2(1), 1984 — the paper that defined RPC’s design: stubs, binding through a database, call semantics.
- J. Waldo, G. Wyant, A. Wollrath, S. Kendall, “A Note on Distributed Computing”, Sun Microsystems Laboratories TR-94-29, 1994.
- A. S. Tanenbaum and M. van Steen, Distributed Systems, 3rd ed., §4.2 (remote procedure call: parameter passing, stubs, binding).
- R. Srinivasan, “XDR: External Data Representation Standard”, RFC 1832, 1995; the Protocol Buffers encoding documentation (varints, field numbers, compatibility rules).
- The CS:APP / 15-213 chapters on linking (library interposition) and network programming (
rio, framing).
Preview of Lecture 4 — RPC II: failure semantics, idempotence and the end-to-end argument
Everything today assumed that each request reaches the server and each reply comes back. Next we remove that assumption. Lecture 1 showed that a client that times out cannot tell what happened; now we name the possible guarantees — at-least-once, at-most-once, and the elusive exactly-once — and build each one: retries, request ids, duplicate-suppressing reply caches, and how to garbage-collect them. We ask which operations are idempotent and how to make non-idempotent ones safe, how to choose timeouts (and how aggressive retries can melt a server down), what happens to orphaned computations when a client crashes, and why the end-to-end argument says that a reliable network does not make a file transfer reliable.
术语表 (Glossary, English → 中文)
| English | 中文 |
|---|---|
| remote procedure call (RPC) | 远程过程调用 |
| client stub / server stub (skeleton) | 客户端存根 / 服务器端存根(骨架) |
| dispatcher | 分派器 |
| marshalling / unmarshalling | 编组 / 解组 |
| serialization / deserialization | 序列化 / 反序列化 |
| external data representation | 外部数据表示 |
| byte order / endianness | 字节序 |
| little-endian / big-endian | 小端 / 大端 |
| network byte order | 网络字节序 |
| application binary interface (ABI) | 应用程序二进制接口 |
| alignment / padding | 对齐 / 填充 |
| ILP32 / LP64 / LLP64 | 三种数据模型(int、long、指针的位宽约定) |
| self-describing format / schema | 自描述格式 / 模式(结构定义) |
| type tag | 类型标签 |
| variable-length integer (varint) | 变长整数编码 |
| framing / length prefix | 分帧 / 长度前缀 |
| property-based testing | 基于性质的测试 |
| malformed / hostile input | 畸形 / 恶意输入 |
| length bomb | 长度炸弹 |
| checksum | 校验和 |
| backward / forward compatibility | 向后 / 向前兼容 |
| interface evolution / versioning | 接口演进 / 版本管理 |
| call by value / call by reference | 传值调用 / 传引用调用 |
| copy/restore (value-result) | 复制-恢复(值-结果)调用 |
| aliasing | 别名 |
| pointer swizzling / flattening | 指针重写(混合) / 扁平化 |
| object identity | 对象标识 |
| remote reference / remote object | 远程引用 / 远程对象 |
| interface definition language (IDL) | 接口定义语言 |
| stub generator | 存根生成器 |
| binding / name server / registry | 绑定 / 名字服务器 / 注册表 |
| port mapper | 端口映射器 |
| late binding | 延迟绑定 |
| thread-per-connection / thread pool | 每连接一线程 / 线程池 |
| event-driven server | 事件驱动服务器 |
| global interpreter lock (GIL) | 全局解释器锁 |
| chatty vs chunky interface | 细粒度(频繁交互)与粗粒度(批量)接口 |
| batching / pipelining | 批处理 / 流水线 |
| asynchronous call / future | 异步调用 / future(未来值) |
| interposition (LD_PRELOAD) | 插入(拦截)技术 |
| information disclosure | 信息泄露 |