Part 03 · The Language of the Web

Status Codes and Error Meanings

StatusCodes

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:

QuestionWhy it mattersWho needs the answer
Whose fault is it?Fix the client or fix the serverDevelopers, on-call engineers
Should I try again?Retrying a bad request is useless; not retrying a temporary failure loses dataRetry 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.

route?404method?405who?401allowed?403too fast?429valid?400/422deps ok?503201createdno tokenstops at who? → 401qty: 0stops at valid? → 422good orderthe first failed check decides the status
A request passes a row of checks in order: does the route exist (404), is the method allowed (405), who is this (401), are they allowed (403), are they too fast (429), is the input valid (400 or 422), are dependencies up (503). A request with no token stops at the identity check with 401. One with qty 0 stops at validation with 422. A good order passes every check and gets 201 Created.

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

  1. 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.
  2. 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).
  3. 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.
  4. 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-Authenticate if 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.
  5. 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).
  6. 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.
  7. 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).
Predict first

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

Step through it

Five spikes, five different responses

DashboardOn-call engineerClientServer

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?

Try each case

Pick the right code

409 Conflict  {"error":{"code":"email_taken"}}
works: The request is fine, but it clashes with existing state. 409 (or 422) with a clear code lets the app show 'this email is already in use'.

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

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-After says "our side, temporary". Retrying this POST is OK only because the server refused before doing anything.
  • 10: the sixth request from t-user that 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
  • /user without 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 on code, show message, highlight field. Some teams use the standard "problem details" format (application/problem+json).
  • Map exceptions to statuses in one place. A middleware that turns NotFoundError into 404, ValidationError into 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-After with 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

Try each case

Pick a failure

403 returned as 401 for 'not allowed' actions
breaks: Clients treat 401 as 'your token is bad, log in again'. Use 403 for permission problems so valid sessions stay alive.

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 handle return (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 →