Part 03 · The Language of the Web
Status Codes and Error Meanings
Reading 2xx to 5xx like a map of who is at fault and what to do next.
⏱ 1 hours · Station 29 of 153
3 a.m., and the dashboard is all red
You're on call. The alert says "error rate 12%". You open the logs and see thousands of failed requests. The first question isn't "what's the bug?". It's "whose fault is it?"
- If they're 401s, a mobile release probably broke login tokens. That's a client problem.
- If they're 429s, one customer's script is hammering the API. Your rate limiter is doing its job.
- If they're 503s, a dependency is down. Retries will help once it recovers.
- If they're 500s, it's your code. Wake up the team.
All four are "errors", and they need completely different reactions. The status code is how one number can tell you which one you're looking at, before you read a single log line. This lesson is about choosing those numbers well, so the people (and programs) reading them at 3 a.m. can act fast.
The problem: "it failed" isn't enough
Every failure raises three questions, and the status code should answer them:
| Question | Why it matters | Who needs the answer |
|---|---|---|
| Whose fault is it? | Fix the client or fix the server | Developers, on-call engineers |
| Should I try again? | Retrying a bad request is useless; not retrying a temporary failure loses data | Retry libraries, proxies, apps |
| What exactly should change? | "Log in", "slow down", "fix this field" | The client code and the user |
A single generic code (always 200, or always 500) answers none of them. Too many exotic codes confuse everyone. The goal is a small, standard set used consistently.
Think of a hospital reception desk
You walk into a hospital.
- "Which department? We don't have a dentist here." (404) The thing you asked for doesn't exist.
- "Please show your ID card first." (401) We don't know who you are.
- "I know who you are, but you can't enter the operating theatre." (403) Known, but not permitted.
- "Your form is unreadable." (400) "Your form is readable, but you wrote age: -3." (422) The request itself is wrong.
- "You've come in 10 times today. Come back in an hour." (429) Too fast.
- "Our X-ray machine is broken. Try again this afternoon." (503) Our problem, temporary.
- "Something went wrong in here, sorry." (500) Our problem, unexpected.
The receptionist checks in a sensible order: first does the department exist, then who you are, then whether you're allowed, then whether your form is right. The first check that fails is what you're told.
Where the analogy stops working. A receptionist can explain in a long conversation. A status code is one number, and most clients only look at its first digit. That's why the class (2, 4 or 5) must be right even if the exact code is debatable; the details go in the response body.
The building blocks
- Classes first. 2xx success, 3xx redirection, 4xx the client must change something, 5xx the server failed. Getting the class right is more important than picking the perfect code inside it.
- The 2xx you'll use: 200 OK (here's the result), 201 Created (with
Location), 202 Accepted (queued, will happen later), 204 No Content (done, nothing to return). - The 3xx you'll use: 301/308 moved permanently, 302/307 temporarily (307/308 keep the method, 301/302 may turn POST into GET in browsers), 304 Not Modified.
- The 4xx you'll use:
- 400 Bad Request: malformed (invalid JSON, wrong types).
- 401 Unauthorized: really means unauthenticated: no credentials or bad ones. Send
WWW-Authenticateif you can. - 403 Forbidden: authenticated, but not allowed.
- 404 Not Found: no such resource (also used to hide that something exists from users who may not see it).
- 405 Method Not Allowed, with
Allow. - 409 Conflict: the request clashes with current state (version mismatch, duplicate unique value).
- 422 Unprocessable Content: well-formed but semantically invalid (qty 0, end date before start date). Many APIs use 400 for this too; pick one and be consistent.
- 429 Too Many Requests, ideally with
Retry-After.
- The 5xx you'll use: 500 Internal Server Error (a bug), 502 Bad Gateway (a proxy got a bad answer from upstream), 503 Service Unavailable (overloaded or a dependency is down, temporary; send
Retry-After), 504 Gateway Timeout (a proxy gave up waiting for upstream). - Order of checks matters. Route → method → authentication → authorisation → rate limit → validation → business rules → dependencies. Checking validation before authentication, for example, lets strangers probe your input rules.
- Retry rules follow from the class. 4xx: don't retry unchanged (except 429 after waiting, and sometimes 409 after re-reading). 5xx: retry with backoff, but only if the request is idempotent or the server says nothing happened (lesson 4).
A user is logged in, but tries to open another customer's invoice: GET /invoices/981. Which status should the API return?
Behind the scenes: reading an incident by status
Five spikes, five different responses
Step 1/5 Spike of 401s after a mobile release
Only the new app version gets them. Clients are sending expired or malformed tokens. Server is fine; roll back or fix the app.
- fault
- client
The picture to keep in your head
A status code answers three questions in one number:
- Whose fault? 4 = client, 5 = server.
- Try again? 4 = not unchanged (429: after waiting), 5 = yes, later, if safe.
- What to change? The exact code and the body: log in (401), slow down (429), fix this field (422).
Check in order, return the first failure, and keep the class honest.
Try it: which status?
Pick the right code
409 Conflict {"error":{"code":"email_taken"}}Code from first principles
A tiny server that checks every request in the standard order (route, method, identity, permission, rate limit, body format, body meaning, dependencies) and returns the first failure. A client-side advice function then reads only the status to decide whose fault it was and whether to retry.
package main
import (
"fmt"
"strconv"
"strings"
)
type request struct {
method, path, token, body string
paymentDown bool
}
var (
routes = map[string][]string{"/orders": {"POST"}, "/orders/7": {"GET", "DELETE"}}
users = map[string]string{"t-user": "user", "t-admin": "admin"}
seen = map[string]int{} // requests per token, for the rate limit
rateLimit = 5
reasons = map[int]string{200: "OK", 201: "Created", 400: "Bad Request", 401: "Unauthorized", 403: "Forbidden",
404: "Not Found", 405: "Method Not Allowed", 422: "Unprocessable Content", 429: "Too Many Requests", 503: "Service Unavailable"}
)
// handle runs the checks in the order a real server does them; the first failure decides the status.
func handle(r request) (int, string) {
allowed, ok := routes[r.path]
if !ok {
return 404, "no such resource"
}
if !contains(allowed, r.method) {
return 405, "Allow: " + strings.Join(allowed, ", ")
}
role, ok := users[r.token]
if !ok {
return 401, "who are you? send a valid token"
}
if r.method == "DELETE" && role != "admin" {
return 403, "you are known, but not allowed"
}
seen[r.token]++
if seen[r.token] > rateLimit {
return 429, "Retry-After: 60"
}
if r.method == "POST" {
if !strings.HasPrefix(r.body, "{") || !strings.HasSuffix(r.body, "}") {
return 400, "body is not valid JSON"
}
_, after, _ := strings.Cut(r.body, `"qty":`)
qty, _ := strconv.Atoi(strings.TrimSuffix(after, "}"))
if qty < 1 {
return 422, "qty must be at least 1"
}
if r.paymentDown {
return 503, "payment service down, Retry-After: 30"
}
return 201, "Location: /orders/8"
}
return 200, `{"id":7,"item":"pen"}`
}
func contains(list []string, s string) bool {
for _, x := range list {
if x == s {
return true
}
}
return false
}
// advice is what the client should conclude from the status alone.
func advice(code int) string {
switch {
case code < 300:
return "fault: none, retry: no"
case code == 429:
return "fault: client (too fast), retry: yes, after waiting"
case code < 500:
return "fault: client, retry: no, fix the request"
default:
return "fault: server, retry: yes, later"
}
}
func main() {
reqs := []request{
{"GET", "/orders/7", "t-user", "", false},
{"GET", "/orders/99", "t-user", "", false},
{"PUT", "/orders", "t-user", "", false},
{"POST", "/orders", "", `{"qty":2}`, false},
{"DELETE", "/orders/7", "t-user", "", false},
{"POST", "/orders", "t-user", `{"qty":0}`, false},
{"POST", "/orders", "t-user", `{"qty":`, false},
{"POST", "/orders", "t-user", `{"qty":2}`, true},
{"POST", "/orders", "t-user", `{"qty":2}`, false},
{"POST", "/orders", "t-user", `{"qty":2}`, false},
}
for i, r := range reqs {
code, detail := handle(r)
fmt.Printf("%2d. %s %s -> %d %s (%s)\n %s\n", i+1, r.method, r.path, code, reasons[code], detail, advice(code))
}
}const routes = { "/orders": ["POST"], "/orders/7": ["GET", "DELETE"] };
const users = { "t-user": "user", "t-admin": "admin" };
const seen = {}; // requests per token, for the rate limit
const rateLimit = 5;
const reasons = { 200: "OK", 201: "Created", 400: "Bad Request", 401: "Unauthorized", 403: "Forbidden",
404: "Not Found", 405: "Method Not Allowed", 422: "Unprocessable Content", 429: "Too Many Requests", 503: "Service Unavailable" };
// handle runs the checks in the order a real server does them; the first failure decides the status.
function handle(r) {
const allowed = routes[r.path];
if (!allowed) return [404, "no such resource"];
if (!allowed.includes(r.method)) return [405, "Allow: " + allowed.join(", ")];
const role = users[r.token];
if (!role) return [401, "who are you? send a valid token"];
if (r.method === "DELETE" && role !== "admin") return [403, "you are known, but not allowed"];
seen[r.token] = (seen[r.token] ?? 0) + 1;
if (seen[r.token] > rateLimit) return [429, "Retry-After: 60"];
if (r.method === "POST") {
if (!r.body.startsWith("{") || !r.body.endsWith("}")) return [400, "body is not valid JSON"];
const after = r.body.split('"qty":')[1] ?? "";
const qty = parseInt(after.replace(/}$/, ""), 10) || 0;
if (qty < 1) return [422, "qty must be at least 1"];
if (r.paymentDown) return [503, "payment service down, Retry-After: 30"];
return [201, "Location: /orders/8"];
}
return [200, '{"id":7,"item":"pen"}'];
}
// advice is what the client should conclude from the status alone.
function advice(code) {
if (code < 300) return "fault: none, retry: no";
if (code === 429) return "fault: client (too fast), retry: yes, after waiting";
if (code < 500) return "fault: client, retry: no, fix the request";
return "fault: server, retry: yes, later";
}
const reqs = [
["GET", "/orders/7", "t-user", "", false],
["GET", "/orders/99", "t-user", "", false],
["PUT", "/orders", "t-user", "", false],
["POST", "/orders", "", '{"qty":2}', false],
["DELETE", "/orders/7", "t-user", "", false],
["POST", "/orders", "t-user", '{"qty":0}', false],
["POST", "/orders", "t-user", '{"qty":', false],
["POST", "/orders", "t-user", '{"qty":2}', true],
["POST", "/orders", "t-user", '{"qty":2}', false],
["POST", "/orders", "t-user", '{"qty":2}', false],
].map(([method, path, token, body, paymentDown]) => ({ method, path, token, body, paymentDown }));
reqs.forEach((r, i) => {
const [code, detail] = handle(r);
console.log(`${String(i + 1).padStart(2)}. ${r.method} ${r.path} -> ${code} ${reasons[code]} (${detail})\n ${advice(code)}`);
});use std::collections::HashMap;
struct Request {
method: &'static str,
path: &'static str,
token: &'static str,
body: &'static str,
payment_down: bool,
}
struct Server {
seen: HashMap<&'static str, u32>, // requests per token, for the rate limit
}
const RATE_LIMIT: u32 = 5;
fn reason(code: u16) -> &'static str {
match code {
200 => "OK",
201 => "Created",
400 => "Bad Request",
401 => "Unauthorized",
403 => "Forbidden",
404 => "Not Found",
405 => "Method Not Allowed",
422 => "Unprocessable Content",
429 => "Too Many Requests",
_ => "Service Unavailable",
}
}
impl Server {
// handle runs the checks in the order a real server does them; the first failure decides the status.
fn handle(&mut self, r: &Request) -> (u16, String) {
let allowed: &[&str] = match r.path {
"/orders" => &["POST"],
"/orders/7" => &["GET", "DELETE"],
_ => return (404, "no such resource".into()),
};
if !allowed.contains(&r.method) {
return (405, format!("Allow: {}", allowed.join(", ")));
}
let role = match r.token {
"t-user" => "user",
"t-admin" => "admin",
_ => return (401, "who are you? send a valid token".into()),
};
if r.method == "DELETE" && role != "admin" {
return (403, "you are known, but not allowed".into());
}
let count = self.seen.entry(r.token).or_insert(0);
*count += 1;
if *count > RATE_LIMIT {
return (429, "Retry-After: 60".into());
}
if r.method == "POST" {
if !r.body.starts_with('{') || !r.body.ends_with('}') {
return (400, "body is not valid JSON".into());
}
let after = r.body.split_once("\"qty\":").map_or("", |(_, a)| a);
let qty: i32 = after.trim_end_matches('}').parse().unwrap_or(0);
if qty < 1 {
return (422, "qty must be at least 1".into());
}
if r.payment_down {
return (503, "payment service down, Retry-After: 30".into());
}
return (201, "Location: /orders/8".into());
}
(200, r#"{"id":7,"item":"pen"}"#.into())
}
}
// advice is what the client should conclude from the status alone.
fn advice(code: u16) -> &'static str {
match code {
0..=299 => "fault: none, retry: no",
429 => "fault: client (too fast), retry: yes, after waiting",
300..=499 => "fault: client, retry: no, fix the request",
_ => "fault: server, retry: yes, later",
}
}
fn main() {
let r = |method, path, token, body, payment_down| Request { method, path, token, body, payment_down };
let reqs = [
r("GET", "/orders/7", "t-user", "", false),
r("GET", "/orders/99", "t-user", "", false),
r("PUT", "/orders", "t-user", "", false),
r("POST", "/orders", "", r#"{"qty":2}"#, false),
r("DELETE", "/orders/7", "t-user", "", false),
r("POST", "/orders", "t-user", r#"{"qty":0}"#, false),
r("POST", "/orders", "t-user", r#"{"qty":"#, false),
r("POST", "/orders", "t-user", r#"{"qty":2}"#, true),
r("POST", "/orders", "t-user", r#"{"qty":2}"#, false),
r("POST", "/orders", "t-user", r#"{"qty":2}"#, false),
];
let mut server = Server { seen: HashMap::new() };
for (i, req) in reqs.iter().enumerate() {
let (code, detail) = server.handle(req);
println!("{:2}. {} {} -> {code} {} ({detail})\n {}", i + 1, req.method, req.path, reason(code), advice(code));
}
}routes = {"/orders": ["POST"], "/orders/7": ["GET", "DELETE"]}
users = {"t-user": "user", "t-admin": "admin"}
seen = {} # requests per token, for the rate limit
RATE_LIMIT = 5
reasons = {200: "OK", 201: "Created", 400: "Bad Request", 401: "Unauthorized", 403: "Forbidden",
404: "Not Found", 405: "Method Not Allowed", 422: "Unprocessable Content", 429: "Too Many Requests",
503: "Service Unavailable"}
def handle(r):
"""Run the checks in the order a real server does them; the first failure decides the status."""
allowed = routes.get(r["path"])
if allowed is None:
return 404, "no such resource"
if r["method"] not in allowed:
return 405, "Allow: " + ", ".join(allowed)
role = users.get(r["token"])
if role is None:
return 401, "who are you? send a valid token"
if r["method"] == "DELETE" and role != "admin":
return 403, "you are known, but not allowed"
seen[r["token"]] = seen.get(r["token"], 0) + 1
if seen[r["token"]] > RATE_LIMIT:
return 429, "Retry-After: 60"
if r["method"] == "POST":
body = r["body"]
if not (body.startswith("{") and body.endswith("}")):
return 400, "body is not valid JSON"
after = body.partition('"qty":')[2].removesuffix("}")
qty = int(after) if after.lstrip("-").isdigit() else 0
if qty < 1:
return 422, "qty must be at least 1"
if r["payment_down"]:
return 503, "payment service down, Retry-After: 30"
return 201, "Location: /orders/8"
return 200, '{"id":7,"item":"pen"}'
def advice(code):
"""What the client should conclude from the status alone."""
if code < 300:
return "fault: none, retry: no"
if code == 429:
return "fault: client (too fast), retry: yes, after waiting"
if code < 500:
return "fault: client, retry: no, fix the request"
return "fault: server, retry: yes, later"
reqs = [
("GET", "/orders/7", "t-user", "", False),
("GET", "/orders/99", "t-user", "", False),
("PUT", "/orders", "t-user", "", False),
("POST", "/orders", "", '{"qty":2}', False),
("DELETE", "/orders/7", "t-user", "", False),
("POST", "/orders", "t-user", '{"qty":0}', False),
("POST", "/orders", "t-user", '{"qty":', False),
("POST", "/orders", "t-user", '{"qty":2}', True),
("POST", "/orders", "t-user", '{"qty":2}', False),
("POST", "/orders", "t-user", '{"qty":2}', False),
]
for i, (method, path, token, body, down) in enumerate(reqs, start=1):
code, detail = handle({"method": method, "path": path, "token": token, "body": body, "payment_down": down})
print(f"{i:2d}. {method} {path} -> {code} {reasons[code]} ({detail})\n {advice(code)}")import java.util.*;
public class Main {
record Request(String method, String path, String token, String body, boolean paymentDown) {}
static final Map<String, List<String>> ROUTES = Map.of("/orders", List.of("POST"), "/orders/7", List.of("GET", "DELETE"));
static final Map<String, String> USERS = Map.of("t-user", "user", "t-admin", "admin");
static final Map<String, Integer> SEEN = new HashMap<>(); // requests per token, for the rate limit
static final int RATE_LIMIT = 5;
static final Map<Integer, String> REASONS = Map.of(200, "OK", 201, "Created", 400, "Bad Request", 401, "Unauthorized",
403, "Forbidden", 404, "Not Found", 405, "Method Not Allowed", 422, "Unprocessable Content", 429, "Too Many Requests",
503, "Service Unavailable");
// handle runs the checks in the order a real server does them; the first failure decides the status.
static Object[] handle(Request r) {
List<String> allowed = ROUTES.get(r.path());
if (allowed == null) return new Object[] {404, "no such resource"};
if (!allowed.contains(r.method())) return new Object[] {405, "Allow: " + String.join(", ", allowed)};
String role = USERS.get(r.token());
if (role == null) return new Object[] {401, "who are you? send a valid token"};
if (r.method().equals("DELETE") && !role.equals("admin")) return new Object[] {403, "you are known, but not allowed"};
int count = SEEN.merge(r.token(), 1, Integer::sum);
if (count > RATE_LIMIT) return new Object[] {429, "Retry-After: 60"};
if (r.method().equals("POST")) {
String body = r.body();
if (!body.startsWith("{") || !body.endsWith("}")) return new Object[] {400, "body is not valid JSON"};
int at = body.indexOf("\"qty\":");
String after = at < 0 ? "" : body.substring(at + 6).replaceAll("}$", "");
int qty;
try { qty = Integer.parseInt(after); } catch (NumberFormatException e) { qty = 0; }
if (qty < 1) return new Object[] {422, "qty must be at least 1"};
if (r.paymentDown()) return new Object[] {503, "payment service down, Retry-After: 30"};
return new Object[] {201, "Location: /orders/8"};
}
return new Object[] {200, "{\"id\":7,\"item\":\"pen\"}"};
}
// advice is what the client should conclude from the status alone.
static String advice(int code) {
if (code < 300) return "fault: none, retry: no";
if (code == 429) return "fault: client (too fast), retry: yes, after waiting";
if (code < 500) return "fault: client, retry: no, fix the request";
return "fault: server, retry: yes, later";
}
public static void main(String[] args) {
Request[] reqs = {
new Request("GET", "/orders/7", "t-user", "", false),
new Request("GET", "/orders/99", "t-user", "", false),
new Request("PUT", "/orders", "t-user", "", false),
new Request("POST", "/orders", "", "{\"qty\":2}", false),
new Request("DELETE", "/orders/7", "t-user", "", false),
new Request("POST", "/orders", "t-user", "{\"qty\":0}", false),
new Request("POST", "/orders", "t-user", "{\"qty\":", false),
new Request("POST", "/orders", "t-user", "{\"qty\":2}", true),
new Request("POST", "/orders", "t-user", "{\"qty\":2}", false),
new Request("POST", "/orders", "t-user", "{\"qty\":2}", false),
};
for (int i = 0; i < reqs.length; i++) {
Object[] res = handle(reqs[i]);
int code = (Integer) res[0];
System.out.printf("%2d. %s %s -> %d %s (%s)%n %s%n", i + 1, reqs[i].method(), reqs[i].path(), code, REASONS.get(code), res[1], advice(code));
}
}
}Output (the same in all five languages):
1. GET /orders/7 -> 200 OK ({"id":7,"item":"pen"})
fault: none, retry: no
2. GET /orders/99 -> 404 Not Found (no such resource)
fault: client, retry: no, fix the request
3. PUT /orders -> 405 Method Not Allowed (Allow: POST)
fault: client, retry: no, fix the request
4. POST /orders -> 401 Unauthorized (who are you? send a valid token)
fault: client, retry: no, fix the request
5. DELETE /orders/7 -> 403 Forbidden (you are known, but not allowed)
fault: client, retry: no, fix the request
6. POST /orders -> 422 Unprocessable Content (qty must be at least 1)
fault: client, retry: no, fix the request
7. POST /orders -> 400 Bad Request (body is not valid JSON)
fault: client, retry: no, fix the request
8. POST /orders -> 503 Service Unavailable (payment service down, Retry-After: 30)
fault: server, retry: yes, later
9. POST /orders -> 201 Created (Location: /orders/8)
fault: none, retry: no
10. POST /orders -> 429 Too Many Requests (Retry-After: 60)
fault: client (too fast), retry: yes, after waiting
Reading the output:
- 2 and 3: 404 and 405 come first; there's no point asking who you are for a route that doesn't exist. The 405 says which method would work.
- 4 vs 5: no token is 401 ("who are you?"); a valid user token trying an admin action is 403 ("known, not allowed").
- 6 vs 7:
{"qty":0}is valid JSON with a bad value, so 422;{"qty":isn't JSON at all, so 400. - 8: the request was fine, but the payment service was down. 503 with
Retry-Aftersays "our side, temporary". Retrying this POST is OK only because the server refused before doing anything. - 10: the sixth request from
t-userthat reached the rate limiter, over the limit of 5: 429. It's a 4xx (the client has to change its behaviour), but the one 4xx that's worth retrying after waiting.
The same patterns in a real public API:
$ for u in https://api.github.com/ https://api.github.com/user https://api.github.com/repos/torvalds/no-such-repo-xyz; do printf "%s -> " "$u"; curl -s -o /dev/null -w "%{http_code}\n" "$u"; done
https://api.github.com/ -> 200
https://api.github.com/user -> 401
https://api.github.com/repos/torvalds/no-such-repo-xyz -> 404
$ curl -s https://api.github.com/user
{
"message": "Requires authentication",
"documentation_url": "https://docs.github.com/rest",
"status": "401"
}
$ curl -s -D - -o /dev/null https://api.github.com/ | tr -d '\r' | grep -iE "^(HTTP|x-ratelimit-limit|x-ratelimit-remaining)"
HTTP/2 200
x-ratelimit-limit: 60
x-ratelimit-remaining: 40
/userwithout a token is 401, and the body explains it in words, with a link to the docs. Status for programs, body for humans.- A missing repo is 404. (GitHub also returns 404 for private repos you can't see, rather than 403, so outsiders can't learn they exist.)
- The rate limit is announced up front: 60 requests per hour for anonymous clients, 40 left for this machine. Go over it and you get 403 or 429 from GitHub, with the reset time in headers.
Real engineering
- One error shape for the whole API. For example
{"error":{"code":"qty_too_small","message":"qty must be at least 1","field":"qty"}}. Clients branch oncode, showmessage, highlightfield. Some teams use the standard "problem details" format (application/problem+json). - Map exceptions to statuses in one place. A middleware that turns
NotFoundErrorinto 404,ValidationErrorinto 422, anything unknown into 500. Handlers raise meaningful errors; they don't pick numbers. - Never leak internals in 5xx. Log the stack trace with a request ID; return only the ID and a generic message.
- Alert on 5xx, watch 4xx. 5xx means you're broken. A sudden 4xx spike often means a client release broke, or someone is probing you.
- Send
Retry-Afterwith 429 and 503. Well-behaved clients wait exactly that long instead of guessing. - Don't invent codes. Use the standard ones. Custom numbers like 299 or 499 confuse proxies and libraries. (Nginx's 499 "client closed request" exists only in its own logs; it's never sent to anyone.)
When it breaks
Pick a failure
403 returned as 401 for 'not allowed' actions
Think before you read on
Your API receives POST /orders and calls the payment provider, which times out after 10 seconds. You don't know whether the payment went through. What status do you return, and what should the client do?
Reveal
This is the hardest case: the outcome is unknown. A 5xx is honest (504 if you think of yourself as a gateway to the provider, or 502/503), but the client must not blindly retry, because the charge may have happened. The safe design: the client sent an idempotency key, so retrying with the same key lets the server check "did order K already succeed?" and return the stored result instead of charging again. Meanwhile, the server should reconcile with the provider (ask "what happened to payment K?") before deciding. Status codes signal what happened; idempotency makes the unknown case safe.
Check yourself
1. What's the difference between 401 and 403?
Answer
401 means the server doesn't know who you are (no credentials or invalid ones), so authenticate. 403 means it knows who you are, and you're not allowed to do this.
2. When would you use 422 instead of 400?
Answer
400 for a malformed request (not valid JSON, wrong types). 422 for a well-formed request whose content breaks a rule (qty 0, end date before start). Some APIs use 400 for both; consistency matters most.
3. Which status codes are usually worth retrying, and how?
Answer
5xx (especially 502, 503, 504) and 429, with exponential backoff and jitter, honouring Retry-After, and only for idempotent requests or ones protected by an idempotency key.
4. Why should validation happen after authentication in the check order?
Answer
So unauthenticated strangers can't learn anything about your input rules or resources by probing; they're stopped at 401 before any detailed validation errors are revealed.
Your challenge: one place for errors
Refactor the code so handlers don't return numbers:
- Define error types (or classes, or enum values):
NotFound,MethodNotAllowed,Unauthenticated,Forbidden,RateLimited,BadJSON,Invalid,DependencyDown. - Make
handlereturn (or raise) one of those errors instead of a status code. - Write a single
toResponse(err)that maps each error to its status, reason and a JSON body{"error":{"code":"...","message":"..."}}.
Before you run it, predict whether the ten output lines' status codes will change.
You've succeeded when the ten requests produce exactly the same status codes as before, every error body has the same shape, and adding a new error type means changing only toResponse.
The mental model
A status code answers three questions in one number: whose fault (4 = client, 5 = server), whether to retry (4 = not unchanged, except 429 after waiting; 5 = later, if safe), and what to change (the exact code plus a consistent error body). Check requests in order, route, method, identity, permission, rate, validity, dependencies, and return the first failure. Get the class right, send Retry-After when you can, and never hide a failure behind a 200.
Station stamp
Finish the chapter
Done reading? Press Complete to save your progress. XP is Pro-only — on Pro this chapter is worth +10 XP.
Go Pro to earn XP →