Lesson 6 of 17
24. 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:

CodeMeaningClient should
200 OK, 201 Created, 204 No ContentSuccessCarry on
400 Bad RequestMalformed or invalid inputFix the request; don't retry as is
401 UnauthorizedNot authenticated (missing or bad credentials)Log in or refresh the token
403 ForbiddenAuthenticated, but not allowedDon't retry
404 Not FoundNo such resourceDon't retry
409 ConflictClashes with current state ("order already paid")Re-read state and decide
422 Unprocessable ContentWell-formed but fails business rulesFix the input
429 Too Many RequestsRate limited (Chapter 25)Wait (see Retry-After) and retry
500 Internal Server ErrorServer bugRetry carefully (24.9)
502 / 503 / 504Upstream failed, service unavailable, timeoutRetry 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."