HTTP wire contract: messages and observable outcomes
Why you care
Every backend bug report eventually reduces to "what did the server actually say back," and the answer is a status code plus headers, not a feeling. Interviewers ask "what's the difference between 401 and 403" or "what does 202 mean" precisely because those answers reveal whether you have only ever glanced at a 200/404/500 and guessed at everything else. In ETL and integration work specifically, webhooks and partner callbacks are just HTTP requests arriving instead of leaving, and treating them differently from a client call you make is the source of half the "why did we double-process this" incidents. If you cannot tell "accepted" apart from "completed" at a glance, you will build something that lies about its own state.
Explain like I'm 5
An HTTP request is a filled-out courier form: the request line says where it's going and what kind of job it is (deliver, replace, remove), the headers are the special instructions taped to the box (fragile, cash on delivery, my account number), and the body is what's actually inside. The response is the courier's receipt: a status code that says what happened (delivered, refused, come back later), headers with details, and sometimes a body with more information. A "202 Accepted" is the courier taking the box and handing you a tracking slip - it says nothing about whether the parcel has arrived yet. A "200 OK" on a status check is the confirmation that it actually got there.
Core concept
An HTTP message has three parts on each side: a request line (method, path, version) or status line (version, status code, reason phrase), a set of headers (case-insensitive name: value pairs, repeatable), and an optional body. Headers describe the message; the body carries the payload. A connection carries one or more of these request/response pairs, one at a time per HTTP/1.1 connection (Trace TLS and HTTP/1.1, HTTP/2 and HTTP/3 covers what changes for HTTP/2 and HTTP/3). A webhook is not a different protocol - it's an ordinary HTTP request your service receives instead of sends, which is why everything in this card applies to writing a receiver, not just a client (Receive authenticated, replay-aware webhooks).
Status codes are grouped by their first digit, and the exact code inside each group matters:
- 2xx - it worked.
200the response body carries the result.201a resource was created; expect aLocationheader pointing at it.204it worked and there is deliberately no body (a delete, a health check).202is the odd one out: the request was accepted, not completed - the work happens later, out of band, and HTTP gives you no built-in mechanism to be told when it finishes; you poll or you get a separate callback. - 3xx - go elsewhere.
301/302mean "moved" (permanently/temporarily); historically, some clients turned a redirectedPOSTinto aGET, which is exactly the kind of surprise that makes redirects risky for anything butGET/HEAD.307/308are the same permanent/temporary pair but promise to preserve the method and body - use these when aPOSTmust stay aPOSTafter the redirect. - 4xx - your request, your problem.
400malformed or unparsable.401means "I don't know who you are" (no or invalid credentials).403means "I know who you are, and no."404resource not found - or deliberately used instead of403to avoid confirming something exists.409the request conflicts with the current state of the resource (two people editing the same row).422the request is well-formed JSON/XML but semantically invalid (a negative amount, a missing required field).429you're being rate-limited; a well-behaved server sendsRetry-After. - 5xx - the server's problem.
500generic, unhandled failure.502a gateway/proxy got an invalid response from whatever is behind it.503temporarily unavailable (overloaded, draining, maintenance) - responses here should not be cached.504a gateway timed out waiting on whatever is behind it.
The decision rule: pick the status that describes what actually happened, not the closest one you remember. If work is deferred, that's 202, not 200 with a note in the body. If the client is wrong, use the most specific 4xx you have; if the client did nothing wrong and it's you, use the most specific 5xx. Never encode the real outcome only in the body while returning 200 - anything downstream that reads status codes (caches, load balancers, retry logic, monitoring) will believe the status line, not your JSON.
Minimal example One server, three outcomes you can read off the status line
import http.server, threading, http.client
class Handler(http.server.BaseHTTPRequestHandler):
def log_message(self, *a): pass
def do_GET(self):
if self.path == "/health":
self.send_response(204)
self.end_headers()
else:
self.send_response(404)
self.send_header("Content-Type", "text/plain")
self.end_headers()
self.wfile.write(b"not found")
def do_POST(self):
self.send_response(201)
self.send_header("Location", "/orders/1")
self.end_headers()
server = http.server.HTTPServer(("127.0.0.1", 0), Handler)
port = server.server_address[1]
threading.Thread(target=server.serve_forever, daemon=True).start()
conn = http.client.HTTPConnection("127.0.0.1", port)
conn.request("GET", "/health")
r = conn.getresponse(); print(r.status, r.reason); r.read()
conn.request("POST", "/orders", body=b'{"amount":100}', headers={"Content-Type":"application/json"})
r = conn.getresponse(); print(r.status, r.getheader("Location")); r.read()
conn.request("GET", "/missing")
r = conn.getresponse(); print(r.status, r.read())
server.shutdown()204 No Content
201 /orders/1
404 b'not found'In production Accepted now, complete later - and a conflict in between
import http.server, threading, http.client, time
orders = {} # id -> "processing" | "done"
class Handler(http.server.BaseHTTPRequestHandler):
def log_message(self, *a): pass
def do_POST(self):
if self.path == "/orders":
length = int(self.headers.get("Content-Length", 0))
self.rfile.read(length)
order_id = str(len(orders) + 1)
orders[order_id] = "processing"
self.send_response(202)
self.send_header("Location", f"/orders/{order_id}")
self.end_headers()
elif self.path.endswith("/cancel"):
order_id = self.path.split("/")[2]
if orders.get(order_id) == "done":
self.send_response(409)
self.end_headers()
else:
orders[order_id] = "cancelled"
self.send_response(200)
self.end_headers()
else:
self.send_response(404)
self.end_headers()
def do_GET(self):
order_id = self.path.split("/")[-1]
status = orders.get(order_id)
if status is None:
self.send_response(404)
self.end_headers()
elif status == "processing":
self.send_response(202)
self.end_headers()
else:
self.send_response(200)
self.end_headers()
server = http.server.HTTPServer(("127.0.0.1", 0), Handler)
port = server.server_address[1]
threading.Thread(target=server.serve_forever, daemon=True).start()
conn = http.client.HTTPConnection("127.0.0.1", port)
conn.request("POST", "/orders", body=b"{}")
r = conn.getresponse(); loc = r.getheader("Location"); print("create:", r.status, loc); r.read()
conn.request("GET", loc)
r = conn.getresponse(); print("poll while processing:", r.status); r.read()
orders["1"] = "done" # stand-in for the worker finishing the job
conn.request("GET", loc)
r = conn.getresponse(); print("poll after worker finished:", r.status); r.read()
conn.request("POST", "/orders/1/cancel")
r = conn.getresponse(); print("cancel after done:", r.status); r.read()
server.shutdown()create: 202 /orders/1
poll while processing: 202
poll after worker finished: 200
cancel after done: 409See it happen Accept is not complete
- Client sends the request line, headers and body in one message.
- The server has only accepted the work; nothing about the order is guaranteed done yet.
- Client polls the status endpoint named in Location.
- Still processing: same status family, no new information beyond 'not yet'.
- The actual completion happens out of band, driven by a worker, not by this HTTP exchange.
- Client polls again.
- Only now does the status code say the work is actually complete.
In your world
The situation
Your nightly job posts each of the day's 800 refunds to an internal ledger API and logs 200 OK for every call, treating any 2xx as "done."
What actually breaks
The ledger API actually returns 202 Accepted while it queues refunds for a fraud check, then 200 once approved and 409 if a refund was already reversed. Your job's audit log shows 800 successes; finance later finds only 640 refunds actually posted, because 160 are still sitting in the fraud queue and your code never checked which 2xx it got.
What you'd do on Monday
Branch on the exact code instead of 2xx in general, and poll or subscribe for the ones that were only accepted:
resp = post_refund(payload)
if resp.status_code == 201:
mark_done(payload["id"])
elif resp.status_code == 202:
queue_for_followup(payload["id"], resp.headers["Location"])
elif resp.status_code == 409:
log.warning("refund %s already reversed, skipping", payload["id"])
else:
raise RuntimeError(f"unexpected {resp.status_code} for refund {payload['id']}")Imagine you work at Akamai
The numbers
Illustrative: one edge point of presence handling 2,000,000 requests/minute is about 33,333 requests/second. If the origin behind it returns 502/504 for even 0.1% of that traffic under load, that's ~33 failed requests every second, or roughly 2.9 million failed edge-to-origin calls in a single day - small percentages become large absolute counts once you multiply by request volume, not request count per script run.
What the Scenario-A answer does here
The Scenario A fix (branch on the exact status) still holds for a single service, but "just return 200 with an {"ok": false} field so nothing downstream has to think about status codes" breaks badly here: intermediate caches, retry logic and monitoring at the edge make automated decisions off the status line itself, and a 200 body they never parse looks identical to a real success.
What flips at this scale
At CDN scale, the status code is a machine-readable contract other systems act on without reading your body: a cache decides whether to store the response, a load balancer decides whether to retry against another origin, and an alert decides whether to page someone - all based on the exact code and headers like Retry-After, not on inspecting JSON.
The trade-off you'd defend
I would defend precise status codes plus Retry-After on every error path over a uniform 200 with an error flag in the body, trading a slightly more complex client-side branch for correct caching, retry and alerting behavior at a scale where nobody is reading bodies by hand.
Illustrative traffic and error-rate figures chosen to make the arithmetic concrete; not Akamai-published numbers.
Gotchas
Returning 200 with the real outcome buried in the body
Dashboards and logs show 100% success while the business operation actually failed.
The status line is what caches, proxies, retry logic and monitoring read; a 200 says "success" to all of them regardless of what the JSON body says.
Return the status that matches the outcome (4xx/5xx/202) and keep the body for detail, not as the only source of truth.
Confusing 401 with 403
A client shows "please log in" when the real problem is a permissions gap, or shows "access denied" for someone who was never authenticated at all.
401 means the server doesn't know who's asking (missing/invalid credentials); 403 means it does know, and says no anyway.
Return 401 only when authentication itself failed or is missing; return 403 once identity is established but the action is disallowed.
A 302 quietly turns your POST into a GET
An automated client following a redirect after a POST arrives at the next URL with no body and a GET, silently dropping data.
302/301 have historically been treated by clients as license to switch the method to GET.
Use 307/308 when the method and body must be preserved across the redirect.
429 without Retry-After
A rate-limited client backs off for an arbitrary guessed duration, either hammering the server again too soon or waiting far longer than necessary.
429 alone tells the client it was throttled but not for how long.
Always send Retry-After on 429 (and on 503), and have clients honor it instead of guessing.
Tricky questions
No - 404 means "not found," full stop, so it's only used when the resource genuinely doesn't exist.
Servers deliberately return 404 instead of 403 when they don't want to confirm a resource exists at all (a private repo, another user's record). 403 reveals existence and denies access; 404 denies existence itself. Which one you choose is a security decision, not just an accuracy one.
Yes, 500 always means the application threw an unhandled exception.
500 is the generic catch-all for "something went wrong and I have no better code for it." A well-designed service maps known failure modes to specific codes - 502/503/504 for upstream problems, 409/422 for a bad-but-well-formed request - and reserves 500 for genuinely unexpected failures, so a spike in 500s specifically (not 4xx) is the signal worth paging on.
Scenario question
You're handed a partner integration spec that says "call our endpoint; a 200 response means the operation completed." Your own client needs to know definitively whether money moved before it updates its own ledger. How do you build the client?
Model answer
I would not trust "200 means done" as the whole story without checking what the partner actually documents for their async paths - if any endpoint can return 202, I treat that as "accepted, not complete" and poll a status URL (or subscribe to a webhook) until I see a terminal code. Even where they claim synchronous 200 completion, I would still handle 409 (already applied) and 5xx (unknown outcome, safe to retry only if idempotent) explicitly rather than assuming every non-200 is the same kind of failure. The trade-off is more branches in the client than "if 200, done" - but the alternative is a ledger that's wrong the first time the partner's "always synchronous" claim turns out to have an exception.
Interview corner
CommonWalk me through what happens, at the message level, when a client calls an API.
TrickA client gets 200 back from a POST, but the operation actually failed halfway through. What's wrong?
Experience checkWhere have status codes bitten you in real ETL or integration work?
CommonWhat's the practical difference between 202 and 200?
Memory hook
A courier's tracking slip (202) is not the same as a signed delivery receipt (200) - one says "I took it," the other says "it arrived."
The status code, not the body, is what the rest of the system trusts - make it tell the truth.
Self-check
What's the difference between 401 and 403?
401 means the server doesn't know who you are (no/invalid credentials); 403 means it knows and refuses anyway.
Why is 202 different from every other 2xx code?
It means the request was accepted, not completed - the work happens later, out of band, with no HTTP-native way to be notified when it finishes.
Why should 301/302 redirects be treated carefully for a POST?
Some clients historically turn the redirected request into a GET, silently dropping the method and body; use 307/308 when the method must be preserved.
Extend the minimal example's server with a /orders/<id>/cancel route that returns 409 if the order is already done, and a client script that creates an order, polls it twice, marks it done, then tries to cancel it. Paste the four status codes your script prints, in order, and explain in one sentence why the last one is a 409 and not a 200.