HTTP is the language of the web and of most APIs: a client sends a request with a method, a path and headers, and the server answers with a status code, headers and a body. Its semantics have stayed stable for decades while the wire format evolved from text over TCP (HTTP/1.1) to binary multiplexed streams (HTTP/2) to QUIC over UDP (HTTP/3). TLS wraps it all in encryption and proves you are talking to the real server, which is what the S in HTTPS means.
Think of it like
Ordering at a counter through a sealed tube
HTTP is the order form: a verb (GET, POST), what you want (the path), notes for the kitchen (headers) and sometimes an attachment (the body). The reply comes back stamped with a code: 200 means here it is, 404 means we don't have that, 503 means the kitchen is overwhelmed. TLS is the sealed, tamper-evident tube the forms travel through, and the certificate is the health inspector's license on the wall proving this really is the restaurant you meant to visit.
Anatomy of an HTTP message
Every HTTP message has the same four parts: a start line, headers, a blank line, and an optional body. HTTP/2 and HTTP/3 encode these as binary frames, but the meaning is identical, so it pays to know the readable HTTP/1.1 form.
POST /api/v1/orders HTTP/1.1 <- method, target, version
Host: shop.example.com <- headers (one per line)
Content-Type: application/json
Authorization: Bearer eyJhbGciOi...
Idempotency-Key: 7c1d4a3e-0b6f-4c2a-9f7e-1f2d3c4b5a69
Content-Length: 41
<- blank line ends the headers
{"productId": 42, "quantity": 2} <- body
HTTP/1.1 201 Created <- version, status code, reason
Content-Type: application/json
Location: /api/v1/orders/9001
Cache-Control: no-store
{"id": 9001, "status": "pending"}- Method
- The action:
GET,POST,PUT,PATCH,DELETE,HEAD,OPTIONS. - Request target
- The path and query, such as
/api/v1/orders?status=open. The host travels in theHostheader (:authorityin HTTP/2 and HTTP/3). - Headers
- Case-insensitive
Name: valuemetadata: content type, caching rules, credentials, cookies. - Body
- Optional payload: JSON, HTML, an image, a file upload. Its length is given by
Content-Lengthor chunked transfer encoding.
Methods: safety and idempotency
Two properties matter more than any other. A safe method does not change server state, so crawlers and prefetchers may call it freely. An idempotent method has the same effect whether you send it once or ten times, so clients and proxies can retry it safely after a timeout.
| Method | Purpose | Safe | Idempotent | Request body | Cacheable |
|---|---|---|---|---|---|
GET | Read a resource | Yes | Yes | No (undefined semantics) | Yes |
HEAD | Like GET, headers only | Yes | Yes | No | Yes |
OPTIONS | Ask what is allowed (CORS preflight) | Yes | Yes | Rarely | No |
POST | Create a resource or run an action | No | No | Yes | Rarely |
PUT | Replace a resource entirely | No | Yes | Yes | No |
PATCH | Partially modify a resource | No | Not by default | Yes | No |
DELETE | Remove a resource | No | Yes | Rarely | No |
PUT /users/7 {name: "Ada"} twice leaves the same state. POST /orders twice creates two orders. PATCH {op: "increment"} twice increments twice.Status codes
| Class | Meaning | Who should act |
|---|---|---|
1xx | Informational: keep going | Protocol machinery (rarely seen by apps) |
2xx | Success | Nobody: it worked |
3xx | Redirection: look elsewhere or use your cache | The client follows Location or uses its cached copy |
4xx | Client error: the request is wrong | The caller must fix the request; retrying unchanged will not help (except 408/429) |
5xx | Server error: the server failed | The server owner; clients may retry idempotent requests with backoff |
| Code | Name | When to use it |
|---|---|---|
101 | Switching Protocols | Upgrading to WebSocket (see Real-time Communication) |
200 | OK | Generic success with a body |
201 | Created | A POST created a resource; include a Location header |
202 | Accepted | Work queued for asynchronous processing |
204 | No Content | Success with no body (common for DELETE) |
206 | Partial Content | Range request: resumable downloads, video seeking |
301 / 308 | Moved Permanently / Permanent Redirect | URL changed for good; browsers cache it. 308 forbids changing the method |
302 / 307 | Found / Temporary Redirect | Temporary move. 307 forbids changing POST to GET |
304 | Not Modified | Conditional request: your cached copy is still valid, no body sent |
400 | Bad Request | Malformed syntax or invalid parameters |
401 | Unauthorized | Missing or invalid credentials (really "unauthenticated") |
403 | Forbidden | Authenticated, but not allowed to do this |
404 | Not Found | No such resource (also used to hide existence from unauthorized callers) |
409 | Conflict | State conflict: duplicate username, version mismatch |
422 | Unprocessable Content | Well-formed but semantically invalid (validation errors) |
429 | Too Many Requests | Rate limited; send Retry-After. See Rate Limiting |
500 | Internal Server Error | Unhandled bug or failure |
502 | Bad Gateway | A proxy got an invalid response from the upstream server |
503 | Service Unavailable | Overloaded or in maintenance; temporary, may include Retry-After |
504 | Gateway Timeout | A proxy timed out waiting for the upstream server |
Headers that matter in system design
Caching: Cache-Control and ETag
| Directive | Effect |
|---|---|
max-age=N | Fresh for N seconds; reuse without asking the server |
s-maxage=N | Overrides max-age for shared caches (CDNs, proxies) only |
public / private | May shared caches store it, or only the user's browser? |
no-cache | May be stored, but must be revalidated before every use |
no-store | Never store anywhere (sensitive data) |
immutable | Will never change; skip revalidation (fingerprinted assets like app.3f9a1c.js) |
stale-while-revalidate=N | Serve a stale copy for up to N seconds while refreshing in the background |
When a cached copy goes stale, the client does not have to download it again. It sends a conditional request with the validator it saved: If-None-Match: "v7" (from the ETag) or If-Modified-Since (from Last-Modified). If nothing changed, the server answers 304 Not Modified with no body. See Caching and Content Delivery Networks.
Content negotiation
Content-Type: application/json; charset=utf-8describes the body being sent;Accept: application/jsonsays what the client wants back.Accept-Encoding: gzip, br/Content-Encoding: brnegotiate compression. Brotli typically beats gzip on text by 15 to 20%.Vary: Accept-Encodingtells caches that the response differs by that request header, so they must key on it.
Cookies
Set-Cookie: session=8f3a91c2; Path=/; Max-Age=86400; HttpOnly; Secure; SameSite=Lax| Attribute | Protects against |
|---|---|
HttpOnly | JavaScript cannot read it, limiting theft through XSS |
Secure | Only sent over HTTPS, never in plaintext |
SameSite=Lax or Strict | Not sent on cross-site subrequests and form posts, blunting CSRF |
Max-Age / Expires | Bounds how long a stolen cookie is useful |
Domain / Path | Limits which hosts and paths receive it |
CORS
Browsers enforce the same-origin policy: a page from https://app.example.com cannot read responses from https://api.other.com unless that server opts in with Cross-Origin Resource Sharing headers. For non-simple requests (custom headers, JSON bodies, PUT/DELETE), the browser first sends an OPTIONS preflight.
OPTIONS /v1/orders HTTP/1.1
Origin: https://app.example.com
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type, authorization
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Methods: GET, POST, DELETE
Access-Control-Allow-Headers: content-type, authorization
Access-Control-Allow-Credentials: true
Access-Control-Max-Age: 600HTTP/1.1: keep-alive and head-of-line blocking
HTTP/1.1 made connections persistent by default, so many requests can reuse one TCP+TLS connection. But each connection still carries one request at a time: the next request waits until the current response finishes. That is head-of-line (HOL) blocking. Pipelining (sending several requests without waiting) was specified but responses still had to return in order, and it was never reliably deployed.
- Browsers work around it by opening about 6 connections per origin, each paying its own handshakes and slow start.
- Old performance hacks followed: domain sharding (more origins, more connections), sprite sheets and bundling (fewer requests).
- Text headers are re-sent in full on every request; cookies alone can add kilobytes.
HTTP/2: one connection, many streams
HTTP/2 keeps the same methods, status codes and headers but changes the wire format to binary frames. Each request/response pair is a stream with an ID, and frames from many streams are interleaved on a single TCP connection. A slow response no longer blocks the others at the HTTP layer. Compare the waterfalls in the simulation above.
- Multiplexing
- Many concurrent streams over one connection; the 6-connection limit and domain sharding become unnecessary (even counterproductive).
- Streams and frames
HEADERSandDATAframes tagged with a stream ID. Odd IDs are client-initiated. Streams can be canceled individually withRST_STREAM.- HPACK
- Header compression using a 61-entry static table of common headers, a dynamic table of recently sent ones, and Huffman coding. Repeated headers shrink to a byte or two.
- Flow control and priority
- Per-stream and per-connection windows; clients can hint which resources matter most.
- Server push
- Let the server send resources before they were requested. Rarely helped in practice, and major browsers have removed support.
HTTP/3: QUIC over UDP
HTTP/3 replaces TCP with QUIC, a transport built on UDP that implements reliability, congestion control and streams in user space, with TLS 1.3 built in. Browsers usually discover it from an Alt-Svc header or an HTTPS DNS record, then switch over.
- No transport HOL blocking: each QUIC stream is independently ordered, so a lost packet only stalls the streams whose data it carried.
- Faster setup: transport and TLS handshakes are combined into 1 RTT; resumed connections can send requests in the first flight (0-RTT).
- Connection migration: connections are identified by connection IDs, not the IP/port 4-tuple, so a phone moving from Wi-Fi to cellular keeps its connection.
- QPACK replaces HPACK, because HPACK assumed in-order delivery.
- Trade-offs: some networks block or throttle UDP (browsers fall back to HTTP/2), and user-space QUIC costs more CPU than kernel TCP.
| HTTP/1.1 | HTTP/2 | HTTP/3 | |
|---|---|---|---|
| Transport | TCP | TCP | QUIC over UDP |
| Format | Text | Binary frames | Binary frames |
| Concurrency per connection | 1 request at a time | Many multiplexed streams | Many independent streams |
| HOL blocking | HTTP and TCP level | TCP level only | None at transport level |
| Header compression | None | HPACK | QPACK |
| Encryption | Optional (TLS) | TLS in practice (ALPN h2) | Always (TLS 1.3 built in) |
| New connection setup | TCP + TLS: 2 RTT (TLS 1.3) | TCP + TLS: 2 RTT | 1 RTT, 0-RTT on resumption |
| Survives network change | No | No | Yes (connection IDs) |
HTTPS and TLS
TLS gives HTTP three guarantees: confidentiality (eavesdroppers see only ciphertext), integrity (tampering is detected) and authentication (a certificate proves the server owns the domain). Asymmetric cryptography is used only during the handshake to agree on keys; the bulk data is then encrypted with fast symmetric ciphers such as AES-GCM or ChaCha20-Poly1305.
The TLS 1.3 handshake
- 1
ClientHello
The client sends supported cipher suites, a random value, its key share (an ephemeral Diffie-Hellman public key, guessing the group the server will pick), the server name (SNI) and the protocols it speaks (ALPN:
h2,http/1.1). - 2
ServerHello and key derivation
The server picks a cipher suite and replies with its own key share. Both sides can now compute the same shared secret; everything after this point is encrypted.
- 3
Certificate, CertificateVerify, Finished
In the same flight, the server sends its certificate chain, a signature over the handshake made with its private key (proving it owns the certificate), and a MAC over the whole transcript.
- 4
Client verifies and finishes
The client validates the chain and hostname, checks the signature, and sends its own
Finished. It can send the HTTP request in the same flight: one round trip in total. - 5
Resumption and 0-RTT
On reconnect, a pre-shared key from a previous session lets the client send early data with the ClientHello. Early data can be replayed by an attacker, so servers should accept it only for idempotent requests like
GET.
Certificates and the chain of trust
- A certificate binds a public key to names (the Subject Alternative Names, like
shop.example.comor*.example.com) and carries a validity period, the issuer, and the issuer's signature. - Chain of trust: the leaf certificate is signed by an intermediate CA, which is signed by a root CA whose certificate ships pre-installed in the OS or browser trust store. The server sends the leaf and intermediates; roots are never sent.
- Validation: every signature in the chain checks out, the hostname matches a SAN, the dates are valid and the certificate is not revoked.
- Certificate Transparency: CAs must publish every certificate they issue to public append-only logs, so mis-issued certificates for your domain can be spotted.
HSTS
Redirecting HTTP to HTTPS leaves a gap: the very first plaintext request can be intercepted and "stripped" so the victim never reaches HTTPS. HTTP Strict Transport Security closes it for every later visit. To protect even the first visit, domains can be added to the browsers' built-in HSTS preload list (add the preload directive and submit the domain).
Try it
# Response headers only, forcing HTTP/2 (use --http3 if your curl supports it)
curl -sI --http2 https://example.com/
# Conditional request: replay the ETag and expect 304 Not Modified
curl -s -o /dev/null -w '%{http_code}\n' -H 'If-None-Match: "abc123"' https://example.com/
# Show the certificate chain and negotiated TLS version
openssl s_client -connect example.com:443 -servername example.com -brief </dev/nullImplementation
The server tags each representation with a hash. If the client already holds that version, it answers 304 with no body.
import hashlib
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
PRODUCT = {"id": 42, "name": "Desk lamp", "priceCents": 3999}
class Handler(BaseHTTPRequestHandler):
def do_GET(self) -> None:
if self.path != "/products/42":
self.send_error(404)
return
body = json.dumps(PRODUCT).encode()
etag = '"' + hashlib.sha1(body).hexdigest() + '"'
# Simplified: real clients may send a list of ETags or "*"
if self.headers.get("If-None-Match") == etag:
self.send_response(304) # no body: the client's copy is still valid
self.send_header("ETag", etag)
self.send_header("Cache-Control", "public, max-age=60")
self.end_headers()
return
self.send_response(200)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.send_header("Cache-Control", "public, max-age=60")
self.send_header("ETag", etag)
self.end_headers()
self.wfile.write(body)
HTTPServer(("127.0.0.1", 8080), Handler).serve_forever()Key takeaways
- HTTP messages are a start line, headers, a blank line and an optional body; HTTP/2 and HTTP/3 change the encoding, not the meaning.
- Safe methods do not change state; idempotent ones (GET, PUT, DELETE) can be retried. POST and PATCH need idempotency keys to be retried safely.
- Status classes tell you who must act: 4xx means fix the request, 5xx means the server failed and idempotent requests may be retried.
- Cache-Control plus ETag-based conditional requests turn repeat downloads into tiny 304s.
- HTTP/2 multiplexes streams over one TCP connection but still suffers TCP head-of-line blocking; HTTP/3 over QUIC removes it and handshakes in 1 RTT.
- TLS 1.3 authenticates the server with a certificate chain and agrees on ephemeral keys in one round trip; HSTS keeps browsers from ever downgrading to HTTP.
Common pitfalls
- Using
GETfor actions that change state; crawlers, prefetchers and retries will trigger them. - Blindly retrying
POSTafter a timeout and creating duplicate orders or payments. - Returning
200with an error in the body, which breaks caches, monitoring and client retry logic. - Treating CORS as an access-control mechanism, or using
Access-Control-Allow-Origin: *on authenticated APIs. - Forgetting that 0-RTT early data can be replayed, and accepting non-idempotent requests in it.
Interview tips
- When designing an API, state the method, status codes and idempotency of each endpoint; it shows you have thought about retries.
- Explain HOL blocking at both layers: HTTP/1.1 per connection, HTTP/2 at the TCP level, and how QUIC solves it.
- Know the TLS 1.3 handshake at a high level: key shares in the hellos, certificate plus signature, Finished, 1 RTT total.
Real-world applications
- Every REST API, web page and CDN interaction.
- Setting cache headers so CDNs and browsers absorb most traffic.
- Enabling HTTP/2 and HTTP/3 at the edge to cut mobile latency.
- Automating certificate issuance and renewal with ACME.
Test yourself
Which HTTP method is idempotent but NOT safe?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.