Service Communication

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.

Retry a payment through a lossy network

10%

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

A Function Call That Crosses the Network

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.

Break one call in five places

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?

Say it aloud

P equals one minus the quantity one minus q, to the n.

P
P the chance that one checkout meets at least one slow call.
q
q the chance that one call is slow, for example slower than 1 second.
n
n the calls one checkout makes. The power "to the n" multiplies the chance of a fast call by itself n times.
In plain words

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 numbers

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).

  1. Discovery: find the service by name, with DNS and health checks.
  2. HTTP: the request on the wire, methods and status codes.
  3. Pools: reuse connections, multiplex streams, size the pool.
  4. REST: design around resources and page through lists.
  5. Retries: back off, add jitter, avoid retry storms.
  6. Idempotency: make a retried charge run once.
  7. Encoding: JSON and Protocol Buffers, and changing them safely.
  8. gRPC: typed calls, streams and deadlines.
  9. The gateway: rate limits and a circuit breaker during an outage.
  10. The field guide: numbers, checklist, code and links.
Orders sends a charge to Payments. Payments charges the card, but the reply is lost. What does Orders know?

Chapter 1

Find the Service: DNS and Discovery

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.

Say it aloud

Q equals N over T-T-L.

Q
Q the DNS queries a second for one name, when every cache asks again as soon as its copy expires.
N
N the caches that keep their own copy, for example one per client process.
TTL
T-T-L the time to live of the record, in seconds. It is also the longest a cache can use an old address.
In plain words

Each of the N caches asks once per TTL. So Q is N divided by TTL. Halve the TTL and the queries double.

With numbers

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.

Move a service and watch the caches

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.

300 s

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.

Payments' record has TTL 3,600 s. You will move it tomorrow. What do you do first?

Chapter 2

An HTTP Request, Byte by Byte

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.

POST /v1/payments HTTP/1.1 28 bytes method, path, version Host: payments.internal 25 bytes Content-Type: application/json 32 bytes Idempotency-Key: ord42-pay-1 30 bytes Content-Length: 61 20 bytes 2 bytes empty line: headers end {"customer_id":"cus_42","amount_cents":4999,"currency":"usd"} 61 bytes

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.

Decide whether to retry

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.

A POST with no idempotency key times out. Which RFC 9110 rule applies to an automatic retry?

Chapter 3

Connections: Reuse, Multiplex, Pool

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.

Say it aloud

L equals lambda times W.

L
L the average number of connections in use at one moment.
λ
lambda the arrival rate: requests a second.
W
W how long each request holds its connection, in seconds.
In plain words

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 numbers

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.

Size the pool

Purple cells are busy connections, empty cells are idle, pink are requests waiting for a connection. Drag the pool size down toward L.

2,000
50 ms
110

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.

A client sends 500 requests a second and each holds a connection for 80 ms. On average, how many connections are busy?

Chapter 4

Design the API Around Resources

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.

POST /orders create an order 201 Created, Location: /orders/42 GET /orders/42 read one 200 OK GET /orders?status=paid read a list 200 OK PUT /orders/42 replace it 200 OK PATCH /orders/42 change some fields 200 OK DELETE /orders/42 remove it 204 No Content

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?

Say it aloud

R-offset equals L times P times P plus one, over two.

Roffset
R-offset the rows the database reads to serve every page with offsets.
L
L the limit: rows on one page.
P
P the number of pages.
P + 1
P plus one with P and the division by two, this is the sum 1 + 2 + … + P.
In plain words

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.

With numbers

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.

Page through a list that keeps changing

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.

A client pages with offsets while new rows keep arriving at the top. What goes wrong?

Chapter 5

Retry With Backoff and Jitter

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.

Say it aloud

d-k equals the min of C and b times two to the k.

dk
d-k the backoff ceiling for retry k. With full jitter the client sleeps a random time between 0 and d-k.
min
the min of take the smaller of the two values, so the wait never passes the cap.
C
C the cap, for example 10 s.
b
b the base wait, for example 100 ms.
2k
two to the k one doubling per failed attempt.
In plain words

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.

With numbers

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.

Spread a thousand retries

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.

3

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:

Say it aloud

A equals r plus one, to the L.

A
A the worst-case attempts that reach the bottom service for one call at the top.
r
r the retries each layer makes after its first try. r + 1 is its tries in all.
L
L the layers that retry, stacked one on another.
In plain words

Each layer turns one call into r plus 1 calls to the layer below. Stack L layers and multiply L times.

With numbers

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.

Two layers each retry up to 2 times (3 tries in all). How many attempts can one top call cause at the bottom?

Chapter 6

Idempotency: Make the Retry Safe

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.

Send the same charge twice

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.

An endpoint handles {"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

Contracts: Encoding and Evolution

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.

Say it aloud

n equals the ceiling of b over seven.

n
n the bytes of the varint.
⌈ ⌉
the ceiling of round up to the next whole number, because you cannot send part of a byte.
b
b the bits in the number's binary form, at least 1. A negative int64 counts as 64 bits.
7
seven the payload bits in each byte; the eighth bit says "more bytes follow".
In plain words

Write the number in binary and count its bits b. Cut them into groups of 7. The number of groups is n.

With numbers

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.

Encode one request two ways

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.

4,999

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.

ChangeProtobufJSON API
Add an optional fieldsafe: old readers skip itsafe if clients ignore unknown keys
Rename a fieldsafe on the binary wire; names are not sentbreaks: the key changes
Change a field numberbreaks: old readers see another fieldnot applicable
Remove a fieldsafe if you mark the number reservedbreaks clients that read it
Add a required request fieldproto3 has no required fieldsbreaks 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.

How many bytes does protobuf use for the varint 300?

Chapter 8

RPC: gRPC, Streams and Deadlines

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.

service PaymentService { rpc Charge (ChargeRequest) returns (ChargeReply); unary rpc Watch (AccountId) returns (stream Transaction); server streaming rpc Upload (stream Tick) returns (UploadSummary); client streaming rpc Trade (stream Order) returns (stream Fill); bidirectional }

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.

Say it aloud

t equals D minus e minus m.

t
t the timeout this service gives its next call.
D
D the deadline it received: the time its caller will wait.
e
e the time it has spent already, before this call.
m
m a margin to send the reply back, for example 10 ms.
In plain words

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 numbers

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.

Pass the deadline down

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.

300 ms
400 ms

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.

A service receives a 500 ms deadline, spends 120 ms, and keeps a 10 ms margin. What timeout does its next call get?

Chapter 9

The Gateway Under an Outage

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.

Run the gateway through an outage

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.

A breaker is open, and its open time has 20 s left. A new payment call arrives. What happens?

Chapter 10

The Field Guide

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.

Terms and numbers

TermWhat it isThis lesson's number
Tail chanceP = 1 − (1 − q)n1% slow, 4 calls: 3.9%; 100 calls: 63%
DNS loadQ = N / TTL10,000 caches, 30 s: 333 queries a second
A requestrequest line, headers, empty line, body198 bytes: 137 head, 61 body
Little's lawL = λ · W2,000/s × 50 ms = 100 busy; pool 110 waits 1.2 ms
Offset pagingR = L · P (P + 1) / 21 M rows: 5.0 billion reads, cursor 1 M
Backoffdk = min(C, b · 2k), sleep 0 to dk100, 200, 400, 800 ms
AmplificationA = (r + 1)L3 retries, 3 layers: 64
Double chargespayments × lost-reply rate, no key1,000,000 × 0.1% = 1,000 a day
Varintn = ⌈b / 7⌉4,999 → 2 bytes; request 93 B JSON, 29 B protobuf
Deadlinet = D − e − m300 − 40 − 10 = 250 ms

Checklist

  1. Call services by name; lower the TTL before you move one.
  2. Reuse connections; size each pool well above λ · W.
  3. Set a deadline on every call and pass what is left downstream.
  4. Retry only idempotent calls, at one layer, with full jitter and a cap.
  5. Send an idempotency key on every POST with a side effect; claim it atomically.
  6. Add fields, never renumber them; send 64-bit IDs as strings in JSON.
  7. Page long lists with a cursor.
  8. Put a breaker and a per-client rate limit at the gateway.

The core as code

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")

Keep going

The takeaway. A remote call can end without telling you what happened. So find services by name, keep connections warm, bound every call with a deadline, and retry with jitter. Make each retry safe with an idempotency key, and let a breaker stop the retries when the service is down.

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.

Service Communication
RFC 9110 · RFC 9113 · Protobuf encoding · Back to Gleams