HTTP

From a site's name to a response: watch one request go through DNS, TCP and TLS and come back as a status code. Then send requests to a toy shop yourself, and compare status codes, methods and each HTTP version side by side.

Level: BasicWatch: 12 steps · ~1 minuteSend requests yourselfRecall: 3 questions · 9 cardsCompare 18 status codesTypeScript · Go · Python

What you'll take away

  • Trace what happens after you press Enter: DNS, TCP and TLS, then the HTTP request
  • Tell a 401 from a 403 and a 4xx from a 5xx, and know which one a retry can fix
  • Know which methods are safe to send twice, and why a second POST may order twice
  • Use an ETag and If-None-Match to get a short 304 instead of the whole body again

The 1-minute version

Tap a point and the picture below plays that step.

4Compare them all
DNS: ask for the addressmessage 1 of 12
DNS
browser
A? shop.example → …
Step 1 / 12 · step by step
0Round trips (RTT) so far
not yetEncrypted
–connection
0Messages landed
–status

The picture: your laptop at the front of the street, the shop's server at the far end and DNS on the corner. A light is one message, out on one lane and back on the other; a lock rides on it once the connection is encrypted. The name shop.example and the IP 203.0.113.10 are reserved for examples (RFC 2606, RFC 5737). The server in the "Play" step runs in this page; no request leaves your machine.

Step 4 · Every option at once, on one clock

Compare them all: HTTP

Every tile sends the same kind of request at the same moment; watch what the server answers and what it means. Badge colors: 2xx worked, 3xx go somewhere else, 4xx the client got it wrong, 5xx the server broke. 502 / 503 are what a load balancer answers (the Load balancer lesson).

0.0 s
200 OKDone: here's what you asked for

Use it when A GET that found it, or a PUT / PATCH that answers with the data

Skip it when When it actually failed: a 200 with { error } inside fools caches and monitoring

Small scenes of what really happens: the request and response in each tile are made up for this lesson. Press any tile to see it large above, with when it fits.

HTTP is text in an agreed format

A request = a first line (method, path, version) + headers + a blank line + a body. A response = a status line (the status code) + headers + a body. HTTP remembers nothing between requests: who you are has to come along with every request, in a header such as a cookie or Authorization.

Methods

methodWhat it doessafeidempotent
GETRead✓✓
POSTCreate / submit work✗✗
PUTReplace the whole thing✗✓
PATCHChange part of it✗Depends on how you write it
DELETEDelete✗✓

Five groups of status codes

  • 1xx Information along the way (101, for example: switching to WebSocket)
  • 2xx It worked · 3xx Go somewhere else, or use the copy you already have
  • 4xx The client got it wrong: fix the request before you send it again
  • 5xx The server broke: you can try again later; the request wasn't wrong

Caching with ETag

The server attaches an ETag (a version tag for the data) to the response. Next time, the browser asks with If-None-Match; if it's still the same version, the server answers a short 304 and doesn't send the body again. Cache-Control says how long the copy can be kept without asking.

One request, one response. For a page that has to hear about changes as they happen: Polling, SSE and WebSocket.

HTTP/1.1, HTTP/2, HTTP/3

The messages are the same; what changes is how they travel. HTTP/1.1 sends one request at a time per connection. HTTP/2 sends many requests at once over one connection, but TCP hands data over in order, so one lost packet holds everything up. HTTP/3 moves onto QUIC (UDP), where each stream only waits for its own data, and connections open faster.

In real code

server.ts
// A tiny HTTP server and client (node:http + fetch) on 127.0.0.1 and a port the OS picks:
// an ETag answered with 304, a 201 with Location, a 429 with Retry-After, a 404.
// Run: node server.ts   (Node 23.6+; on Node 22: node --experimental-strip-types server.ts)
import assert from "node:assert/strict";
import { createServer } from "node:http";
import type { AddressInfo } from "node:net";

const orders = new Map([[42, { id: 42, item: "Thai tea", v: 3 }]]);
let nextId = 43;
const hits: number[] = [];

const server = createServer((req, res) => {
  const url = new URL(req.url ?? "/", "http://localhost");
  if (req.method === "GET" && url.pathname === "/orders/42") {
    const o = orders.get(42)!;
    const etag = `"v${o.v}"`;
    if (req.headers["if-none-match"] === etag) return res.writeHead(304, { ETag: etag }).end();
    return res.writeHead(200, { "Content-Type": "application/json", ETag: etag }).end(JSON.stringify(o));
  }
  if (req.method === "POST" && url.pathname === "/orders") {
    const o = { id: nextId++, item: "green tea", v: 1 };
    orders.set(o.id, o);
    return res.writeHead(201, { "Content-Type": "application/json", Location: `/orders/${o.id}` }).end(JSON.stringify(o));
  }
  if (req.method === "GET" && url.pathname === "/search") {
    const now = Date.now();
    while (hits.length && now - hits[0] > 10_000) hits.shift();
    if (hits.length >= 2) return res.writeHead(429, { "Retry-After": "10" }).end();
    hits.push(now);
    return res.writeHead(200, { "Content-Type": "application/json" }).end("[]");
  }
  res.writeHead(404).end();
});

await new Promise<void>((ok) => server.listen(0, "127.0.0.1", ok));
const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;

const first = await fetch(`${base}/orders/42`);
const etag = first.headers.get("etag")!;
await first.text();
const again = await fetch(`${base}/orders/42`, { headers: { "If-None-Match": etag } });
const created = await fetch(`${base}/orders`, { method: "POST" });
await created.text();
const searches = [];
for (let i = 0; i < 3; i++) { const r = await fetch(`${base}/search`); await r.text(); searches.push(r); }
const missing = await fetch(`${base}/nope`);

server.closeAllConnections();
server.close();

assert.deepEqual([first.status, again.status, created.status], [200, 304, 201]);
assert.equal(created.headers.get("location"), "/orders/43");
assert.deepEqual(searches.map((r) => r.status), [200, 200, 429]);
assert.equal(searches[2].headers.get("retry-after"), "10");
assert.equal(missing.status, 404);
console.log(`200 → 304 (ETag ${etag}) · 201 ${created.headers.get("location")} · search 200 200 429 (Retry-After: 10) · 404`);
Run: node server.ts (Node 23.6+ · on Node 22 add --experimental-strip-types)It printed: 200 → 304 (ETag "v3") · 201 /orders/43 · search 200 200 429 (Retry-After: 10) · 404

A small server and a client in one file. It runs on 127.0.0.1 on a port the OS picks, then makes real requests: 200 → 304 with an ETag, 201 with Location, 429 with Retry-After, and 404. Go uses net/http's "GET /path" patterns (Go 1.22+). Python: urllib treats anything that isn't 2xx as an error, 304 included.

Common questions

What happens when I type a URL and press Enter?

The browser asks DNS for the name's IP, opens a TCP connection, sets up TLS for HTTPS, then sends the request and reads the status, headers and body that come back. Keep-alive lets the next request skip the first three.

HTTP remembers nothing. So how does a site know I'm logged in?

Because who you are travels with every request, in a header such as a cookie or Authorization. The server reads it there each time; it doesn't remember you from the last request.

Read: HTTP is text

What's the difference between 401 and 403?

401 means we don't know who you are: no token, or it expired, so logging in fixes it. 403 means we know exactly who you are, and the answer is no. Logging in again still gets a 403.

4xx or 5xx: whose fault is it?

4xx: the client got it wrong, so fix the request before sending it again; the same request gets the same answer. 5xx: the server broke and the request was fine, so trying again later may work.

What does idempotent mean, and why care?

Sending the same request twice ends the same as sending it once. GET, PUT and DELETE are; POST isn't, so a second send may create a second order. That's why only some methods are safe to retry on their own.

Table: methods

PUT or PATCH: when do I use which?

PUT sends the whole thing to replace what's there, so sending it twice ends the same. PATCH changes part of it, and whether that's idempotent depends on how you write it: "set to 5" is, "add 1" isn't.

Table: methods

How does a 304 make things faster?

The first response carries an ETag. Next time the browser asks with If-None-Match, and if the version still matches the server answers a short 304 without the body. Cache-Control says how long the copy can be used without asking at all.

Read: caching with ETag

What changed between HTTP/1.1, HTTP/2 and HTTP/3?

The messages are the same; how they travel changes. HTTP/2 sends many requests at once over one connection, but TCP delivers in order, so one lost packet holds up everything. HTTP/3 runs on QUIC (UDP), where each stream waits only for its own data.

Read: the three versions

Next lesson

DNSLevel: Basic

Finding the IP was one step here; next, follow that lookup from your browser to the root and back, and see how TTLs keep it fast.