A call to another service can fail after the work ran. The caller cannot tell, so it retries. At 10% loss each way, a retry with no key double charges about 1 order in 10.
Run 20 payments with no retry, then with retries, then with retries and an idempotency key. Drag the loss rate and run again. Then we build the whole stack: discovery, HTTP, pools, REST, retries, keys, encodings, gRPC and the gateway.
You need a little Python and what a request and a response are. Network Foundations helps. We build the rest from zero.
Illustrative toy from a fixed seed: each request and each response is lost at the rate you set. A lost response looks the same to the caller as a lost request: a timeout. The expected rates come from a short script (Chapter 6).
Chapter 0
See the four ways a remote call can end, and why the caller sees only one of them
A shop starts as one program. Checkout calls charge_card(), a function in the same process. It returns in nanoseconds. It never half-succeeds, and the compiler checks its arguments.
Then the shop splits into services: separate programs for Orders, Payments, Inventory and Shipping, each deployed by its own team. Now charge_card() is a message to another machine. Orders must find Payments by name and turn the arguments into bytes. The reply must come back over the network.
That network can lose the request, the reply, or both. The Payments server can crash halfway. It can also be slow. Pick each case below and watch what the Orders service sees.
Blue is the request, teal the reply, yellow the caller's 1-second timeout. Pick where the call goes wrong.
Illustrative timings: 20 ms each way, 50 ms of work, a 1 s timeout, and 1.8 s of work in the slow case.
Four of the five cases end the same way for the caller: a timeout, no reply within the limit it set. In two of them Payments charged the card. The caller cannot tell which case it is in. Every pattern in this lesson exists to act well without knowing.
Slowness also adds up. Checkout calls several services in a row. Call the chance that one call is slow q, and the number of calls one checkout makes n. What is the chance P that the checkout hits at least one slow call?
P equals one minus the quantity one minus q, to the n.
Each call is fast with chance 1 minus q. All n calls are fast with that chance multiplied n times. P is everything else.
With made-up numbers: q = 1% and n = 4 calls give P = 1 − 0.994 = 3.9%. A page that fans out to n = 100 calls gets P = 63%. Dean and Barroso give this 100-call case in "The Tail at Scale" (2013).
Chapter 1
Ask for a name, cache the answer for a TTL, and trade fresh answers against query load
Orders could keep Payments' address in a config file: 10.0.3.42. That works until Payments moves to a new machine, or runs as three copies. So services use names, and a lookup system maps each name to the current addresses.
That system is the Domain Name System (DNS). A resolver walks a tree of servers: the root, then the .com servers, then the domain's own authoritative server. The answer is a record. An A record maps a name to an IPv4 address, AAAA to IPv6, CNAME to another name, and SRV to a host and a port (RFC 1035, 3596, 2782).
Each answer carries a TTL (time to live) in seconds. Every cache on the way may keep the answer that long without asking again. So a short TTL means fresh answers and many queries. A long TTL means few queries and stale answers after a move. Call the number of client caches N and the queries a second that reach the DNS server Q.
Q equals N over T-T-L.
Each of the N caches asks once per TTL. So Q is N divided by TTL. Halve the TTL and the queries double.
With made-up numbers: N = 10,000 client processes. TTL = 300 s gives Q = 33 queries a second. TTL = 30 s gives 333. With TTL = 3,600 s, a moved service keeps getting traffic at its old address for up to an hour.
Each row is a client cache. At time 0 Payments moves. Purple is the cached old address, green the new one. Drag the TTL, then press Move.
Illustrative: each cache fetched its copy at a random moment within the last TTL, so its copy expires at a random moment within the next TTL. Query load uses N = 10,000.
To move a service safely, lower the TTL first, then wait one old TTL so every cache holds the short one, then change the address. Inside a cluster, a registry also tracks which copies are healthy. Kubernetes gives each Service the name payments.default.svc.cluster.local (with the common default cluster domain), and Orders asks for payments.
A registry learns health from probes. A liveness probe asks "is the process alive?"; a fail means restart it. A readiness probe asks "can it serve now?"; a fail means stop sending it traffic, but keep it running.
Failure. Symptom: errors to a service that moved an hour ago. Measure: dig payments.internal shows the TTL; logs show the old address. Cause: a long TTL, or a client library that caches DNS forever. Fix: lower TTLs before moves and check the client's own DNS cache setting.
Chapter 2
Read a request line by line, then let the method and the status code decide whether to retry
Most services talk HTTP. In HTTP/1.1 a request is plain text (RFC 9112). First comes a request line with the method, the path and the version. Then come header fields, one per line, an empty line, and the optional body. Each line ends with the two bytes carriage return and line feed.
That is 198 bytes: 137 of request line and headers, 61 of body. The server answers with a status line such as HTTP/1.1 201 Created, its own headers and a body.
The method says what the caller wants. RFC 9110 defines two properties. A method is safe if it asks for no change: GET, HEAD, OPTIONS and TRACE. It is idempotent if sending it twice has the same intended effect as once: PUT, DELETE and the safe methods. POST is neither. PATCH is neither as well (RFC 5789), though you can write one PATCH so that it is idempotent.
The status code says what happened. 2xx means success, 3xx go elsewhere, 4xx the request is wrong, 5xx the server failed. Two codes carry advice: 429 Too Many Requests (RFC 6585) and 503 Service Unavailable may come with a Retry-After header in seconds.
Pick the method of the call, then what came back. The verdict follows RFC 9110's rule for automatic retries.
The rule: retry automatically only if repeating the request has the same effect as sending it once (RFC 9110, Section 9.2.2), and only for a fault that might pass. An idempotency key (Chapter 6) makes a POST repeatable.
Failure. Symptom: a few orders appear twice after a deploy. Measure: pairs of identical POSTs a second apart in the access log. Cause: a client library or proxy that retries every request on timeout, POST included. Fix: limit automatic retries to idempotent methods, or send an idempotency key.
Chapter 3
Keep connections open, count how many are busy, and size the pool so calls do not queue
A new TCP and TLS 1.3 connection costs two round trips before the first request (Network Foundations, Chapter 8). So HTTP/1.1 keeps connections open by default and sends the next request on the same one (RFC 9112, Section 9.3).
But an HTTP/1.1 connection answers in order. A client may pipeline, sending several requests before the replies, yet the server must reply in the order the requests came. One slow reply holds up the rest. So clients keep a connection pool: a set of open connections, one request on each at a time.
HTTP/2 (RFC 9113) splits one connection into streams. Each request gets its own stream number, and frames from many streams interleave on the wire. A server limits how many streams may be open at once; RFC 9113 recommends no fewer than 100. A lost TCP packet still stalls every stream, because TCP below is one ordered byte stream.
How many connections does a pool need? Call the request rate λ and the time each request holds a connection W. The average number busy is L.
L equals lambda times W.
Multiply the requests a second, lambda, by the seconds each one stays, W. That is L, how many are inside at once. This is Little's law; it holds for any steady system.
With made-up numbers: λ = 2,000 requests a second, W = 50 ms. L = 2,000 × 0.05 = 100 busy connections. One HTTP/1.1 connection carries at most 1 / 0.05 = 20 requests a second.
Purple cells are busy connections, empty cells are idle, pink are requests waiting for a connection. Drag the pool size down toward L.
The wait uses Erlang C, the queue with c servers, random arrivals and random hold times around W. The picture is one random moment of that queue.
The pool needs more than L. With 110 connections the pool is 91% busy, and 24% of requests wait, 1.2 ms on average. With 101, 88% wait, 44 ms on average. With 100 or fewer the queue grows without end.
Failure. Symptom: latency climbs while the downstream service looks idle. Measure: the pool's "waiting for connection" metric or time. Cause: a pool smaller than λW, often after W grew because the downstream slowed. Fix: size to well above λW and set a timeout on the wait for a connection.
Chapter 4
Name the nouns, let the methods be the verbs, and page through long lists with a cursor
REST is a style, not a standard. Roy Fielding described it in his 2000 dissertation. In practice a "REST API" means: name each thing as a resource with its own path, and use the HTTP methods as the verbs.
Compare POST /cancelOrder?id=42. The REST form lets a stranger guess every route from one. It also lets HTTP's rules work: a cache may keep a GET, and a client may retry a PUT. RFC 9110 says a 201 names the new resource in its Location header. Paths are case-sensitive (RFC 3986), so pick one spelling and keep it.
A list needs pagination. With an offset, the client asks for ?offset=200&limit=100 and the database skips 200 rows to return 100. With a cursor, the server returns an opaque token for "after order 9,800", and the next query starts there through an index. Call the rows per page L and the pages P. What does reading the whole list cost?
R-offset equals L times P times P plus one, over two.
Page 1 reads L rows, page 2 reads 2L, page P reads P times L. Add them: L times the sum 1 to P. A cursor reads each row once, L times P in all.
One million orders, L = 100, so P = 10,000. R-offset = 100 × 10,000 × 10,001 / 2 = 5,000,500,000 rows. The cursor reads 1,000,000, about 5,000 times fewer. The last offset page alone reads a million rows.
The list is newest first, 4 orders a page. Before each next page, a new order arrives at the top. Choose offset or cursor and press Next page.
Illustrative list of 20 orders. An insert at the top shifts every offset by one, so the offset reader sees one row twice per page. A delete would make it skip one.
Failure. Symptom: the first pages load fast, deep pages take seconds. Measure: the query plan shows offset plus limit rows read for each page. Cause: offset pagination. Fix: a cursor on an indexed column, such as WHERE id < :last_id ORDER BY id DESC LIMIT 100.
Chapter 5
Wait longer after each failure, spread the waits at random, and retry at one layer only
A busy server fails 1,000 calls in the same second. If all 1,000 clients retry after exactly one second, the server gets the same spike again, and again. This is the thundering herd.
The fix has two parts. Exponential backoff doubles the wait after each failure, so a sick server gets more room each round. Jitter picks the actual wait at random, so the clients stop moving in step. Call the attempt number k (0 for the first retry), the base wait b and the cap C. Call the backoff ceiling for attempt k dk.
d-k equals the min of C and b times two to the k.
Double the base wait b once for each failure k. Stop at the cap C. Then sleep a random time up to that ceiling d-k.
b = 100 ms and C = 10 s give ceilings of 100, 200, 400, 800 and 1,600 ms. On retry k = 3, the 1,000 clients spread over 800 ms. In 50 ms slices that is about 63 a slice, not 1,000 at once.
All 1,000 clients failed at time 0. Each bar counts the retries that land in one 50 ms slice. The yellow line is the backoff ceiling. Choose the jitter and the attempt.
Illustrative random draws from a fixed seed, base 100 ms, cap 10 s. "Full jitter" is the variant that Marc Brooker's 2015 AWS Architecture Blog post "Exponential Backoff And Jitter" recommends.
Retries also multiply across layers. A web tier calls Orders, which calls Payments, which calls the bank. If each of L layers tries r extra times, one user click can become this many attempts at the bottom:
A equals r plus one, to the L.
Each layer turns one call into r plus 1 calls to the layer below. Stack L layers and multiply L times.
r = 3 and L = 3: A = 43 = 64 attempts at the bank for one click, at the moment the bank is already failing. Retry at one layer only and A = 4.
Failure. Symptom: a short blip in one service becomes a long outage. Measure: requests at the bottom service per request at the top, during the incident. Cause: stacked retries with no jitter. Fix: retry at one layer, use full jitter, and cap retries to a small share of traffic.
Chapter 6
Give each logical operation a key, claim the key before the work, and replay the saved reply
An operation is idempotent if doing it twice has the same effect as doing it once. "Set the address to 5 Elm Street" is idempotent. "Charge $49.99" is not. Chapter 0 showed that a caller must retry without knowing whether the first try ran. So every call with a side effect needs an idempotent form.
How often does it matter? Take 1,000,000 payments a day, and say 0.1% lose the reply after the charge ran. With retries and no protection, that is 1,000,000 × 0.001 = 1,000 double charges a day. In the hero at 10% loss each way, about 9.7% of orders pay twice.
The standard fix is an idempotency key. The client makes one random key per logical operation, such as a UUID, and sends the same key on every try. The server keeps a key store: key, a fingerprint of the request, its status and the saved reply. On a repeat it returns the saved reply and does not charge again.
Pick what happens to the two copies, then the server's logic. "Claim first" also stores a fingerprint of the body. The purple box is the key store; the ledger shows each charge.
Illustrative. "Claim first" inserts the key with status "in progress" in one atomic step before charging; a second copy that finds it gets 409, and a copy with a different fingerprint gets 422, as the IETF Idempotency-Key draft suggests.
"Check, then charge" has a gap. Two copies can both check, both miss, and both charge. The fix is to claim the key in one atomic step first. A database does this with a unique index: INSERT … ON CONFLICT (key) DO NOTHING. Exactly one insert wins.
The loser reads the row. If it is in progress, answer 409 Conflict. If the fingerprint differs, answer 422. If the work has ended, replay the saved reply.
Real systems do this. Stripe accepts an Idempotency-Key header on every POST, up to 255 characters. It saves the first reply once the endpoint starts work, 500 errors included, and rejects a reused key with different parameters. The header itself is an IETF Internet-Draft (draft-ietf-httpapi-idempotency-key-header-09), not yet an RFC.
Failure. Symptom: customers report two charges after a network blip. Measure: charges per idempotency key, and keys seen twice within seconds. Cause: no key, or check-then-charge. Fix: claim the key atomically, store a fingerprint, keep keys at least 24 hours.
{"action": "add_funds", "amount": 100} with no key. A client times out and retries the same body. What happens if the first try ran?Chapter 7
Turn a request into bytes two ways, count them, and change the schema without breaking old readers
Before a request crosses the wire, its fields become bytes. JSON (RFC 8259) writes field names and values as text. Protocol Buffers (protobuf) writes a field number and a compact binary value. Both sides know the names from a shared .proto file.
Each protobuf field starts with a tag: the field number shifted left 3 bits, plus a 3-bit wire type. Fields 1 to 15 fit in one tag byte. Whole numbers use a varint: 7 bits of the number per byte, with the top bit set on every byte except the last. Call the bits a number needs b and its varint bytes n.
n equals the ceiling of b over seven.
Write the number in binary and count its bits b. Cut them into groups of 7. The number of groups is n.
4,999 cents is 13 bits, so n = 2: the bytes 87 27. 127 needs 1 byte, 128 needs 2, a million needs 3. A negative int64 needs 10, which is why protobuf has the ZigZag type sint64.
The bars are the bytes of the same ChargeRequest. The hex row is the protobuf message, coloured by field. Drag the amount and add a field.
Real encodings, computed in the page: compact JSON with no spaces, and the protobuf wire format for fields 1 customer_id (string), 2 amount_cents (int64), 3 currency (string), 4 idempotency_key (string).
The default request is 93 bytes of JSON and 29 of protobuf, 3.2 times smaller. The names make most of the difference. Speed depends on the library, so measure it in your own stack.
Schemas change while old code still runs. A change is backward compatible if new code reads old data, and forward compatible if old code reads new data. Protobuf readers skip fields with numbers they do not know, so adding a field is safe both ways.
| Change | Protobuf | JSON API |
|---|---|---|
| Add an optional field | safe: old readers skip it | safe if clients ignore unknown keys |
| Rename a field | safe on the binary wire; names are not sent | breaks: the key changes |
| Change a field number | breaks: old readers see another field | not applicable |
| Remove a field | safe if you mark the number reserved | breaks clients that read it |
| Add a required request field | proto3 has no required fields | breaks old clients: 400 |
Failure. Symptom: order IDs above 9,007,199,254,740,991 come back off by one in a browser. Measure: compare the ID in the raw JSON with the parsed value. Cause: JavaScript reads JSON numbers as doubles; RFC 8259 calls only integers up to 253 − 1 interoperable. Fix: send 64-bit IDs as strings, as protobuf's JSON mapping does.
Chapter 8
Call a remote method like a function, stream messages both ways, and pass the deadline down the chain
A remote procedure call (RPC) makes a network call look like a function call. gRPC is one such framework. You write the service in a .proto file, and the compiler protoc generates a client stub and a server skeleton in your language.
On the wire, gRPC rides HTTP/2. Each call is a POST to /PaymentService/Charge (with the package name in front) and content type application/grpc. Each message carries a 5-byte prefix: 1 byte "compressed?" and a 4-byte length. The 29-byte ChargeRequest of Chapter 7 is 34 bytes in its frame. The status, grpc-status, comes in the trailers at the end, even on success.
The caller can set a deadline, sent as the grpc-timeout header. Each service should pass the time that is left to the next call, so work stops when no one waits for it. Call the whole deadline D, the time spent so far e, a safety margin m, and the budget for the next call t.
t equals D minus e minus m.
From the deadline D, subtract the time e already used and the margin m. Give the rest, t, to the next call as its deadline.
With made-up numbers: A has D = 300 ms and spends e = 40 ms. So B gets t = 300 − 40 − 10 = 250 ms. B spends 30 ms. So C gets 250 − 30 − 10 = 210 ms. C must stop by 280 ms, before A gives up at 300.
Each bar is one service's work over time. The yellow line is A's deadline. Red is work after A has given up. Drag C's work time and turn propagation on.
Illustrative chain: A works 40 ms before calling B, B works 30 ms before calling C, network time folded in, margin 10 ms per hop.
Two other tools fit other shapes. GraphQL sends one query naming exactly the fields the client wants, which suits screens that need many linked things. WebSockets (RFC 6455) start as an HTTP request that upgrades to a two-way channel, which suits chat and live updates.
Chapter 9
Break Payments, flood the gateway, and watch retries, a rate limit and a circuit breaker shape the load
Outside clients do not call 40 services directly. They call one API gateway, a reverse proxy that checks who is calling, routes each path to its service, and adds a request ID for tracing. It is also where two guards live.
A rate limiter caps each client. The common form is a token bucket: the bucket gains tokens at a fixed rate up to a size, and each request spends one. An empty bucket means 429.
A circuit breaker watches calls to one service. It starts closed and lets calls through. If too many fail, it opens and answers 503 at once for a while. Then it goes half-open, lets a few probes through, and closes again if they succeed.
Blue is the load that reaches Payments; the yellow dashes are its capacity. Green is replies that worked, red is failures, both per second. Press Break Payments and compare the guards.
Illustrative fluid model in 0.1 s steps: clients send 100 calls a second; Payments serves up to 200 a second; Break fails every call for 15 s; Flood adds one client sending 300 a second for 5 s. The breaker opens above 50% failures over the last second (at least 20 calls), stays open 5 s, then sends 5% of calls as probes. The rate limit is a token bucket of 50 a second per client, size 50.
With retries alone, the broken Payments service gets 400 calls a second, four times the clients' rate, and all of them fail. Turn on the breaker. Within a second it opens, and Payments sees only a trickle of probes. When Payments returns, a probe succeeds and the breaker closes.
The flood shows the rate limit. One client sends 300 calls a second. Without a limit, Payments gets 400 a second, twice its 200. The failed calls come back as retries, the load passes 1,000, and every client sees failures. With a bucket of 50 a second for that client, the extra calls end at the gateway as 429s and the other clients stay served.
Failure. Symptom: Payments recovers, then falls over again within seconds. Measure: calls a second at Payments against its capacity at the moment of recovery. Cause: a backlog of retries arrives at once. Fix: a breaker that closes slowly through half-open, backoff with jitter, and a retry budget.
Chapter 10
Keep the numbers, the checklist and the code for the next service you call
One call goes like this. Orders looks up Payments by name and caches the answer for a TTL. It takes a connection from a pool and sends a POST with an idempotency key and a deadline. If no reply comes in time, it backs off with jitter and retries with the same key, and the server replays the saved reply. A breaker stops the retries when Payments is down.
| Term | What it is | This lesson's number |
|---|---|---|
| Tail chance | P = 1 − (1 − q)n | 1% slow, 4 calls: 3.9%; 100 calls: 63% |
| DNS load | Q = N / TTL | 10,000 caches, 30 s: 333 queries a second |
| A request | request line, headers, empty line, body | 198 bytes: 137 head, 61 body |
| Little's law | L = λ · W | 2,000/s × 50 ms = 100 busy; pool 110 waits 1.2 ms |
| Offset paging | R = L · P (P + 1) / 2 | 1 M rows: 5.0 billion reads, cursor 1 M |
| Backoff | dk = min(C, b · 2k), sleep 0 to dk | 100, 200, 400, 800 ms |
| Amplification | A = (r + 1)L | 3 retries, 3 layers: 64 |
| Double charges | payments × lost-reply rate, no key | 1,000,000 × 0.1% = 1,000 a day |
| Varint | n = ⌈b / 7⌉ | 4,999 → 2 bytes; request 93 B JSON, 29 B protobuf |
| Deadline | t = D − e − m | 300 − 40 − 10 = 250 ms |
python# a careful call: one key for all tries, full jitter, a deadline, retry only what may pass import random, time, uuid, requests RETRYABLE = {429, 502, 503, 504} def charge(session, body, deadline_s=2.0, base=0.1, cap=10.0, tries=4): key = str(uuid.uuid4()) # one key per logical charge end = time.monotonic() + deadline_s for k in range(tries): left = end - time.monotonic() if left <= 0: break try: r = session.post("http://payments/v1/charges", json=body, headers={"Idempotency-Key": key}, timeout=left) if r.status_code not in RETRYABLE: return r # success, or a 4xx to fix wait = float(r.headers.get("Retry-After", 0)) except (requests.Timeout, requests.ConnectionError): wait = 0 # unknown outcome: the key makes a retry safe d = min(cap, base * 2 ** k) # backoff ceiling d_k time.sleep(min(max(wait, random.uniform(0, d)), max(0, end - time.monotonic()))) raise TimeoutError("deadline passed; outcome unknown, safe to retry later with the same key")
Now press Present or Teach and explain five things from memory. Explain the four ways a call ends, Little's law for a pool, backoff with jitter, the atomic idempotency claim, and the breaker's three states. Then go back to the hero, set the loss to 30% and compare retries with and without a key.