Notes
All notes

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:

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.

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

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:

\[ \text{delay}_n = \min(\text{cap},\ \text{base} \times 2^n) + \text{random jitter} \]

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

QQuestionSelf-check

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.