Summary#
HTTP is a request/response protocol: a client sends a method (GET, POST...), a path and headers; the server returns a status code, headers and a body. Methods have rules: safe methods do not change data, idempotent ones can be repeated safely. Headers drive caching (Cache-Control, ETag), content type and auth. HTTP/2 multiplexes many requests over one TCP connection; HTTP/3 runs over QUIC to remove head-of-line blocking. HTTPS is HTTP inside TLS, usually terminated at a load balancer or CDN.
Why It Exists#
HTTP is the language of the web and of most APIs. Browsers, mobile apps, microservices, CDNs, load balancers and caches all understand it, which is why almost every design ends with "the client calls an HTTP endpoint". Knowing its semantics lets you design APIs that cache well, retry safely and fail clearly. Knowing its versions and TLS lets you explain latency: how many round trips before the first byte. This page builds on TCP vs UDP.
How It Works#
The request/response model#
GET /api/orders/42 HTTP/1.1
Host: shop.example.com
Authorization: Bearer eyJhbGciOi...
Accept: application/json
If-None-Match: "v7"
HTTP/1.1 304 Not Modified
ETag: "v7"
Cache-Control: private, max-age=60Each request is independent: HTTP is stateless. Anything the server needs to remember between requests (who you are, your cart) travels in headers such as cookies or tokens, or lives in a server-side store keyed by them.
Inside a message, in more depth#
An HTTP/1.1 message is plain text you could type by hand. The first line names the method, the path and the version. Header lines follow, then a blank line, then an optional body. You can try it: open a TCP connection with a tool such as nc example.com 80, type GET / HTTP/1.1, then Host: example.com, then an empty line, and the server answers. HTTP/2 and HTTP/3 carry exactly the same meaning (method, path, headers, body), only encoded as binary frames. So everything on this page about methods, status codes and headers applies to all three versions.
A few parts of the message do more work than they appear to:
Host. One IP address often serves thousands of sites. TheHostheader (and the TLS SNI field, covered below) tells the server which site you want. This virtual hosting is what lets a CDN or load balancer front many domains on shared addresses.- Framing. The receiver has to know where the body ends. Either
Content-Lengthsays how many bytes follow, orTransfer-Encoding: chunkedsends the body as a series of sized pieces, ending with a zero-length chunk. Chunked encoding lets a server start streaming a response before it knows the total size, as with a large export or a server-rendered page sent in pieces. - Where inputs go. Required identifiers belong in the path (
/events/123). Optional filters, sorting and pagination belong in the query string (?city=NYC&limit=20). Large or sensitive data belongs in the body. URLs are logged by proxies, saved in browser history and sent inRefererheaders, so secrets must never be in them. Many servers and proxies also cap URL length at around 8 KB.
Why statelessness is so valuable. Because each request carries everything needed to handle it, any server behind a load balancer can answer any request. A server can be added, removed or restarted without users noticing. Most simple HTTP handlers are just a function from the request (plus the data in the database) to a response. In system design you want as little of the system as possible to hold state between requests, and HTTP pushes you in that direction. When state is needed (a login, a shopping cart), it lives in a shared store such as a database or Redis, keyed by a token the client sends back each time.
Self-contained messages make intermediaries possible. Because a request and its response fully describe themselves, other machines can sit in the middle and add value without understanding the application. Many layers can each read and act on the same headers:
Each layer uses standard fields: caches read Cache-Control and ETag, load balancers read Host and the path, gateways read Authorization, and compression proxies read Accept-Encoding. Designing your API with correct HTTP semantics is what lets all of this infrastructure help you for free.
Methods, safety and idempotency#
- A safe method only reads; it must not change server state. Caches and crawlers may call it freely.
- An idempotent method has the same effect whether it is called once or many times. Clients and proxies can retry it after a timeout. See Idempotency.
| Method | Use | Safe | Idempotent |
|---|---|---|---|
| GET | Read a resource | Yes | Yes |
| HEAD | Read headers only | Yes | Yes |
| POST | Create, or trigger an action | No | No (make it so with an idempotency key) |
| PUT | Replace a resource at a known URL | No | Yes |
| PATCH | Partially update a resource | No | Not guaranteed |
| DELETE | Remove a resource | No | Yes |
| OPTIONS | Ask what is allowed (CORS preflight) | Yes | Yes |
Safety and idempotency in more depth#
Idempotency is about effect, not response. Deleting order 42 twice leaves the same state as deleting it once, so DELETE is idempotent, even though the first call returns 204 and the second returns 404. Likewise, PUT with the full new state of a resource is idempotent: sending it ten times leaves one resource in that state.
PATCH depends on what it says. PATCH {"status": "shipped"} sets a value and is idempotent in practice. PATCH {"op": "increment", "field": "stock", "by": 1} is not: each retry adds one more. If you design PATCH operations, prefer "set to" over "change by", or protect them with a version check.
Why it matters: retries happen without asking you. Browsers may retry a GET after a dropped connection. HTTP client libraries often retry idempotent requests on connection errors automatically. Load balancers and service meshes can be configured to retry on 502 or 503. A timeout tells the client nothing about whether the server acted, so the only safe response to a timeout is a retry, and the only safe retry is an idempotent one.
A worked failure: a user books a seat with POST /bookings. The server reserves the seat and charges the card, but the response is lost when a mobile network drops. The app retries, and the user is charged twice. Three standard fixes, each making the retry harmless:
- Idempotency key. The client generates a unique key per user action and sends it as a header such as
Idempotency-Key: 7f3c.... The server stores the key with the result, and a repeat returns the stored result instead of acting again. Stripe's API is the well-known example. See Idempotency. - Client-chosen ID with PUT. The client creates the booking ID itself and calls
PUT /bookings/7f3c.... A second PUT to the same URL just overwrites the same booking. - Natural uniqueness. A database constraint, such as one booking per seat per event, makes the duplicate fail instead of succeed.
Safe methods must really be safe. Crawlers, link prefetchers, browser previews and security scanners follow GET links freely. A "delete" or "unsubscribe" action behind a plain GET link will eventually be triggered by something that is not a human. State changes belong behind POST, PUT, PATCH or DELETE, ideally with a confirmation step for destructive ones.
Cacheability follows from the method. GET and HEAD responses are cacheable by default when headers allow it. In theory a POST response can be cached if it carries explicit freshness information, but almost no cache does so in practice, so treat POST as uncacheable. This is one more reason to make reads GETs: they get caching, retries and prefetching for free.
Status codes#
| Range | Meaning | Common codes |
|---|---|---|
| 1xx | Informational | 101 Switching Protocols (WebSocket upgrade) |
| 2xx | Success | 200 OK, 201 Created, 202 Accepted (async), 204 No Content |
| 3xx | Redirect or cached | 301/308 permanent, 302/307 temporary, 304 Not Modified |
| 4xx | Client error, do not retry as is | 400 Bad Request, 401 Unauthenticated, 403 Forbidden, 404 Not Found, 409 Conflict, 429 Too Many Requests |
| 5xx | Server error, may retry | 500 Internal Error, 502 Bad Gateway, 503 Unavailable, 504 Gateway Timeout |
The split matters for clients: 4xx means "fix the request", 5xx and 429 mean "retry later with backoff".
Choosing status codes in more depth#
Status codes are a contract with every client, monitor and proxy, not decoration. The right code lets each of them react correctly without parsing your error text.
| Situation | Code | Why this one |
|---|---|---|
| Created a resource | 201 Created, with Location and the new resource | Clients learn the new URL directly |
| Accepted work that finishes later | 202 Accepted, with a status URL to poll | Honest about async processing (video transcoding, exports) |
| Malformed JSON or missing field | 400 Bad Request | The client must change the request |
| Well-formed but invalid (end date before start date) | 422 Unprocessable Content, or 400 | Some APIs separate syntax errors from validation errors |
| No credentials, or expired token | 401 Unauthorized | The client should log in or refresh its token |
| Valid user without permission | 403 Forbidden, or 404 to hide that the resource exists | 404 avoids leaking that a private resource exists |
| Version conflict or duplicate | 409 Conflict | The client should re-read and decide |
If-Match version no longer current | 412 Precondition Failed | Optimistic concurrency check failed |
| Rate limit hit | 429 Too Many Requests, with Retry-After | Tells the client to slow down, not to give up |
| Bug or unexpected failure | 500 Internal Server Error | Not the client's fault |
| A proxy got a bad answer from the next hop | 502 Bad Gateway | Points at the upstream, not the proxy |
| Overloaded or in maintenance | 503 Service Unavailable, with Retry-After | Temporary, retry later |
| A proxy's upstream did not answer in time | 504 Gateway Timeout | Upstream is slow or down |
502 versus 504 tells you where to look. When a load balancer returns 502, the backend answered with something invalid or closed the connection (often a crash, or a backend whose keep-alive timeout is shorter than the load balancer's, so it closes connections the balancer is about to reuse). A 504 means the backend accepted the request but did not answer within the balancer's timeout. Both come from the proxy, not your code, so your application logs may show nothing at all.
Redirects. 301 and 302 historically allowed clients to change a POST into a GET when following the redirect. 307 (temporary) and 308 (permanent) forbid that, so the method and body are preserved. 303 See Other explicitly says "now GET this other URL", which is the classic answer after a form POST. Permanent redirects are cached aggressively by browsers, so use 302 or 307 while you are still testing.
Error bodies. Return a consistent machine-readable error body. RFC 9457 (2023) defines "problem details", a JSON format served as application/problem+json with fields such as type, title, status and detail. Whatever format you choose, never return 200 with an error inside: monitors, caches and retry logic all trust the status code.
Retry policy follows from the code.
| Response | Retry? |
|---|---|
| Connection error or timeout | Only if the request is idempotent or carries an idempotency key |
| 429, 503 | Yes, after Retry-After or with exponential backoff and jitter |
| 502, 504 | Yes for idempotent requests, with backoff |
| 500 | Maybe once. It may be a bug that fails every time |
| Other 4xx | No. Fix the request first |
Rejecting politely: 429 and rate-limit headers#
When a client exceeds its limit, an API has two options: reject now, or queue the request and process it when the limit resets. For interactive APIs, rejecting fast is almost always right. Queued requests use memory, make response times unpredictable, and users who think their request failed retry anyway and add more load. Queuing makes sense only for batch jobs that can afford to wait.
A helpful rejection tells the client exactly how to recover:
HTTP/1.1 429 Too Many Requests
Content-Type: application/json
Retry-After: 60
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1767225600
{"error": "rate_limited", "detail": "Limit of 100 requests per minute exceeded. Retry in 60 seconds."}Retry-After is standard HTTP and can be a number of seconds or a date. The X-RateLimit-* headers are a widespread convention (GitHub's API uses a similar set), and the IETF is standardising unprefixed RateLimit headers. Successful responses can carry the same headers, so well-behaved clients slow down before hitting the wall. In an interview, saying "excess requests get a 429 with Retry-After and remaining-quota headers" is usually all the detail needed. See Rate Limiting.
Key headers#
| Header | Purpose |
|---|---|
Content-Type | Format of the body, such as application/json |
Authorization | Credentials, usually Bearer <token> |
Cache-Control | Who may cache the response and for how long: public, max-age=3600, private, no-store |
ETag / If-None-Match | A version tag; the client sends it back and gets a cheap 304 if nothing changed |
Last-Modified / If-Modified-Since | Time-based version of the same check |
Accept-Encoding / Content-Encoding | Compression (gzip, Brotli) |
Retry-After | How long to wait after a 429 or 503 |
Cache-Control and ETag are what make CDNs and browser caches work; see CDN.
Headers in more depth#
Methods and status codes are small fixed sets, like enums. Headers are open-ended key-value pairs, and that openness is one of HTTP's best design decisions: new features (compression, caching, CORS, tracing) arrived as new headers without changing the protocol, and anything that does not understand a header just ignores it. It is a useful lesson for designing any interface: leave room for fields you have not thought of yet.
Content negotiation shows the idea at work. A client lists what it can handle and the server picks the best option it has:
Accept: application/jsonpicks the format.Accept-Language: frpicks the language.Accept-Encoding: gzip, brsays the client can decompress gzip or Brotli. The server compresses with one of them and says which inContent-Encoding: br. An old client that sends noAccept-Encodingstill gets an uncompressed response, so new and old clients coexist. Brotli typically makes text assets 15-25% smaller than gzip.Varytells caches which request headers changed the response.Vary: Accept-Encodingmeans a cache must store the gzip and Brotli versions separately. Forgetting it can serve compressed bytes to a client that cannot read them. Overusing it (for exampleVary: User-Agent) fragments the cache into thousands of copies and destroys the hit rate.
Cache-Control directives, precisely. These are easy to confuse, and the confusion causes real incidents:
| Directive | Meaning |
|---|---|
max-age=N | Fresh for N seconds in any cache |
s-maxage=N | Overrides max-age for shared caches (CDNs, proxies) only |
public / private | Shared caches may store it, or only the user's own browser may |
no-cache | May be stored, but must be revalidated before every reuse. It does not mean "do not cache" |
no-store | Must not be stored anywhere. Use for sensitive personal data |
must-revalidate | Once stale, never serve it without checking with the origin |
stale-while-revalidate=N | May serve a stale copy for N seconds while fetching a fresh one in the background |
stale-if-error=N | May serve a stale copy for N seconds if the origin is failing |
immutable | Will never change, so do not even revalidate (for content-hashed file names) |
stale-while-revalidate and stale-if-error deserve more use than they get: the first hides origin latency from users, and the second turns an origin outage into slightly old content instead of errors.
Conditional requests make revalidation cheap. The server tags each version of a resource with an ETag, often a hash of the content or a version number. A strong ETag ("v7") promises byte-for-byte identity. A weak one (W/"v7") promises only equivalent meaning, which is enough for caching but not for resuming downloads by byte range.
Authorization. The Authorization header carries credentials: Bearer plus a token for most APIs, or Basic (base64 of user and password, acceptable only over HTTPS and mostly for internal tools). Two rules matter more than the format:
- HTTPS protects data in transit, not its truthfulness. The client can send anything it likes. A classic bug is accepting
"userId": 123in a request body and loading that user's data. An attacker just changes the number. The server must derive identity from the verified token or session, and check that the caller may act on the resource named in the path. See Authentication and Authorization. - Choose the credential by caller. Short-lived signed tokens (often JWTs carrying the user ID, permissions and expiry) suit user sessions. API keys suit third-party developers and internal services, not humans.
Other headers designers meet often.
- CORS (cross-origin resource sharing). A browser page from
app.example.comcallingapi.example.comis cross-origin. The browser sends anOriginheader, may first send anOPTIONSpreflight for non-simple requests, and allows the call only if the API answers with a matchingAccess-Control-Allow-Origin. CORS protects users in browsers. It does nothing against a script calling your API directly. X-Forwarded-ForandForwardedrecord the original client IP as a request passes through proxies. Anyone can set these headers, so trust only the entries added by your own proxies, or an attacker can fake their IP to dodge rate limits.- Security headers.
Strict-Transport-Security(HSTS) forces HTTPS.Content-Security-Policylimits where scripts may load from.X-Content-Type-Options: nosniffstops browsers guessing content types. - Tracing. The W3C
traceparentheader carries a trace ID through every service a request touches, so distributed traces can be stitched together. See Observability.
Header size is a real cost. Many servers limit total request headers to 8-16 KB and reject larger ones with 431 or 400. Cookies are sent on every request to their domain, so a few kilobytes of cookies on a page with 100 asset requests adds hundreds of kilobytes of upload, which is one reason HTTP/2 introduced header compression and why static assets are often served from a cookie-free domain.
Compression in practice#
Text responses (HTML, JSON, CSS, JavaScript) usually shrink to 15-30% of their size when compressed, which saves bandwidth and, on slow links, time. A few practical rules:
- Choose the algorithm by content and client. gzip is supported everywhere. Brotli compresses text better and is supported by all modern browsers over HTTPS. Zstandard (zstd) is fast to compress and decompress and is increasingly supported by browsers and CDNs. The server picks from what the client lists in
Accept-Encoding. - Pre-compress static assets at build time at the highest level, since the cost is paid once. Compress dynamic responses on the fly at a moderate level: the highest Brotli levels can cost far more CPU than the bandwidth they save.
- Do not compress what is already compressed. JPEG, PNG, video, zip files and most fonts gain almost nothing and waste CPU.
- Small responses of a few hundred bytes can grow when compressed, and most servers skip them below a threshold of about 1 KB.
- Beware of secrets next to user input. The BREACH attack (2013) showed that if a compressed HTTPS response contains both a secret (such as a CSRF token) and text the attacker can influence, the attacker can guess the secret byte by byte by watching how the response size changes. The mitigations are to keep secrets out of compressed responses that reflect user input, or to mask the secret differently on every response.
Cookies#
A cookie is a small value the server sets with Set-Cookie; the browser sends it back automatically on later requests to that site. Cookies usually hold a session ID or token. Important attributes:
HttpOnly: JavaScript cannot read it, which limits theft by injected scripts.Secure: only sent over HTTPS.SameSite=LaxorStrict: not sent on most cross-site requests, which limits cross-site request forgery.Max-Age/Expires: lifetime.
Mobile apps and server-to-server calls usually send tokens in the Authorization header instead of cookies.
Sessions, cookies and tokens in more depth#
HTTP forgets everything between requests, so "logged in" has to be rebuilt on every request from something the client sends. There are two main designs:
| Server-side session | Self-contained token (for example a JWT) | |
|---|---|---|
| What the client holds | A random session ID in a cookie | A signed token with user ID, roles and expiry |
| What the server does per request | Looks up the session in a shared store such as Redis (about 0.5-1 ms) | Verifies the signature locally (microseconds), no lookup |
| Logout and revocation | Delete the session: immediate | Hard. The token stays valid until it expires, unless you keep a deny-list, which brings the lookup back |
| Size on every request | About 32 bytes | Often 500 bytes to over 1 KB |
| Typical use | Browser apps on one site | APIs, mobile apps, calls between services |
The common hybrid uses short-lived access tokens (5-15 minutes) for API calls plus a long-lived refresh token, stored more carefully, to get new access tokens. Revoking a user then means refusing their next refresh, and the damage window is at most one access-token lifetime.
Never pin users to servers instead. "Sticky sessions" keep a user's state in one server's memory and make the load balancer always route them there. That breaks the stateless model: the user is logged out when that server restarts, load spreads unevenly, and scaling in is painful. Keep session state in a shared store, and the web tier stays freely replaceable.
Cookie scope and limits. Domain and Path decide which requests carry the cookie. A cookie set for .example.com goes to every subdomain, including ones you may not fully trust. Browsers limit each cookie to about 4 KB. Cookies set by the site in the address bar are first-party. Ones set by other domains embedded in the page are third-party, which browsers increasingly block or partition, breaking designs that relied on them for cross-site login or tracking.
Why SameSite matters. In cross-site request forgery (CSRF), a malicious page makes the victim's browser send a request to your site, such as a form that POSTs to /transfer, and the browser helpfully attaches the victim's cookies. SameSite=Lax, now the default in major browsers, stops cookies being sent on cross-site POSTs, which blocks most CSRF. Sensitive actions still deserve an anti-CSRF token or a check of the Origin header. APIs that use Authorization headers instead of cookies are not exposed to CSRF in the same way, because browsers never attach those headers automatically.
Keep-alive#
HTTP/1.0 opened a new TCP connection per request. Keep-alive (the default since HTTP/1.1) keeps the connection open for further requests, saving the TCP and TLS handshakes each time. Servers and load balancers close idle connections after a timeout (often 60-120 seconds).
Keep-alive in more depth#
HTTP keep-alive and TCP keep-alive are different things. HTTP keep-alive (a persistent connection) means "do not close the connection after this response, more requests may follow". TCP keep-alive is a kernel feature that sends empty probe packets on an idle connection to check that the peer is still there and to stop NAT devices forgetting it. A long-lived HTTP connection through a NAT or load balancer often needs both.
Who closes, and when. Either side may close an idle persistent connection at any time, and sends Connection: close when it intends to close after the current response. Servers usually also cap the number of requests per connection (NGINX defaults to 1,000), which recycles connections and spreads load when servers are added. Typical idle timeouts are 60-120 seconds at load balancers (AWS ALB defaults to 60 seconds) and 5-75 seconds in web servers, and the mismatch rule from the termination section applies: the side further from the client should wait longer.
What idle connections cost. Each idle connection holds a file descriptor, kernel buffers and some per-connection memory in the server, typically from a few kilobytes to tens of kilobytes. Ten thousand idle keep-alive connections are trivial for an event-driven server such as NGINX or Envoy, which watches all of them with one epoll call per worker. The same load would exhaust a server that dedicates a thread to each connection. Dan Kegel's 1999 essay "The C10K problem" made this point about handling ten thousand concurrent clients, and event-driven designs have been the standard answer ever since.
Browsers and connection limits. Browsers allow about six HTTP/1.1 connections per host, but they normally use a single HTTP/2 or HTTP/3 connection per origin, and even share one connection across hostnames that resolve to the same IP and are covered by the same certificate (connection coalescing). Old HTTP/1.1 tricks such as domain sharding defeat this and slow modern pages down.
Partial content and range requests#
A client can ask for part of a resource with Range: bytes=1000000-1999999. A server that supports it answers 206 Partial Content with Content-Range, and advertises support with Accept-Ranges: bytes. Ranges power several everyday features:
- Resuming downloads after a dropped connection, using
If-Rangewith the ETag so you never stitch pieces of two different file versions together. - Video seeking in progressive downloads, by jumping straight to the bytes for minute 37.
- Parallel downloads of large objects from object storage, by fetching several ranges at once over separate connections, which also spreads them across network paths.
- Reading part of a big file, as columnar formats like Parquet do when a query engine reads only the footer and the columns it needs from an object in S3.
HEAD complements ranges: it returns only the headers (size, type, ETag, Last-Modified), so a client can check whether a large object changed, or plan a ranged download, without fetching the body.
HTTP/1.1 vs HTTP/2 vs HTTP/3#
| HTTP/1.1 | HTTP/2 | HTTP/3 | |
|---|---|---|---|
| Transport | TCP | TCP | QUIC over UDP |
| Format | Text | Binary frames | Binary frames |
| Concurrency | One request at a time per connection; browsers open ~6 connections | Many streams multiplexed on one connection | Many independent streams |
| Header compression | None | HPACK | QPACK |
| Head-of-line blocking | Per connection (requests queue) | At TCP level: one lost packet stalls all streams | None across streams |
| Setup (with TLS 1.3) | TCP + TLS: 2 RTT | 2 RTT | 1 RTT, or 0-RTT on resume |
| Best for | Simple clients, legacy | Service-to-service, gRPC, most web | Mobile and lossy networks |
Multiplexing removes the need for many connections and tricks like bundling all images into one file. Header compression matters because requests repeat large headers (cookies, user agents) many times.
How HTTP evolved, and why#
HTTP/1.1 (1997) and its workarounds. With one request at a time per connection, a page with 100 assets would take 100 round trips on a single connection. Browsers opened about six connections per host, sites spread assets over several hostnames (domain sharding), merged images into sprites, and bundled scripts into one large file. Pipelining, which lets a client send several requests without waiting, existed in the spec but was nearly unusable: responses still had to come back in order, and buggy proxies mishandled it. These tricks cost extra TCP and TLS handshakes, wasted cache space and made deployments clumsy.
HTTP/2 (2015) rebuilt the transport layer of HTTP. It grew out of Google's SPDY experiment. Every request and response becomes a stream with an ID, broken into binary frames (HEADERS, DATA, SETTINGS, RST_STREAM, GOAWAY and others) that interleave freely on one connection.
- Multiplexing means a slow response no longer blocks fast ones on the same connection. Sharding, sprites and giant bundles become unnecessary, and often harmful, because extra connections each pay their own handshake and slow start.
- Header compression (HPACK). Requests repeat the same large headers: cookies, user agent, accept lists. HPACK keeps a static table of 61 common header fields, a dynamic table of headers already sent on this connection, and Huffman-codes literal values. A repeated cookie then costs a byte or two instead of a kilobyte. HTTP/2 deliberately avoided compressing headers with plain gzip, because the 2012 CRIME attack showed that compressing secrets alongside attacker-controlled data leaks the secrets through the compressed size.
- Per-stream flow control and a concurrent-stream limit (commonly 100) stop one stream or one client hogging the connection.
- Prioritisation was in the original spec but rarely implemented well. It was simplified in later RFCs.
- Server push turned out to waste bandwidth on resources already in the browser cache, and browsers removed it (see the deep dive at the end of the page).
Which version is used is negotiated in the TLS handshake. The client lists the protocols it supports with ALPN (application-layer protocol negotiation), for example h2 and http/1.1, and the server picks one, so no extra round trip is needed. HTTP/3 cannot be negotiated this way because it runs on a different transport. A server advertises it in an Alt-Svc response header or an HTTPS DNS record, and the client tries QUIC on its next connection.
HTTP/3 (2022) moved HTTP onto QUIC. It keeps HTTP/2's ideas but replaces TCP with QUIC's independent streams, which removes transport head-of-line blocking (see TCP vs UDP). HPACK had to change, because it relies on headers arriving in order, and QUIC streams do not guarantee that across streams. QPACK is the replacement: it sends dynamic table updates on a dedicated stream, so a lost packet on one request does not block decoding headers of the others.
A security lesson: HTTP/2 Rapid Reset. In October 2023, Google, Cloudflare and AWS disclosed a new kind of DDoS attack (CVE-2023-44487). An attacker opens a stream and immediately cancels it with RST_STREAM, over and over, on a single connection. The cancelled streams do not count against the concurrent-stream limit, but each still costs the server work to set up. The attacks reached record request rates: Google reported a peak of about 398 million requests per second. Servers were patched to limit how fast a client may reset streams and to close abusive connections. Multiplexing gives clients more power per connection, and servers must budget per-connection work, not just connections.
TLS handshake and certificates#
TLS (Transport Layer Security) encrypts traffic, protects it from tampering, and proves the server's identity. In TLS 1.3, the handshake takes one round trip:
The certificate binds the domain name to the server's public key and is signed by a certificate authority (CA) the client already trusts. The client checks the signature chain, the hostname and the expiry date. Both sides then derive shared session keys (via ephemeral Diffie-Hellman, giving forward secrecy: stealing the server's key later does not decrypt past traffic). Free automated CAs such as Let's Encrypt issue short-lived certificates (90 days), which makes automated renewal essential.
TLS in more depth#
TLS gives three guarantees, and it helps to keep them separate:
- Confidentiality: eavesdroppers on the path (a café Wi-Fi, an ISP) see only encrypted bytes.
- Integrity: any change to the bytes in transit is detected, and the connection fails.
- Authentication: the client knows it is talking to the real
bank.example.com, not an impostor in the middle. Optionally, with mTLS, the server learns who the client is too.
How keys are agreed. In TLS 1.3, the client's first message already includes a key share: the public half of a temporary elliptic-curve Diffie-Hellman key pair (usually X25519). The server answers with its own share, and each side combines them to compute the same secret. That secret has never crossed the network, and it is thrown away after the connection. The server's long-term private key is used only to sign the handshake, proving it owns the certificate. Because the session keys are temporary, someone who steals the server's private key later still cannot decrypt recorded traffic. That is forward secrecy. The bulk data is then encrypted with an authenticated cipher, AES-GCM or ChaCha20-Poly1305, which provides confidentiality and integrity in one step.
TLS 1.2 versus 1.3. TLS 1.2 needed two round trips for a full handshake and allowed older options, including RSA key exchange without forward secrecy and weak ciphers. TLS 1.3 (RFC 8446, 2018) removed the weak options, encrypts most of the handshake, and needs one round trip. Prefer 1.3 and keep 1.2 only for older clients.
The chain of trust.
Root CAs keep their keys offline, and day-to-day signing is done by intermediates. The server must send its leaf and the intermediate certificates. A missing intermediate is a classic bug that works in some browsers (which cache intermediates from other sites) and fails in others, and in most non-browser clients.
Names and SNI. Before the handshake completes, the server must pick the right certificate among the many domains it hosts. The client says which name it wants in the SNI (server name indication) field of its first message. SNI was traditionally sent in clear text, revealing which site you visit even over HTTPS. Encrypted Client Hello (ECH) is being deployed to hide it.
Revocation is weaker than people think. If a private key leaks, the certificate must be revoked. Checking revocation online (OCSP) on every connection is slow and a privacy leak, and clients often "soft-fail" when the check does not respond. OCSP stapling, where the server attaches a recent signed status, helps. The industry's stronger answer is short certificate lifetimes, so a stolen key stops being useful quickly. Let's Encrypt issues 90-day certificates, and the CA/Browser Forum has voted to shrink the maximum lifetime of public certificates in steps, towards 47 days by 2029. With lifetimes that short, renewal has to be automated (the ACME protocol) or outages are guaranteed.
What TLS costs. On modern CPUs with AES hardware instructions, bulk encryption is cheap: a single core encrypts several gigabytes per second. The expensive part is the handshake's public-key operations. One core can perform thousands of ECDSA-signed handshakes per second, and noticeably fewer with RSA 2048-bit keys, which is one reason ECDSA certificates are popular at large edges. Session resumption (a ticket or pre-shared key from an earlier connection) skips the certificate signature and verification. At scale, the handshake rate, not the request rate, is what sizes TLS terminators. A reconnect storm after a load-balancer restart can saturate them even though normal traffic is fine.
Expiry is the classic TLS outage. When a certificate expires, every client fails at once, and the error pages blame the user's network. A related trap is trust-store changes. When the old "DST Root CA X3" root that Let's Encrypt had relied on for compatibility expired on 30 September 2021, many older devices and client libraries that did not trust Let's Encrypt's newer ISRG Root X1 started failing to connect to sites with perfectly valid certificates. Monitor expiry dates for every certificate, including internal and client ones, and test with old clients when chains change.
Where HTTPS is terminated#
TLS termination is where traffic is decrypted.
- At the edge (CDN or load balancer): the most common choice. Certificates live in one place, the LB can inspect HTTP for routing, and app servers save CPU.
- Re-encrypt to backends: the LB decrypts, inspects, then opens a new TLS connection to the app. Needed when internal networks are not trusted or regulation requires encryption everywhere.
- TLS passthrough: an L4 load balancer forwards encrypted bytes and the app terminates TLS. The LB cannot route by path or header.
- mTLS (mutual TLS) between services: both sides present certificates, usually managed by a service mesh. See Load Balancing.
What terminating TLS changes#
Wherever TLS terminates, the next hop no longer sees the original connection. Three things are lost unless you pass them on deliberately:
- The client's IP address. Behind a proxy, every request appears to come from the proxy. HTTP proxies add
X-Forwarded-For(or the standardForwardedheader). L4 proxies that do not parse HTTP use the PROXY protocol, a small header placed at the start of the TCP stream. Rate limiting, fraud checks and audit logs all depend on getting this right, and on trusting only what your own proxies add. - The original scheme. The application receives plain HTTP from the load balancer. If it naively "redirects HTTP to HTTPS", it redirects forever.
X-Forwarded-Proto: httpstells it the user's connection was secure. - Client certificate details with mTLS terminated at a proxy. The proxy must forward the verified identity in a header, and backends must accept that header only from the proxy.
Translation between versions. The edge may speak HTTP/3 to phones, HTTP/2 to the load balancer and HTTP/1.1 to an old backend. Each hop is a separate connection with its own pool, timeouts and keep-alive settings. A common mistake is mismatched idle timeouts: if a backend closes idle keep-alive connections after 5 seconds but the load balancer keeps them for 60, the balancer will sometimes send a request on a connection the backend is just closing, and users see sporadic 502s. The rule: each upstream's idle timeout must be longer than the timeout of the proxy in front of it.
Where the private keys live. Terminating at a third-party CDN means the CDN holds your private key, or can act with it. Banks and others that cannot hand keys over use the CDN's keyless mode (Cloudflare described "Keyless SSL" in 2014): the CDN does everything except the private-key signature, which it requests from a key server the customer runs. Large operators also keep keys in hardware security modules (HSMs), which perform signatures without ever revealing the key.
Long-lived connections through proxies. WebSockets begin as an HTTP/1.1 request with Upgrade: websocket and a 101 response, then become a raw two-way channel. Every proxy on the path must allow the upgrade and have idle timeouts long enough for the connection, or it will cut quiet sockets. See Real-time Communication.
Mutual TLS between services#
With ordinary TLS only the server proves who it is. With mutual TLS (mTLS) the client presents a certificate too, so both sides are authenticated by cryptography rather than by network location. In a zero-trust network, "this request came from inside our VPC" is not proof of anything. mTLS makes every service prove its identity on every connection.
Running mTLS by hand across hundreds of services is hard: each service needs a private key, a certificate naming its identity, a way to rotate both before they expire, and a policy saying which identities may call which services. Service meshes such as Istio and Linkerd automate this. A sidecar proxy next to each service handles TLS, a mesh certificate authority issues short-lived certificates (often valid for about a day) and rotates them automatically, and policy is written in terms of service identities instead of IP addresses. SPIFFE is the common standard for those identities, in the form spiffe://example.org/ns/payments/sa/api.
The cost is mostly operational: an extra proxy hop per call (typically well under a millisecond inside a data centre), more CPU for encryption, and a certificate authority that is now critical infrastructure. If it cannot issue certificates, services cannot talk once their certificates expire. Teams that do not need per-service identity often start with TLS from the load balancer to backends and network-level controls, and add mTLS when compliance or a zero-trust policy requires it.
When to Use It#
- HTTP/1.1 for simple clients, webhooks and compatibility.
- HTTP/2 for browser traffic and between services (gRPC requires it).
- HTTP/3 at the edge for mobile users and global audiences.
- HTTPS everywhere on the public internet; plain HTTP only inside trusted networks, and increasingly not even there.
When NOT to Use It#
- Do not use HTTP request/response for high-frequency two-way streams; use WebSockets or gRPC streaming. See Real-time Communication.
- Do not set
Cache-Control: publicon personalised responses; a CDN could serve one user's data to another.
How to Implement It#
- Terminate TLS at the edge with automated certificates; re-encrypt or use mTLS internally if required.
- Use correct methods and status codes so caches, retries and clients behave correctly.
- Set caching headers deliberately: long
max-agewith versioned URLs for static files;privateorno-storefor personal data;ETagfor revalidation. - Enable HTTP/2 everywhere and HTTP/3 at the edge; keep connections alive.
- Harden cookies with
HttpOnly,SecureandSameSite, and sendStrict-Transport-Security(HSTS).
# Static asset with a content hash in its name: cache for a year
GET /assets/app.3f9a1c.js
Cache-Control: public, max-age=31536000, immutable
# Personal API response: never cache in shared caches
GET /api/me
Cache-Control: private, no-store| Technology | Fits when |
|---|---|
| Nginx, Envoy, HAProxy | TLS termination, HTTP/2, reverse proxying |
| AWS ALB, Google Cloud LB, Cloudflare | Managed TLS termination and HTTP/3 at the edge |
| Let's Encrypt, AWS Certificate Manager | Free, automatically renewed certificates |
| Istio, Linkerd | mTLS between internal services |
Trade-offs#
| Choice | Pros | Cons | Pick when |
|---|---|---|---|
| Terminate at LB | Simple, central certs, L7 routing | Plaintext inside the network | Trusted private networks |
| Re-encrypt / mTLS inside | Encryption end to end | More CPU, certificate management | Zero-trust, regulated data |
| TLS passthrough | Backend controls TLS | No L7 routing at LB | Strict end-to-end requirements |
| HTTP/2 | One connection, multiplexing | TCP-level HOL blocking on loss | Most web and internal traffic |
| HTTP/3 | Fast setup, no HOL blocking | More CPU, UDP sometimes blocked | Mobile, lossy, global users |
| Server-side sessions | Instant logout, tiny cookie | A store lookup per request | Browser apps, sensitive accounts |
| Stateless tokens (JWT) | No lookup, works across services | Hard revocation, larger headers | APIs and mobile, with short expiry and refresh tokens |
Long max-age with versioned URLs | Near-100% cache hits for static assets | Must change the URL on every deploy | JS, CSS, images built by a pipeline |
Short s-maxage with stale-while-revalidate | Origin shielded, users never wait | Content can be seconds to minutes stale | Catalogues, public feeds, product pages |
| 0-RTT early data | Saves a round trip for returning clients | Replay risk | Idempotent GETs only |
| ECDSA certificates | Cheaper handshakes, smaller certificates | Very old clients may need RSA | Large edges with high handshake rates |
Common Pitfalls#
- Using GET for actions that change data, so crawlers or prefetchers trigger them.
- Returning 200 with an error body, so clients and monitors miss failures.
- Expired certificates: a classic cause of total outages; automate renewal and alert on expiry.
- Caching personalised responses in a shared cache.
- Retrying non-idempotent POSTs without an idempotency key.
- Putting tokens, emails or other personal data in URLs, where logs, history and
Refererheaders leak them. - Trusting a user ID in the request body instead of the identity in the verified token.
- Forgetting
Varyon content-negotiated responses, or addingVary: User-Agentand destroying the cache hit rate. - Treating
no-cacheas "do not store" whenno-storewas meant. - Backend keep-alive timeouts shorter than the load balancer's, causing sporadic 502s.
- Trusting
X-Forwarded-Forvalues that a client added itself. - Missing intermediate certificates, which break non-browser clients.
- Large cookies sent on every asset request.
Real-World Examples#
Let's Encrypt, launched in 2015, made free automated certificates widely available and contributed to most web traffic now being served over HTTPS.
Major browsers and CDNs, including Chrome, Firefox, Safari, Cloudflare and Akamai, support HTTP/3.
In October 2023 Google, Cloudflare and AWS jointly disclosed the HTTP/2 Rapid Reset attack, which used rapid stream cancellation to generate record request rates. Google reported a peak of about 398 million requests per second. Servers and proxies across the industry shipped patches that limit per-connection stream resets.
When the DST Root CA X3 certificate expired on 30 September 2021, older devices and libraries that did not trust Let's Encrypt's newer root began failing TLS connections to sites whose own certificates were valid. It is a reminder that trust stores on clients are part of your system.
Stripe's public API popularised the Idempotency-Key header for making POST requests safe to retry, a pattern now copied by many payment and commerce APIs.
In the Interview#
HTTP choices an interviewer listens for#
Most designs need only a handful of HTTP decisions, stated briefly while you define the API:
- Resources and methods. Plural nouns for resources (
/events,/events/123/tickets), methods with the right semantics, and inputs in the right place: IDs in the path, filters and pagination in the query, payloads in the body. Mention cursor pagination for long lists and/v1/in the path for versioning, which is the simplest default to defend. - Codes the client relies on. 201 for creation, 202 for async work, 409 for conflicts, 429 with
Retry-Afterfor rate limits. - Retry safety. "Booking is a POST with an idempotency key. Everything else is a GET or a PUT, safe to retry."
- Caching. Which responses are public and for how long, which are private, and how stale content can be (
stale-while-revalidatebehind the CDN). - Security. HTTPS everywhere, TLS terminating at the edge, JWT access tokens for users and API keys for partners, identity always taken from the token and never from the body.
- Latency. "Two round trips before the first byte on a new connection, one with HTTP/3, so keep connections warm and terminate TLS close to users."
By level. A mid-level candidate gets methods, codes and HTTPS right. A senior candidate connects HTTP semantics to infrastructure: what the CDN may cache, which retries are safe, where TLS terminates and what headers carry the client IP. A staff candidate notices second-order effects when they matter: long-lived HTTP/2 connections defeating L4 load balancing, 0-RTT replay limits, certificate lifetime automation, Rapid Reset-style abuse of multiplexing.
Common traps. Using GET for state changes. Putting tokens or personal data in URLs. Declaring Cache-Control: public on a response that includes the user's name. Saying "we use HTTPS so the request is trusted".
Deep Dive: 0-RTT, conditional requests and HTTP semantics at scaleShow
0-RTT resumption. TLS 1.3 and QUIC let a returning client send its first request together with the handshake. The catch: 0-RTT data can be replayed by an attacker, so servers should accept it only for safe, idempotent requests like GET.
Conditional requests save bandwidth and enable concurrency control. If-None-Match with an ETag turns a full response into a small 304. If-Match on a PUT gives optimistic concurrency: the update applies only if the resource still has the version the client read, otherwise the server returns 412 Precondition Failed. This prevents lost updates without locks.
Connection coalescing and limits. HTTP/2 lets a browser reuse one connection for several hostnames on the same certificate and IP, so splitting assets across many domains (an old HTTP/1.1 trick) now hurts. On the server side, a large number of idle keep-alive connections costs memory; load balancers cap them and close idle ones.
Server push was abandoned. HTTP/2 allowed servers to push resources before they were requested. In practice it often wasted bandwidth, and major browsers removed support; the 103 Early Hints status code is the lighter replacement, telling the browser what to preload.
HSTS and certificate transparency. HSTS tells browsers to always use HTTPS for a domain, defeating downgrade attacks. Certificate Transparency logs record every issued certificate publicly, so a mis-issued certificate for your domain can be detected.
Deep Dive: Message framing and request smugglingShow
HTTP/1.1 lets a request state its body length in two ways, Content-Length and Transfer-Encoding: chunked. The spec says what to do if both appear, but for years different servers did different things. That gap enables request smuggling. An attacker sends one carefully ambiguous request to a front-end proxy. The proxy thinks the body ends at one point, the backend thinks it ends at another, and the leftover bytes become the start of the next request on that reused backend connection, which may belong to a different user. Consequences documented by security researchers include bypassing front-end security checks, poisoning caches with attacker content, and capturing other users' requests.
Defences:
- Use the same, strictly conforming parser at every hop, and reject requests that carry both length headers or malformed chunk sizes.
- Prefer HTTP/2 end to end where possible, because its binary frames carry explicit lengths. Be careful where a proxy downgrades HTTP/2 to HTTP/1.1 for the backend, since that translation has produced its own smuggling bugs.
- Keep proxies and servers patched. Most real cases were fixed by parser changes in popular proxies.
The general lesson applies to any layered system: whenever two components parse the same bytes, disagreement about where a message ends is a security bug, not merely a compatibility bug.
Deep Dive: How HTTP caches decide freshnessShow
Every cache, from a browser to a CDN, follows the same model, defined in RFC 9111:
- Is there a stored response for this URL (and for the request headers listed in its
Vary)? - Is it fresh? A response's age is how long ago the origin produced it, including time spent in upstream caches, which each add an
Ageheader. It is fresh if age is below its freshness lifetime:s-maxagefor shared caches, otherwisemax-age, otherwiseExpiresminusDate. - No explicit lifetime? Caches may apply a heuristic: commonly 10% of the time since
Last-Modified. A file last changed 10 days ago may be considered fresh for a day without any header saying so. This surprises teams who never set caching headers and still see stale content. Always setCache-Controlexplicitly. - Stale? The cache revalidates with
If-None-MatchorIf-Modified-Since. A 304 refreshes the stored copy's age without resending the body. Ifstale-while-revalidateallows it, the cache serves the stale copy immediately and revalidates in the background.
Worked example: a product API responds with Cache-Control: public, s-maxage=30, stale-while-revalidate=60 and is requested 2,000 times per second at one CDN location. The origin sees about one revalidation every 30 seconds from that location, instead of 2,000 requests per second, and users never wait for the origin, because an expired copy is served while a refresh runs. The price is that a price change can take up to 90 seconds to show everywhere. If that is too slow for some fields, split them into a separate, short-lived or uncached endpoint, or purge the CDN on change. See Caching Strategies and CDN.
Deep Dive: A page load under HTTP/1.1, HTTP/2 and HTTP/3, in round tripsShow
Take a page that needs an HTML document and then 60 small assets (scripts, styles, images, each well under one congestion window), loaded by a user 100 ms away from the nearest server, with TLS 1.3. Ignore server think time and bandwidth limits to isolate the protocol effects.
HTTP/1.1. DNS aside, the first connection costs one RTT for TCP and one for TLS, then one for the HTML: 300 ms. The browser then opens five more connections, each paying 200 ms of handshakes, which overlap with each other. With six connections, the 60 assets need about ten rounds of requests: roughly 200 + 10 x 100 = 1,200 ms. Total about 1.5 seconds, and more on a lossy network, because each new connection also starts in slow start.
HTTP/2. One connection: 200 ms of handshakes, 100 ms for the HTML, then all 60 requests go out at once and come back interleaved in about one or two RTTs: total roughly 400-500 ms. On a network with 1-2% loss, a lost packet stalls all streams while it is retransmitted, and the single connection's window is halved, so the advantage shrinks, which is the case HTTP/3 improves.
HTTP/3. One RTT for the combined QUIC and TLS handshake, 100 ms for the HTML, one or two RTTs for the assets: about 300-400 ms. With 0-RTT resumption on a returning visit, the HTML request leaves in the first packet, saving another 100 ms. Under loss, only the streams whose packets were lost wait.
Three lessons follow. Round trips, not bytes, dominate the loading of small resources over distance. Every protocol improvement since HTTP/1.1 has been about removing round trips or stopping one loss from blocking unrelated work. And the biggest gain of all is often not the protocol but proximity: serving those same assets from a CDN location 10 ms away makes even HTTP/1.1 fast.
Deep Dive: Debugging HTTP and TLS in productionShow
When a request is slow or failing, a few tools separate the possible causes quickly:
curl -vshows the TLS version negotiated, the certificate chain the server sent, the request and response headers, and redirects. Add--http2or--http3to test a specific version.curl -wwith timing variables (time_namelookup,time_connect,time_appconnect,time_starttransfer,time_total) splits a request into DNS, TCP, TLS, server processing and download. Iftime_starttransferminustime_appconnectis large, the server or its dependencies are slow, and network tuning will not help.openssl s_client -connect host:443 -servername hostprints the full certificate chain and its expiry dates. It is the quickest way to catch a missing intermediate or an expired certificate that one client sees and others do not.- The browser's network panel shows a waterfall of every request with its timing phases, protocol and cache status. A HAR export captures it so others can analyse it later.
Server-Timingresponse headers let your backend report its own breakdown (database 12 ms, cache 1 ms, render 30 ms) to the browser's developer tools, which ties front-end and back-end views together without any extra tooling.- Proxy and load-balancer logs usually record both the time spent waiting for the backend and the total time. A 504 with "upstream time 30.0 s" points at a backend that hung. A 502 with "upstream time 0.001 s" points at a connection the backend closed or refused.
A useful habit is to compare a failing request through the whole path (client to CDN to load balancer to service) with the same request sent straight to one backend from inside the network. If the direct request works, the problem lies in the layers in between: timeouts, header limits, TLS settings or routing rules.
Key Takeaways#
- HTTP is stateless request/response; state travels in cookies or tokens.
- Safe methods only read; idempotent methods can be retried. POST needs an idempotency key to be retried safely.
- Use status codes correctly: 4xx means fix the request, 5xx and 429 mean retry with backoff.
Cache-ControlandETagdecide what browsers and CDNs cache; never publicly cache personal data.- HTTP/2 multiplexes over TCP; HTTP/3 uses QUIC to cut setup time and remove cross-stream head-of-line blocking.
- TLS usually terminates at the CDN or load balancer; use re-encryption or mTLS inside when required.
- Correct HTTP semantics let browsers, CDNs, load balancers and gateways help you. Statelessness lets any server answer any request.
- Idempotency is about effect on state. Make POSTs retry-safe with idempotency keys, client-chosen IDs or unique constraints.
- Status codes drive client behaviour: 429 and 503 with
Retry-Aftersay "slow down", 502 and 504 point at the hop behind the proxy. no-cachemeans revalidate,no-storemeans never store.stale-while-revalidateandstale-if-errorhide origin latency and outages.- HTTPS proves where data came from in transit, not that its contents are honest. Take identity from verified tokens.
- HTTP/2 multiplexes with HPACK, HTTP/3 moves to QUIC with QPACK, and ALPN or
Alt-Svcdecides which is used. - TLS 1.3 gives forward secrecy in one round trip. Handshake rate sizes TLS terminators, and certificate expiry must be automated and monitored.