Communication, APIs and Idempotency (System Design #14)
A payment request is sent, the network times out, and the client retries. Did the charge happen once, twice, or not at all? Without careful design, the answer is “who knows”, and the customer is furious. Everything in this chapter — protocols, API styles, retries — exists to make that question answerable.
Components in a distributed system must talk, and every conversation can fail in ways that are invisible to the caller. This chapter covers the transport choices (HTTP, TCP, UDP), the API styles built on them (RPC/gRPC, REST, GraphQL), and the property that makes retries safe: idempotency.
Transport: TCP, UDP, and HTTP
At the bottom, two transports:
- TCP — reliable, ordered byte stream. Handles retransmission and ordering for you. Connection setup costs a round trip (TLS adds more). Most APIs use TCP.
- UDP — unreliable, unordered datagrams. No retransmission; lower latency and overhead. Used for real-time media, games, DNS, and custom protocols that tolerate loss.
HTTP runs over TCP (or QUIC/UDP for HTTP/3) and adds request/response semantics, caching headers, status codes, and a huge ecosystem. When someone says “an API”, they usually mean HTTP. Long-lived bidirectional needs (chat, live updates) often move to WebSockets (persistent TCP) or server-sent events (one-way push over HTTP), because request/response alone cannot push.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
b/.style={draw, thick, rounded corners=3pt, minimum width=1.9cm, minimum height=0.7cm, align=center, font=\rmfamily\small},
a/.style={->, thick}]
\node[b, fill=blue!10] (tcp) at (-2.4,0.9) {TCP\\reliable, ordered};
\node[b, fill=orange!16] (udp) at (-2.4,-0.9) {UDP\\fast, lossy};
\node[b, fill=green!12] (h) at (1.2,0.9) {HTTP/gRPC/WS};
\node[b, fill=yellow!22] (rt) at (1.2,-0.9) {media/games/DNS};
\draw[a] (tcp) -- (h); \draw[a] (udp) -- (rt);
\end{tikzpicture}
API styles: RPC, REST, GraphQL
Three ways to shape an HTTP API, each with a different trade-off.
- RPC (remote procedure call). Model the API as functions:
getUser(id),chargeCard(order). Modern RPC means gRPC: protocol buffers for the schema, HTTP/2 for transport, code generation for clients. Fast, compact, strongly typed, and great for service-to-service calls. Weaker fit for public/browser APIs (browser support and human debuggability). - REST. Resources with URLs and HTTP verbs (
GET /users/42,POST /orders), stateless, cacheable, uniform interface. The default for public APIs because it is simple, cacheable, and tool-friendly. - GraphQL. A single endpoint; the client specifies the exact fields it wants in a query. Solves over-fetching (REST returns too much) and under-fetching (REST needs many calls for a screen). Costs: complex caching, query-cost attacks (deep queries), and server-side query planning.
| Style | Best for | Watch out for |
|---|---|---|
| gRPC | internal service mesh, perf | not browser-friendly; HTTP/2 |
| REST | public APIs, caching | over/under-fetching, versioning |
| GraphQL | varied clients, one screen | caching, expensive queries, authz per field |
\begin{tikzpicture}[font=\rmfamily, >=stealth,
b/.style={draw, thick, rounded corners=3pt, minimum width=1.7cm, minimum height=0.68cm, align=center, font=\rmfamily\small},
a/.style={->, thick}]
\node[b, fill=green!12] (rest) at (-2.9,0) {REST\\many endpoints};
\node[b, fill=orange!16] (grpc) at (0,0) {gRPC\\typed RPC};
\node[b, fill=blue!10] (gql) at (2.9,0) {GraphQL\\one query shape};
\node[font=\rmfamily\small, text=black!60, anchor=north] at (0,-0.7) {public API \hspace{1.2cm} internal \hspace{1.2cm} flexible clients};
\end{tikzpicture}
Synchronous vs asynchronous communication
- Synchronous (request/response): simple, immediate, easy to reason about. But the caller is blocked and coupled to the callee’s latency and availability. A chain of synchronous calls multiplies failure probability (Chapter 5’s series formula).
- Asynchronous (messages/events, Chapter 13): decoupled, resilient to downstream slowness, but more complex — no immediate result, ordering and duplicate handling required.
The rule: use synchronous calls for queries and anything the user is waiting on; use asynchronous messaging for side effects, fan-out, and slow work. A single user action often does both: synchronous write to the database, asynchronous events for email/search/analytics.
Idempotency: making retries safe
Idempotent means running an operation multiple times has the same effect as running it once. GET, PUT, and DELETE are naturally idempotent (PUT /users/42 {name:"A"} twice = one state). POST is not (two posts = two orders), which is exactly why retries on POST are dangerous.
The standard fix is an idempotency key: the client generates a unique key per logical operation and sends it (a header, e.g. Idempotency-Key). The server records the key and its result; a retry with the same key returns the original result instead of re-executing.
# server-side idempotency: execute once, replay the result on retries
def charge(idem_key, amount, store, payments):
if (prev := store.get(idem_key)) is not None:
return prev # duplicate request -> same result
result = payments.charge(amount) # do the side effect once
store.put(idem_key, result, ttl=24 * 3600)
return result
Two implementation notes. The key must be recorded atomically with the effect (or the effect guarded by a lock), or two concurrent retries can both execute. And the stored result must be complete enough to replay a faithful response, not just “ok”.
Retries, timeouts, and backoff
Retries without discipline make outages worse. A service under stress receives retries on top of failed load and collapses — the retry storm (Chapter 15). Rules:
- Always set timeouts. A call with no timeout eventually hangs a thread and cascades. Choose timeouts from the latency budget, not from optimism.
- Retry only idempotent operations (or ones made idempotent by a key). Never blind-retry a non-idempotent write.
- Use exponential backoff with jitter. Wait longer after each failure, and add randomness so retries do not synchronize into a thundering herd.
\[ \text{delay}_n = \min(\text{cap},\ \text{base} \times 2^n) + \text{random jitter} \]
- Add a circuit breaker. After repeated failures, stop calling for a while (Chapter 17) instead of hammering a dead dependency.
import random, time
def call_with_retry(fn, attempts=4, base=0.1, cap=2.0):
for n in range(attempts):
try:
return fn()
except TransientError:
if n == attempts - 1:
raise
time.sleep(min(cap, base * 2 ** n) + random.uniform(0, base))
# never retry non-idempotent writes, and never without a timeout
The trio — timeout, idempotency key, backoff+jitter — is what makes a distributed call safe to attempt again. Without all three, “just retry” is how you turn a blip into an outage and a charge into a double charge.
Pitfalls
- Retrying non-idempotent writes. Double charges, duplicate orders. Require an idempotency key before retrying.
- No timeouts. A single slow dependency consumes threads/connections until the caller falls over. Set them everywhere.
- Backoff without jitter. All clients retry at the same instant, re-creating the spike. Add jitter.
- Synchronous chains. Each hop multiplies failure probability and latency. Use async where the result is not needed immediately.
- Idempotency key recorded after the effect. A crash between the two allows a duplicate. Record and effect atomically, or lock.
- Ignoring retry amplification. Clients × services × retries can multiply load many times over. Cap retries and add circuit breakers.
Why is POST dangerous to retry, and how does an idempotency key fix it? What three things must accompany any safe retry?
ASolution
A POST creates a new effect each time, so retrying after a timeout can duplicate it. An idempotency key lets the server detect the duplicate and replay the original result instead of re-executing. A safe retry needs a timeout, idempotency (inherent or via key), and exponential backoff with jitter — plus a cap and ideally a circuit breaker.
Next: Performance Antipatterns and Monitoring (System Design #15) — the mistakes that cause outages, and how to see them coming.