24. APIs and Idempotency
1
The picture to keep in your head2
24.1 What is an API contract?3
24.2 What are the main API styles?4
24.3 How do you version an API?5
24.4 How does pagination work (offset vs cursor)?6
24.5 How should errors and status codes work?7
24.6 How does API auth work, in one page?8
24.7 What is the double-charge problem?9
24.8 How do idempotency keys work?10
24.9 How do you retry safely?11
24.10 How do webhooks work?12
Memory card and where the analogy breaks13
Practice: five levels14
Interview questions15
Solutions16
Sources17
Code lab24. APIs and Idempotency
24.5 How should errors and status codes work?
3 min read+10 XP
At the machine: Different lights for different problems: "sold out" (pick something else), "insert exact change" (your mistake, fix it), "machine jammed" (not your fault, try later). One vague "ERROR" light would leave you guessing.
In the system: HTTP status codes tell the client what kind of problem happened, and therefore what to do:
| Code | Meaning | Client should |
|---|---|---|
| 200 OK, 201 Created, 204 No Content | Success | Carry on |
| 400 Bad Request | Malformed or invalid input | Fix the request; don't retry as is |
| 401 Unauthorized | Not authenticated (missing or bad credentials) | Log in or refresh the token |
| 403 Forbidden | Authenticated, but not allowed | Don't retry |
| 404 Not Found | No such resource | Don't retry |
| 409 Conflict | Clashes with current state ("order already paid") | Re-read state and decide |
| 422 Unprocessable Content | Well-formed but fails business rules | Fix the input |
| 429 Too Many Requests | Rate limited (Chapter 25) | Wait (see Retry-After) and retry |
| 500 Internal Server Error | Server bug | Retry carefully (24.9) |
| 502 / 503 / 504 | Upstream failed, service unavailable, timeout | Retry with backoff |
Good error bodies:
- A consistent format across the API. The standard is Problem Details (RFC 9457):
type,title,status,detail, plus your own fields. - A machine-readable code (
"code": "order_already_paid") for programs and a human message for people. - A request ID to quote to support (Chapter 30).
- Never leak internals: no stack traces or SQL in responses.
json
The split that matters most for reliability: 4xx = the client's problem (don't blindly retry), 5xx and 429 = maybe temporary (retry safely, 24.9).
Memory code: "4xx: you fix it. 5xx: we're broken, try later. 429: slow down."