Chapters

HTTP & its versions

Chapter 1 showed one HTTP request as text. This chapter covers the whole protocol: what requests and responses contain, how status codes and headers work, how a stateless protocol remembers who you are, and how HTTP/1.1, HTTP/2 and HTTP/3 carry the same messages in faster ways.

Application protocols · chapter 24 of 34 · 9 min read

Part AThe protocol

Request and response, no memory

HTTP (HyperText Transfer Protocol) is a request/response protocol: the client sends a request, the server returns one response. It is stateless: each request stands alone, and the server does not remember the previous one. That is why cookies and tokens exist, to carry "who you are" on every request (section 6).

Anatomy of a URL

https://api.kade.lk:443/orders/1042?include=items#summary
schemehost (DNS, ch 22)portpathquery stringfragment
The port is usually left out: https means 443, http means 80. The fragment (#summary) is never sent to the server; only the browser uses it.

What a request and a response contain

Both have the same shape: a start line, headers, a blank line, and an optional body. Here is the Kadé app placing an order:

Request

POST /orders HTTP/1.1
Host: api.kade.lk
Authorization: Bearer eyJhbGci…
Content-Type: application/json
Content-Length: 58

{"items":[{"sku":"RICE-5KG","qty":2}],"slot":"evening"}

Request line: method + path + version. Then headers, a blank line, the body.

Response

HTTP/1.1 201 Created
Content-Type: application/json
Location: /orders/1042
Cache-Control: no-store
Content-Length: 41

{"id":1042,"status":"confirmed","total":…}

Status line: version + status code + reason. Then headers, a blank line, the body.

The body's size is given by Content-Length. When the server does not know the size in advance (streaming a CSV export, chapter 19), it uses Transfer-Encoding: chunked in HTTP/1.1 and sends the body in pieces, each with its own length.

Methods

The method states the request's intent. Two properties decide what is safe to retry automatically, which matters a lot when connections drop (chapter 21):

#MethodIntentKadé exampleSafe?Idempotent?
1GETRead somethingGET /orders/1042yesyes
2POSTCreate, or run an actionPOST /ordersnono
3PUTReplace a resource entirelyPUT /users/me/addressnoyes
4PATCHChange part of a resourcePATCH /orders/1042 {"slot":"morning"}nonot guaranteed
5DELETERemoveDELETE /cart/items/9noyes
6HEADLike GET, headers onlychecking a file's sizeyesyes
7OPTIONSAsk what is allowedthe browser's CORS "preflight" before a cross-site callyesyes
Safe = changes nothing on the server. Idempotent = doing it twice has the same effect as once. If a POST /orders times out, retrying it might create two orders. That is why payment APIs like PayGate accept an idempotency key header: the same key twice means "same request", and the server does not repeat it.

Status codes

The first digit gives the family. Learn the families, and API debugging gets much faster:

CodeMeaningWhen kade-api (or something in front of it) sends it
2xx · success
200OKGET /orders/1042 worked
201CreatedPOST /orders created order 1042 (with a Location header)
204No ContentDELETE /cart/items/9 worked, nothing to return
3xx · go somewhere else
301 / 308Moved permanentlyhttp://kade.lk → https://kade.lk (308 keeps the method)
302 / 307Moved temporarilyAfter login, back to the page you came from
304Not Modified"Your cached copy is still good" (section 7)
4xx · the client got something wrong
400Bad RequestBroken JSON
401UnauthorizedNo token, or an expired one: "who are you?"
403ForbiddenValid token, but a shopper calling an admin endpoint: "I know you; not allowed"
404Not FoundGET /orders/99999
409ConflictOrder already paid
422UnprocessableJSON is valid, but qty is −3
429Too Many RequestsRate limit hit (remember the whole office shares one IP, chapter 10)
5xx · the server side broke
500Internal Server ErrorAn unhandled exception in kade-api
502Bad GatewayThe load balancer got a bad or no reply from kade-api (the keep-alive race in chapter 21)
503Service Unavailablekade-api is down or overloaded; often with Retry-After
504Gateway TimeoutThe load balancer waited too long for kade-api
502, 503 and 504 usually come from a proxy or load balancer in front of your app, not from your code. Check which box wrote the response.

Headers, and remembering who you are

Headers carry metadata. The ones you meet daily:

HostWhich site. One IP can serve many sites (virtual hosting); the Host header picks one. Required in HTTP/1.1.
Content-Type / AcceptWhat the body is / what the client wants back (application/json, text/html …)
AuthorizationCredentials, usually Bearer <token>
Cookie / Set-CookieThe server sets a cookie; the browser sends it back on every later request
Cache-Control, ETagHow long a response may be reused (section 7)
Content-EncodingCompression: gzip or br (Brotli). JSON often shrinks to a fifth.
LocationWhere to go (redirects), or where a new resource is (201)
Access-Control-Allow-OriginCORS: which other websites may call this API from a browser

Because HTTP is stateless, identity travels with every request, in one of two ways:

Cookies

Set-Cookie: sid=8f2a91c; HttpOnly; Secure; SameSite=Lax; Max-Age=86400

The browser stores it and sends Cookie: sid=8f2a91c automatically. HttpOnly: JavaScript cannot read it. Secure: HTTPS only. SameSite: not sent on most cross-site requests (blocks CSRF).

Tokens

Authorization: Bearer eyJhbGciOi…

The app stores the token and adds the header itself. Common for mobile apps and APIs. Often a JWT: signed data the server can check without a database lookup.

Caching in one minute

Cache-Control: max-age=86400 on a product image lets the browser (and any CDN) reuse it for a day without asking. When it expires, the browser asks again with If-None-Match: "a1b2" (the ETag it got before). If nothing changed, kade-api answers 304 Not Modified with no body. Cache-Control: no-store on order details means "never keep this". Caching skips whole requests, which beats any protocol speed-up.

Part BThe versions

Same meaning, better delivery

Every version keeps the same methods, status codes and headers. Only the way messages are carried changes:

#VersionYearCarried asConnectionsTransport
1HTTP/1.01996texta new TCP connection for every requestTCP
2HTTP/1.11997textreused (keep-alive); one request at a time eachTCP
3HTTP/22015binary framesone connection, many streams at onceTCP (+ TLS)
4HTTP/32022binary framesone connection, fully independent streamsQUIC over UDP (TLS 1.3 built in)

HTTP/1.1: keep-alive and head-of-line blocking

HTTP/1.1 kept connections open so they could be reused (keep-alive, chapter 21), saving a handshake per request. But on one connection, requests are answered one at a time, in order: a slow response blocks everything behind it. This is head-of-line blocking at the HTTP level.

Browsers worked around it by opening up to 6 connections per host, each paying its own TCP and TLS handshake and slow start (chapter 20). Sites even split assets across several host names to get more connections ("domain sharding"). An idea to send several requests without waiting (pipelining) existed, but was too buggy and is not used.

HTTP/2: many streams on one connection

HTTP/2 introduced multiplexing: many requests and responses share one connection as independent streams, cut into small binary frames and interleaved. Nothing waits in line at the HTTP level.

one TCP connection, frames from three streams interleaved

HEADERS s1HEADERS s3DATA s1HEADERS s5DATA s3DATA s5DATA s1DATA s3 end
s1 = the page's CSS, s3 = a script, s5 = a product image. Each frame carries its stream number, so the receiver sorts them back out.
  • Binary, not text: faster and less error-prone to parse.
  • Header compression (HPACK): headers repeat on every request (cookies, user agent). HPACK sends them once and then refers to them by number.
  • Per-stream flow control and priorities: the same idea as chapter 19, per stream.
  • Server push (sending files before they are asked for) was part of HTTP/2 but proved unhelpful, and browsers have removed it.

The problem HTTP/2 could not fix

HTTP/2 still runs on TCP, and TCP delivers one ordered byte stream (chapter 17). If a single packet is lost, TCP holds back everything behind it until the resend arrives, including frames of streams that had nothing to do with the lost packet. HTTP/2 removed head-of-line blocking at the HTTP level but not at the TCP level. On lossy mobile networks, it can even do worse than HTTP/1.1's six connections, where one loss stalls only one of them.

HTTP/3 on QUIC

HTTP/3 runs on QUIC, a transport built on UDP (chapter 14) that does TCP's job itself, differently:

#FeatureWhat it gives
1Independent streamsEach stream has its own ordering. A lost packet delays only the stream it belonged to.
2TLS 1.3 built inTransport and encryption handshakes are one: a new connection is ready in 1 round trip instead of 2 (chapter 25). A returning client can even send data in the first flight ("0-RTT").
3Connection IDsA connection is identified by an ID, not by the four addresses and ports. When the delivery rider's phone moves from WiFi to mobile data (new IP), the connection keeps going instead of breaking.
4Encrypted transport headersEven packet numbers are encrypted, so middleboxes cannot interfere with it the way they sometimes do with TCP.
5QPACKHeader compression that works with out-of-order streams
Browsers learn a server speaks HTTP/3 from an Alt-Svc header on an earlier response, or from a DNS HTTPS record. They race QUIC against TCP and fall back to HTTP/2 if UDP 443 is blocked, as it is on some office networks.

Watch it: loading the Kadé home page

The home page needs its HTML, then 18 more files (CSS, scripts, a font, product images). Compare how each version loads them from home (41 ms round trip), then lose one packet:

index.html · c1
app.css · c1
theme.css · c1
app.js · c2
cart.js · c3
analytics.js · c4
font.woff2 · c5
rice.jpg · c6
dhal.jpg · c1
milk.jpg · c4
eggs.jpg · c5
bread.jpg · c3
tea.jpg · c6
sugar.jpg · c2
oil.jpg · c1
soap.jpg · c4
salt.jpg · c5
logo.svg · c3
banner.jpg · c6
050100150200250300350400 ms
  • connection setup (TCP + TLS)
  • waiting for the first byte (1 RTT)
  • downloading (c1-c6 = connection)
  • ✕ lost packet · hatched = stalled
Page fully loadedno lossone packet lost
HTTP/1.1370 ms376 ms
HTTP/2200 ms241 ms
HTTP/3159 ms188 ms

A simple model: 41 ms round trip, and a line fast enough that waiting, not bandwidth, is the limit. HTTP/1.1 opens 5 more connections once the HTML arrives, each paying 2 round trips of setup, then fetches one file at a time per connection. HTTP/2 and HTTP/3 ask for everything at once on one connection. With a loss, HTTP/2’s whole connection stalls for a round trip; HTTP/3 delays only milk.jpg; HTTP/1.1 delays only connection 4.

Versions are per connection

Each connection picks its own version, agreed during the TLS handshake (a field called ALPN, chapter 25). So one request can use several versions along the way:

  1. Shopper's browser
  2. Google load balancerHTTP/3 or HTTP/2
  3. kade-apiHTTP/1.1 or HTTP/2 inside GCP
The slow, lossy part (the shopper's mobile network) gets the newest protocol. Inside Google's network, round trips are tiny, so the backend version matters much less.

Summary

#IdeaIn one lineNew terms
1HTTPRequest/response, statelessstateless
2-3MessagesURL parts; start line, headers, blank line, bodyContent-Length, chunked
4MethodsGET, POST, PUT, PATCH, DELETE; safe and idempotent decide retriesidempotency key
5Status2xx ok, 3xx elsewhere, 4xx client, 5xx server (often a proxy)
6-7HeadersHost, auth, cookies with flags, tokens, caching with ETag/304virtual hosting, HttpOnly, SameSite, ETag
9HTTP/1.1Keep-alive, one request at a time, 6 connectionshead-of-line blocking
10-11HTTP/2Binary streams multiplexed on one TCP connection; TCP still blocks on lossmultiplexing, frame, HPACK
12HTTP/3QUIC on UDP: independent streams, 1-RTT setup, connection migrationQUIC, 0-RTT, Alt-Svc
14Per hopEach connection negotiates its own versionALPN

Try it yourself

The full request and response

curl -v https://example.com

Headers only (HEAD)

curl -I https://www.google.com

Which version was used

curl -s -o /dev/null -w '%{http_version}\n' https://www.google.com

An HTTP/3 request

  • What to look for: HTTP/3 200.
  • Runs on: needs a curl built with HTTP/3
  • From section: 12. HTTP/3 on QUIC
curl --http3 -I https://www.google.com

The version per request

  • Steps: Chrome DevTools → Network → right-click the columns → Protocol
  • What to look for: h3, h2, http/1.1 side by side; the Waterfall column shows waiting vs downloading.
  • From section: 13. Watch it: loading the Kadé home page

A conditional request

curl -I -H 'If-None-Match: "etag-value"' URL

Spotted a mistake, or something unclear? Suggest an edit on GitHub