HTTP/1.1, HTTP/2, HTTP/3, Keep-Alive & HTTPS
"Note, however, that TCP head-of-line blocking is not addressed by this protocol." — RFC 9113, HTTP/2, section 1 (June 2022)
Summary: HTTP has one set of semantics (methods, status codes, headers, caching) and three wire versions. HTTP/1.1 reuses connections but serves one response at a time on each; HTTP/2 multiplexes many streams over one TCP connection but still stalls on TCP loss; HTTP/3 moves the streams into QUIC over UDP so a lost packet blocks only its own stream. Around them sit keep-alive pools, timeouts, compression, conditional requests and HTTPS (TLS, HSTS, ACME), which decide most of the latency and failure behaviour you actually see. Focus: HTTP/1.0 vs 1.1 (persistent connections, pipelining, chunked transfer encoding, Host header), HTTP/2 (binary framing, streams, multiplexing, HPACK, flow control, prioritisation, server push and its removal, connection coalescing, ALPN h2, h2c), HTTP/3 over QUIC (independent streams, 0-RTT, connection migration, QPACK, Alt-Svc, UDP fallback), HTTPS everywhere (TLS termination, HSTS, ACME), performance patterns (pool sizing, compression, 103 Early Hints, preload/preconnect), semantics (safe and idempotent methods, status codes, conditional and range requests, content negotiation), timeouts, gRPC and WebSockets over h2, with Go (net/http, quic-go) and Laravel/PHP (HTTP client pool, Guzzle, curl multi) code. Learning goal: For every hop in a design (browser to edge, edge to origin, service to service) pick the HTTP version and say why, size the connection pool and every timeout so they cannot fight each other, place TLS termination and certificate automation, and prove the choice with a test that counts connections and streams.
This chapter is the application-protocol chapter of the Networking & Protocols group. It sits after TCP & UDP (the transports underneath) and before Real-Time Communication, REST API Design and gRPC & Protocol Buffers (what is built on top). The wire-level TLS handshake, certificates, SNI and openssl s_client live in TLS in Practice; PKI and secrets design in Cryptography in Practice; compression algorithms themselves in Compression; cache design (cache-aside, invalidation, stampedes) in Caching and CDNs; sockets, ephemeral ports and TIME_WAIT in Ports, Sockets & Connections; Go's TLS and benchmarking with h2load in HTTP/2, HTTPS, TLS & mTLS in Go. This page owns the system-level decisions: which version on which hop, how many connections, which timeouts, where TLS ends, and what each choice costs.
Page map
| If you are looking for | Go to |
|---|---|
| The whole page in three tables | Everything in one minute |
| Why HTTP needed three versions | Why it exists |
| 1991 to 2022, RFC by RFC | Where it comes from |
| Methods, safe vs idempotent, status code families | Semantics vs versions |
| Keep-alive, persistent connections, pipelining | Persistent connections, Pipelining |
| Content-Length, chunked, Host, 100-continue | HTTP/1.1 message framing |
| Frames, streams, multiplexing, HPACK, QPACK | Binary framing, Header compression |
| Flow control, priorities, head-of-line blocking | Flow control, Head-of-line blocking |
| Server push, 103 Early Hints, preload, preconnect | Push and hints |
| ALPN, h2 vs h2c, coalescing, 421 | Negotiation and coalescing |
| QUIC, connection migration, 0-RTT, Alt-Svc | HTTP/3 over QUIC, 0-RTT, Discovery |
| TLS termination, HSTS, ACME | HTTPS everywhere |
| gzip, Brotli, zstd, Accept-Encoding, Vary | Compression and negotiation |
| ETag, 304, Cache-Control, ranges, 206 | Conditional requests, Range requests |
| Connect, header, body and idle timeouts | Timeouts |
| Pool sizing, MaxIdleConnsPerHost, curl multi | Client pools |
| gRPC and WebSocket over h2 | gRPC and WebSockets |
| Frames, settings, error codes, knobs | Mechanics |
| Code | Go, Laravel |
| Classic failures and their fixes | Solving the classic problems |
| Which version per hop | Choosing |
| Monolith to distributed system | In architecture |
| Counting connections and streams yourself | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The three versions. Same semantics (RFC 9110), different wire.
| Version | In plain words | Concurrency per connection | Header encoding | Transport | Head-of-line blocking |
|---|---|---|---|---|---|
| HTTP/1.0 (RFC 1945, 1996) | One request, one connection, then close | 1, then close (unless Connection: keep-alive) | Text | TCP | Per connection |
| HTTP/1.1 (RFC 9112) | Keep the connection, one exchange at a time | 1 in flight (pipelining is in-order and unused) | Text | TCP, optional TLS | Application level: response 2 waits for response 1 |
| HTTP/2 (RFC 9113) | Many streams interleaved as binary frames on one connection | Up to SETTINGS_MAX_CONCURRENT_STREAMS (recommended at least 100) | HPACK | TCP + TLS (h2) or cleartext (h2c) | TCP level: one lost segment stalls all streams |
| HTTP/3 (RFC 9114) | HTTP/2 ideas mapped onto QUIC streams over UDP | QUIC stream limits (initial_max_streams_bidi) | QPACK | QUIC (RFC 9000) with TLS 1.3 built in, over UDP | Only the stream whose packet was lost |
Cost of a fresh connection (illustrative, at 50 ms round-trip time; back-of-envelope, not a measurement).
| Path | Round trips before the request leaves | Time at 50 ms RTT | When you pay it |
|---|---|---|---|
| TCP + TLS 1.2 | 3 | about 150 ms | Every new connection |
| TCP + TLS 1.3 | 2 | about 100 ms | Every new connection |
| QUIC (HTTP/3) | 1 | about 50 ms | Every new connection |
| QUIC 0-RTT resumption | 0 (request rides in the first flight) | about 0 ms extra | Returning client, replay-safe requests only |
| Reused keep-alive connection | 0 | 0 ms | Every request after the first |
What to remember per concern.
| Concern | Rule | Owner block |
|---|---|---|
| Reuse | One long-lived client per upstream; drain response bodies; never a client per request | Client pools |
| Timeouts | Connect, TLS, header and total timeouts on clients; header, body, write and idle timeouts on servers; client idle timeout below the server's | Timeouts |
| Version per hop | h3 or h2 to the edge, h2 or keep-alive h1.1 inside, gRPC on h2, h2c only on trusted networks | Choosing |
| TLS | Terminate where certificates are automated (ACME); HSTS on every HTTPS response | HTTPS everywhere |
| Bytes | Brotli or zstd for text, Vary: Accept-Encoding, ETag + 304 for revalidation, ranges for large files | Compression, Conditional |
| Push | Dead in browsers; use 103 Early Hints and rel=preload / rel=preconnect | Push and hints |
| Retries | Only idempotent requests, or requests HTTP/2 proves were not processed (GOAWAY, REFUSED_STREAM) | Semantics |
The picture is the whole chapter in one frame: the top band (semantics) never changes; everything below it does. HTTP/2 removed head-of-line blocking from HTTP but left it in TCP, which is why HTTP/3 had to replace the transport.
Why it exists
The web of 1996 fetched one document and a few images. A page in 2026 makes dozens to hundreds of requests, and service-to-service traffic inside a company makes millions per second. Every version of HTTP answers the same question: how do we carry more concurrent request/response exchanges with fewer round trips and fewer connections, without changing what a request means?
RFC 9113 states the HTTP/1.x problem directly: "HTTP/1.0 allowed only one request to be outstanding at a time on a given TCP connection." HTTP/1.1 added persistence and pipelining, but responses must come back in order, so clients opened several connections per host. HTTP/2 multiplexed streams over one connection, which helped until a packet was lost: TCP delivers bytes in order, so every stream on the connection waits for one retransmission. HTTP/3 runs over QUIC, where each stream is ordered independently.
| Fewer, longer-lived connections (h2, h3, keep-alive) | Many short connections (HTTP/1.0 style) |
|---|---|
| Handshake (TCP + TLS) paid once per connection | Handshake paid per request: 1 to 3 RTT each |
| One congestion window warmed up and shared | Every connection starts in slow start |
| Header compression context persists (HPACK/QPACK) | Full headers every time |
| Long-lived connections pin clients to backends: L4 load balancing gets uneven | Every request can land anywhere |
| A dead connection affects many in-flight requests | A dead connection affects one request |
| Needs idle timeouts, health pings and graceful GOAWAY | Simple: close after each response |
Fewer sockets, fewer TIME_WAIT entries, fewer file descriptors | Port exhaustion and TIME_WAIT churn under load |
The analogy we reuse on this page: the shop counter, the conveyor belt and the delivery vans. HTTP/1.0 is a shop where you queue, buy one item and must leave and queue again for the next. HTTP/1.1 keep-alive lets you stay at the counter, but the clerk serves your orders strictly one after another; if the first is a custom cake, the bread waits (pipelining is shouting all your orders at once, but you still get them in order, so nobody bothered). HTTP/2 is a conveyor belt: many orders travel interleaved on one belt, but if one box falls off, the whole belt stops until it is put back (TCP). HTTP/3 gives every order its own small van on a shared road (QUIC streams over UDP): one van with a flat tyre does not stop the others, and if you move house mid-delivery the vans follow your new address (connection migration). HTTPS is the sealed box with a verified label; HSTS is the sign on the door that says "never accept unsealed boxes from us"; ACME is the automatic label printer.
Three common misunderstandings, up front
- "HTTP/2 makes everything faster." It removes application-level head-of-line blocking and handshake overhead per request. On a lossy mobile link, one TCP connection carrying everything can be slower than six HTTP/1.1 connections, because one loss stalls all streams; RFC 9113 says so in its introduction (the opening quote). Inside a data centre with sub-millisecond RTT and no loss, the difference is mostly fewer sockets.
- "Keep-alive is the TCP keep-alive option." HTTP keep-alive (persistent connections) means reusing a connection for several requests. TCP keep-alive is an OS probe that detects dead peers on idle sockets. Go's own documentation for
DisableKeepAliveswarns: "This is unrelated to the similarly named TCP keep-alives." - "HTTP/3 replaces HTTP/2." HTTP/3 needs UDP, which some corporate networks block; RFC 9114 tells clients to "attempt to use TCP-based versions of HTTP in this case". Every HTTP/3 deployment keeps HTTP/2 (and usually HTTP/1.1) on TCP, and advertises h3 with
Alt-Svcor the HTTPS DNS record.
Where it comes from
HTTP/0.9 and 1.0 (1991 to 1996). Tim Berners-Lee's original protocol had one method (GET) and no headers. RFC 1945 (May 1996) documented "common usage of the protocol referred to as "HTTP/1.0"": headers, status codes, POST, content types, and a connection per request. Some clients and servers added an unofficial Connection: keep-alive.
HTTP/1.1 (RFC 2068 in January 1997, RFC 2616 in 1999, RFC 7230-7235 in 2014, RFC 9110-9112 in June 2022). Persistent connections became the default, Host became mandatory (one IP, many sites), chunked transfer encoding allowed streaming of unknown-length bodies, and caching got ETag, Cache-Control and conditional requests. The June 2022 rewrite split HTTP into semantics (RFC 9110), caching (RFC 9111) and per-version wire formats (RFC 9112 for 1.1, 9113 for 2, 9114 for 3).
SPDY to HTTP/2 (2009 to 2015). Google's SPDY experiment showed that multiplexing plus header compression cut page load times; the IETF used it as the starting point for HTTP/2, published as RFC 7540 with HPACK as RFC 7541 (both May 2015). RFC 9113 (June 2022) obsoleted 7540, deprecated its priority tree and the h2c upgrade, and left everything else compatible.
QUIC and HTTP/3 (2012 to 2022). Google's gQUIC moved transport into user space over UDP. The IETF standardised QUIC as RFC 9000 (May 2021) with TLS 1.3 integrated (RFC 9001), then HTTP/3 (RFC 9114) and QPACK (RFC 9204) in June 2022.
Push dies, hints arrive (2017 to 2024). RFC 8297 (December 2017) defined 103 Early Hints. Chrome announced that server push "will be disabled by default in Chrome 106", noting that "only 1.25% of HTTP/2 sites" used it; Firefox 132 (29 October 2024) followed: "HTTP/2 Server Push is deactivated by default with the preference network.http.http2.allow-push now set to false." NGINX's http2_push directive "is obsolete since version 1.25.1".
HTTPS everywhere (2012 to now). HSTS (RFC 6797, November 2012) let sites forbid plain HTTP. ACME (RFC 8555, March 2019), the protocol behind Let's Encrypt, made certificates free and automatic. Lifetimes keep shrinking: Let's Encrypt (2 December 2025): "We currently issue certificates valid for 90 days, which will be cut in half to 45 days by 2028."
Year Milestone What changed for system design
1 1991 HTTP/0.9 GET only, connection per document
2 1996 RFC 1945 HTTP/1.0 Headers, status codes, POST; still one request per connection
3 1997 RFC 2068 HTTP/1.1 Persistent connections by default, Host, chunked, caching
4 2012 RFC 6797 HSTS Sites can forbid plain HTTP
5 2015 RFC 7540 HTTP/2 + RFC 7541 HPACK Multiplexing, binary frames, header compression
6 2017 RFC 8297 103 Early Hints A replacement for push begins
7 2018 RFC 8441 WebSockets over HTTP/2 Extended CONNECT, one stream per socket
8 2019 RFC 8555 ACME Automated certificates become the default
9 2021 RFC 9000 QUIC Transport in user space, over UDP
10 2022 RFC 9110-9114, RFC 9204 QPACK Semantics split from wire; HTTP/3 standard
11 2022 Chrome 106 disables server push Push effectively dead in browsers
12 2024 Firefox 132 disables server push Last major browser drops it
13 2027 Let's Encrypt default 64-day certificates Renewal automation becomes mandatory (45 days by 2028)The concept catalogue
Each block follows the same order: plain words, the usual wrong belief, a definition, a request flow, real scenarios, what each product does, and the fix.
HTTP semantics vs wire versions: methods, safety, idempotency, status codes Must-know
In plain words: what a request means (read this, replace that, delete this) is the same in every HTTP version; only how the bytes travel changes.
Common misunderstanding: "HTTP/2 changed the API." A GET /orders/7 that returns 304 means the same thing on HTTP/1.1, HTTP/2 and HTTP/3; your REST or gRPC contract does not change when the edge upgrades. What does change is retry safety at the transport level (HTTP/2 can prove a request was not processed) and error shapes (a stream reset instead of a closed socket).
Definition: RFC 9110 defines methods, status codes and fields for all versions. A method is safe if "the client does not request, and does not expect, any state change on the origin server"; it is idempotent if "the intended effect on the server of multiple identical requests with that method is the same as the effect for a single such request". Safe methods: GET, HEAD, OPTIONS, TRACE. Idempotent: those plus PUT and DELETE. POST and PATCH are neither, unless the application makes them so (an Idempotency-Key, see API Idempotency).
Client Connection Server
1 POST /payments (no key) -> TCP reset after the request was written
2 did the server charge? unknown: the outcome is lost with the connection
3 retry? only with an Idempotency-Key, or not at all
4 GET /payments/9 -> TCP reset
5 retry safe: GET is idempotent; Go's Transport retries it by itself
6 POST on HTTP/2, server sends GOAWAY last-stream-id=5, our stream was 7
7 retry stream 7 on a new connection: RFC 9113 says it was not processedReal scenario: a payment client that retries POST after a reset and double-charges; a load balancer (AWS ALB, NGINX) that retries idempotent upstream requests on 502 but must never retry POST; a crawler that treats HEAD as free; a cache that may store GET and HEAD responses but not POST by default.
What provides it:
| Product | Automatic retry rule | Note |
|---|---|---|
Go net/http Transport | Retries on a network error only "if the connection has already been used successfully and if the request is idempotent" (GET, HEAD, OPTIONS, TRACE, or an Idempotency-Key / X-Idempotency-Key header) and the body can be replayed | Documented in the net/http package overview |
| HTTP/2 (RFC 9113 8.7) | Streams above the GOAWAY last-stream-id and streams reset with REFUSED_STREAM "can be safely retried" | "Requests that have not been processed have not failed; clients MAY automatically retry them, even those with non-idempotent methods." |
NGINX proxy_next_upstream | By default not for non-idempotent methods (non_idempotent flag opts in) | Keep the default |
| Laravel HTTP client | retry() retries whatever you tell it | Put the method and key check in the when callback (Service Communication) |
Status code families (RFC 9110 section 15):
| Family | Meaning | Codes this chapter uses |
|---|---|---|
| 1xx Informational | Interim, more is coming | 100 Continue, 101 Switching Protocols, 103 Early Hints |
| 2xx Successful | Done | 200 OK, 204 No Content, 206 Partial Content |
| 3xx Redirection | Look elsewhere or use your copy | 301/308 (HTTP to HTTPS), 304 Not Modified |
| 4xx Client error | Fix the request | 400 (missing Host), 408, 416 Range Not Satisfiable, 421 Misdirected Request, 425 Too Early, 431 |
| 5xx Server error | Server or upstream failed | 502 Bad Gateway, 503, 504 Gateway Timeout |
Fix / how to use it: design APIs so reads are GET, replacements are PUT, and every POST with side effects accepts an idempotency key; let transports retry only what they can prove is safe; never return 200 with an error body. Status code design for APIs is in REST API Design.
Persistent connections and keep-alive Must-know
In plain words: keep the TCP (and TLS) connection open after a response and send the next request on it, instead of paying a new handshake each time.
Common misunderstanding: "My client reuses connections because HTTP/1.1 is persistent by default." The protocol allows it; your client must cooperate. A new client object per request, a body that is never read to the end, or a Connection: close from a proxy each turns reuse off, and nothing errors: you just pay 2 to 3 RTT per call and pile up TIME_WAIT sockets.
Definition: RFC 9112 section 9.3: "HTTP/1.1 defaults to the use of "persistent connections", allowing multiple requests and responses to be carried over a single connection." A connection closes after the current response if either side sends the close connection option. For HTTP/1.0 the keep-alive option is an opt-in that proxies must not honour. The server decides how long an idle connection lives (RFC 9112 9.5: "Servers will usually have some timeout value beyond which they will no longer maintain an inactive connection").
Client (shared pool) Server (keep-alive, idle timeout 75 s)
1 GET /a [new TCP + TLS: 2 RTT] -> 200, Content-Length: 512
2 reads all 512 bytes; connection returns to the idle pool
3 GET /b [reused, 0 RTT setup] -> 200
4 ... 80 s of silence ... server idle timeout fires, sends FIN
5 GET /c on the stale connection -> RST or EOF: "server closed idle connection"
6 Go retries /c (GET, used connection) on a new connection; a POST would surface the errorReal scenario: an API gateway calling 20 backends, each request paying a TLS handshake because the gateway builds a client per request; a PHP-FPM app where every web request starts with empty curl handles, so every upstream call is a fresh connection; a Laravel Octane or Go service where one shared client keeps 50 warm connections; 502 errors on AWS ALB when the backend's keep-alive timeout is shorter than the ALB's idle timeout.
What provides it:
| Product | Keep-alive knob | Default |
|---|---|---|
Go net/http client | Transport.MaxIdleConns, MaxIdleConnsPerHost, IdleConnTimeout, DisableKeepAlives | 100 total, 2 per host (DefaultMaxIdleConnsPerHost), 90 s in DefaultTransport |
Go net/http server | Server.IdleTimeout, SetKeepAlivesEnabled | Falls back to ReadTimeout; zero means none |
| NGINX (client side) | keepalive_timeout, keepalive_requests | 75 s, 1000 requests |
| NGINX (to upstream) | keepalive in upstream, keepalive_timeout | Since 1.29.7 enabled by default: 32 idle connections per worker, 60 s |
| AWS ALB | idle_timeout.timeout_seconds, client_keep_alive.seconds | 60 s idle, 3600 s client keepalive |
| curl / PHP | Connection cache per easy or multi handle | Lives as long as the handle; in PHP-FPM, as long as the web request |
| Laravel HTTP client | One Guzzle client per Http:: call; a pool() shares one handler | Reuse within a pool; across web requests only with Octane |
Fix / how to use it: one long-lived client per upstream (Go: a package-level or injected *http.Client; Laravel: Http::pool for fan-out, Octane for cross-request reuse, or a local proxy with upstream keep-alive for PHP-FPM); always drain and close bodies; set the client's idle timeout a few seconds below the server's or load balancer's so the client closes first. Code: Go, Laravel.
Pipelining and why it failed Important
In plain words: send several requests on one HTTP/1.1 connection without waiting; the server must answer them in the same order.
Common misunderstanding: "Pipelining is HTTP/1.1's multiplexing." It is not: responses are strictly ordered, so a slow first response blocks every response behind it (application-level head-of-line blocking), and a connection failure in the middle leaves the client unsure which requests ran.
Definition: RFC 9112 9.3.2: a client "MAY "pipeline" its requests (i.e., send multiple requests without waiting for each response)"; the server "MUST send the corresponding responses in the same order that the requests were received". A user agent "SHOULD NOT pipeline requests after a non-idempotent method".
Client Server
1 GET /slow GET /a GET /b (3 requests written back to back)
2 /a and /b are ready after 5 ms
3 /slow needs 300 ms; /a and /b must wait behind it
4 <- /slow (t=300 ms) <- /a <- /b
5 if the connection dies at t=200 ms: which of /a and /b ran? retry only if idempotentReal scenario: browsers shipped it disabled or removed it because buggy proxies corrupted pipelined responses; libcurl removed it ("This bit is deprecated and has no effect since version 7.62.0" for CURLPIPE_HTTP1); Redis clients use the same idea successfully because Redis is one server, one ordered protocol, no proxies (see Redis).
What provides it: almost nothing in practice. Go's net/http client never pipelines; libcurl only multiplexes (CURLPIPE_MULTIPLEX, the default); NGINX accepts pipelined requests from clients but processes them in order.
Fix / how to use it: do not design for pipelining. Use HTTP/2 or HTTP/3 multiplexing for concurrency on one connection, or several HTTP/1.1 connections from a pool.
HTTP/1.1 message framing: Content-Length, chunked, Host, 100-continue Important
In plain words: on a reused connection the receiver must know exactly where one message ends and the next begins; HTTP/1.1 uses either a byte count or a chunked encoding for that, and the Host header to say which site you mean.
Common misunderstanding: "Framing is the parser's problem, not mine." When two hops disagree about where a message ends (one trusts Content-Length, the other Transfer-Encoding), an attacker can hide a second request inside the first: request smuggling (RFC 9112 11.2). That is an architecture problem whenever a proxy sits in front of a server.
Definition: the body length comes from Content-Length or from Transfer-Encoding: chunked. RFC 9112 7.1: "Chunked enables content streams of unknown size to be transferred as a sequence of length-delimited buffers, which enables the sender to retain connection persistence". Chunked bodies can end with trailers (fields sent after the body; gRPC uses them on HTTP/2). Host is mandatory: "A server MUST respond with a 400 (Bad Request) status code to any HTTP/1.1 request message that lacks a Host header field". Expect: 100-continue lets a client ask permission before uploading a large body; the server answers 100 Continue or a final error. HTTP/2 and HTTP/3 have their own framing (DATA frames with END_STREAM), so Transfer-Encoding: chunked is forbidden there and Host becomes the :authority pseudo-header.
Client Server
1 POST /upload Host: api.example.com
Content-Length: 5000000 Expect: 100-continue (headers only)
2 checks auth and quota
3 <- HTTP/1.1 100 Continue
4 sends the 5 MB body
5 <- HTTP/1.1 201 Created
6 GET /export (streamed CSV) ->
7 <- 200, Transfer-Encoding: chunked
"1000\r\n<4096 bytes>\r\n" ... "0\r\n\r\n" (0-size chunk ends the body; connection stays open)Real scenario: streaming a large report without knowing its size; a reverse proxy that rejects uploads before reading 5 GB; virtual hosting thousands of sites on one IP; a desync between AWS ALB, NGINX and a backend that disagree about Transfer-Encoding.
What provides it:
| Product | Behaviour |
|---|---|
Go net/http | Chunked automatically when you write without Content-Length and flush; Expect: 100-continue handled on the first body read; ExpectContinueTimeout on the client |
| NGINX | Normalises requests before proxying; client_max_body_size stops oversized uploads; chunked_transfer_encoding toggles chunked responses |
| PHP-FPM behind NGINX | Receives a FastCGI request; framing is NGINX's job |
| curl | Sends Expect: 100-continue for large uploads by default and waits briefly for the 100 (a classic one-second stall against servers that ignore it; libcurl behaviour, not from the RFC) |
Fix / how to use it: keep one parser in charge at the edge (a normalising proxy such as NGINX, HAProxy or Envoy), reject requests with both Content-Length and Transfer-Encoding, prefer HTTP/2 between proxy and backend where possible (no ambiguous framing), and stream large responses instead of buffering them.
HTTP/2 binary framing, streams and multiplexing Must-know
In plain words: HTTP/2 cuts every request and response into small binary frames, labels each frame with a stream number, and interleaves frames from many streams on one connection.
Common misunderstanding: "One HTTP/2 connection means one request at a time is processed." The opposite: the server may process hundreds of streams concurrently on one connection, which is why one HTTP/2 client can overload a backend that was sized for "connections", and why a single h2 connection through an L4 load balancer pins all of a client's traffic to one backend.
Definition: RFC 9113: frames share a 9-byte header (length, type, flags, stream identifier). Client-initiated streams use odd numbers (1, 3, 5...), stream 0 is the connection itself. A request is a HEADERS frame (plus CONTINUATION if needed) and optional DATA frames; END_STREAM closes one direction. Concurrency per connection is bounded by SETTINGS_MAX_CONCURRENT_STREAMS: "It is recommended that this value be no smaller than 100". A connection begins with a fixed connection preface from the client and a SETTINGS frame from each side.
Client Server
1 preface "PRI * HTTP/2.0..." + SETTINGS ->
2 <- SETTINGS (MAX_CONCURRENT_STREAMS=128)
3 HEADERS stream 1 (GET /a) ->
4 HEADERS stream 3 (GET /b) ->
5 HEADERS stream 5 (POST /c) + DATA 5 ->
6 <- HEADERS 3, DATA 3 (b finishes first)
7 <- HEADERS 1, DATA 1 ... DATA 5 interleaved
8 RST_STREAM 5 (CANCEL): user navigated away; streams 1 and 3 unaffected
9 <- GOAWAY last-stream-id=3 (graceful shutdown)Real scenario: a browser loading 80 assets over one connection to a CDN; gRPC sending thousands of RPCs per second over a handful of connections; an internal API gateway (Envoy, NGINX) holding one h2 connection per backend instead of 500 HTTP/1.1 sockets; Rapid Reset (CVE-2023-44487), where attackers abused stream cancellation: "request cancellation can reset many streams quickly".
What provides it:
| Product | HTTP/2 support | Concurrency knob |
|---|---|---|
Go net/http | Built in for HTTPS servers and DefaultTransport; Server.Protocols / Transport.Protocols (Go 1.24) | HTTP2Config.MaxConcurrentStreams (server; "defaults to at least 100") |
| NGINX | http2 on; (since 1.25.1; default off) | http2_max_concurrent_streams (128) |
| AWS ALB | routing.http2.enabled (default true) for clients; target groups can use HTTP/2 or gRPC protocol version | Managed |
| Cloudflare | HTTP/2 to visitors by default; HTTP/2 to origin optional | Managed |
| curl / PHP | CURL_HTTP_VERSION_2TLS, multiplexing in curl_multi | CURLMOPT_MAX_CONCURRENT_STREAMS (default 100) |
| Envoy | http2_protocol_options | max_concurrent_streams |
Fix / how to use it: enable h2 on the edge and on long-lived internal hops; cap concurrent streams and protect against reset floods (keep servers patched; Go, NGINX, Envoy and others shipped Rapid Reset mitigations in October 2023); balance long-lived h2 connections at L7 (per request), not L4 (per connection), see Load Balancing.
HPACK and QPACK header compression Important
In plain words: both ends remember headers they already saw (user-agent, cookie, :authority) in a small table, so a repeated header shrinks to an index of one or two bytes.
Common misunderstanding: "Header compression is gzip for headers." Compressing headers with a generic compressor leaked secrets (the CRIME attack on SPDY); HPACK uses a static table, a per-connection dynamic table and Huffman coding precisely to avoid that. And it is stateful: a lost or misordered header block would corrupt the table, which is why HTTP/3 could not reuse HPACK unchanged.
Definition: RFC 7541 "defines HPACK, a compression format for efficiently representing HTTP header fields, to be used in HTTP/2". The dynamic table size is negotiated with SETTINGS_HEADER_TABLE_SIZE ("The initial value is 4,096 octets"). RFC 9204 defines QPACK for HTTP/3: "This is a variation of HPACK compression that seeks to reduce head-of-line blocking." QPACK sends table updates on separate unidirectional encoder and decoder streams and lets the encoder choose whether a header block may reference entries the peer has not acknowledged yet (SETTINGS_QPACK_BLOCKED_STREAMS).
Request 1 on the connection Request 2
1 :method GET -> static index 2 static index 2 (1 byte)
2 :authority api.example.com -> literal, added to dynamic table as 62
3 authorization: Bearer eyJ... (800 bytes) -> literal, added as 63, never-indexed if sensitive
4 :authority -> index 62 (1 byte)
5 authorization -> index 63 (1 byte) or literal again
6 HTTP/3: dynamic table inserts travel on the QPACK encoder stream; a request stream that
references entry 63 before it arrives is "blocked" only if the encoder allowed itReal scenario: mobile clients with large cookies and bearer tokens; gRPC metadata repeated on every RPC; an API gateway forwarding 30 headers per request; 431 Request Header Fields Too Large or COMPRESSION_ERROR when a header grows past limits.
What provides it: Go HTTP2Config.MaxDecoderHeaderTableSize / MaxEncoderHeaderTableSize and Server.MaxHeaderBytes; NGINX large_client_header_buffers for HTTP/1.1 and HTTP/2 header limits, http3_* for QPACK; quic-go ships QPACK as github.com/quic-go/qpack.
Fix / how to use it: keep headers small (cookies scoped to paths, short tokens), mark secrets as never-indexed where the library allows, set explicit header size limits on servers and proxies, and do not try to tune table sizes before you have measured.
Flow control and prioritisation Important
In plain words: flow control stops a fast sender from filling a slow receiver's memory, per stream and per connection; prioritisation tells the server which responses the client needs first.
Common misunderstanding: "HTTP/2 flow control is TCP flow control again." TCP controls the whole connection; HTTP/2 adds a window per stream so one large download cannot starve other streams of the receiver's buffer. With small default windows (65,535 bytes), a large download over a long-RTT link can be throttled by flow control alone; the fix is larger windows, not more connections.
Definition: RFC 9113: each stream and the connection have a send window; DATA frames consume it, WINDOW_UPDATE frames refill it. SETTINGS_INITIAL_WINDOW_SIZE sets the stream window ("The initial value is 2^16-1 (65,535) octets"). The RFC 7540 dependency-tree priority scheme is deprecated: "This update to HTTP/2 deprecates the priority signaling defined in RFC 7540". Its replacement is RFC 9218 Extensible Prioritization, a Priority header (for example priority: u=1, i, urgency 0-7 and an incremental flag) usable in HTTP/2 and HTTP/3, plus PRIORITY_UPDATE frames.
Client (window per stream 64 KiB) Server
1 HEADERS 1 GET /video.mp4 ->
2 HEADERS 3 GET /api/cart priority: u=1 ->
3 <- DATA 1 (64 KiB) ... stream 1 window is now 0
4 <- DATA 3 (cart JSON): stream 3 has its own window
5 WINDOW_UPDATE stream 1 +1 MiB -> (client app read the video bytes)
6 <- DATA 1 continues
7 a client that never reads stream 1 blocks only stream 1, not the connectionReal scenario: a gRPC streaming RPC whose consumer is slow (back-pressure reaches the producer through the window, see Backpressure); a large file download over a 150 ms intercontinental link limited to window/RTT throughput; a browser asking for CSS before images; Cloudflare's "Enhanced HTTP/2 Prioritization" overriding browser hints.
What provides it: Go HTTP2Config.MaxReceiveBufferPerConnection and MaxReceiveBufferPerStream; NGINX http2_recv_buffer_size; Envoy initial_stream_window_size, initial_connection_window_size; quic-go quic.Config stream and connection receive windows.
Fix / how to use it: leave defaults until a test shows window-limited throughput (throughput close to window divided by RTT), then raise per-stream windows for bulk transfers on long-RTT links; send RFC 9218 Priority from clients that care; read response bodies promptly so windows refill.
Head-of-line blocking at every layer Must-know
In plain words: something at the front of a queue that cannot move holds up everything behind it. HTTP has had it at three different layers.
Common misunderstanding: "HTTP/2 solved head-of-line blocking." It solved the HTTP-level version (responses no longer wait for each other) and kept the TCP-level version: when one segment is lost, the kernel withholds all later bytes of the connection, so every stream stalls until the retransmission arrives.
Definition: RFC 9112 9.4 describes HTTP/1.1's version: "a request that takes significant server-side processing and/or transfers very large content would block subsequent requests on the same connection". RFC 9113 admits TCP's. RFC 9000 13 describes how QUIC avoids it: "When a packet loss occurs, only streams with data in that packet are blocked waiting for a retransmission to be received, while other streams can continue making progress."
t (ms) HTTP/1.1 (1 conn) HTTP/2 over TCP HTTP/3 over QUIC
1 0 send A, B, C send A, B, C (streams 1,3,5) send A, B, C (streams 0,4,8)
2 5 B, C ready; wait behind A packet with A2 lost packet with A2 lost
3 10 still waiting B, C bytes arrive but kernel B, C delivered to app
holds them (gap in sequence)
4 60 still waiting retransmit of A2 arrives; A2 retransmitted; only A waited
A, B, C delivered together
5 300 A done; B, C sent - -Real scenario: a mobile app on a train (1-2% loss) where one HTTP/2 connection carrying API calls and images stalls together; a dashboard where one 5 s report request on a single HTTP/1.1 connection delays every widget; this chapter's lab, where fast requests behind a 300 ms one waited about 322 ms on HTTP/1.1 and about 6 ms on HTTP/2.
What prevents it:
| Layer | Who suffers | What removes it |
|---|---|---|
| HTTP/1.1 response order | Every request behind a slow one on the same connection | More connections (browsers used 6 per host), or HTTP/2 |
| TCP byte order | Every HTTP/2 stream on the connection after a loss | HTTP/3 (QUIC streams), or several h2 connections on very lossy links |
| QPACK / HPACK state | HTTP/3 streams referencing unacknowledged table entries | QPACK blocked-streams limit (0 = never block) |
| Application (one slow handler, one lock, one worker) | Everything queued behind it | Timeouts, bulkheads, concurrency limits (Bulkheads) |
Fix / how to use it: for user-facing traffic over lossy links prefer HTTP/3 at the edge; for internal low-loss links HTTP/2 is enough; never put slow and fast requests on one HTTP/1.1 connection in series; and remember queues inside your own service are also head-of-line (Tail Latency).
Server push, 103 Early Hints, preload and preconnect Important
In plain words: the server knows the page will need app.css; push sent the file before the browser asked, Early Hints only tells the browser to fetch it (or to open a connection to a CDN) while the server is still building the page.
Common misunderstanding: "Push is the fast option and hints are the compromise." Push often hurt: it sent bytes the browser already had in cache and competed with the HTML for bandwidth. Chrome measured "only 1.25% of HTTP/2 sites" using it with "mixed results ... without a clear net performance gain and in many cases performance regressions". Hints leave the browser in control.
Definition: HTTP/2 push used PUSH_PROMISE frames and SETTINGS_ENABLE_PUSH; HTTP/3 kept the mechanism (MAX_PUSH_ID, CANCEL_PUSH) but browsers do not use it. RFC 8297: "The 103 (Early Hints) informational status code indicates to the client that the server is likely to send a final response with the header fields included in the informational response." Hints carry Link headers with rel=preload (fetch this resource now, with as=style|script|font|image) or rel=preconnect (open DNS + TCP + TLS to that origin now).
Browser Server
1 GET /dashboard ->
2 <- 103 Early Hints
Link: </build/app.css>; rel=preload; as=style
Link: <https://cdn.example.com>; rel=preconnect
3 starts fetching app.css; opens TLS to cdn.example.com (server still runs SQL)
4 <- 200 OK (HTML, 250 ms later), same Link headers
5 app.css already in memory: first render about one server think-time earlierReal scenario: a server-rendered Laravel page whose controller takes 200 ms of database work; a Go handler that renders a template after calling three services; a CDN (Cloudflare) that caches the Link headers of a page and replays them as 103 for the next visitor; a page that needs a font from another origin.
What provides it:
| Product | Push | Early Hints / preload |
|---|---|---|
| Chrome / Chromium | Disabled by default since Chrome 106 | 103 supported (Cloudflare: "Google Chrome M94 and higher") |
| Firefox | Disabled by default since Firefox 132 | 103 supported for preconnect/preload |
| NGINX | http2_push "obsolete since version 1.25.1" | early_hints directive (1.29.0) decides when an upstream's 103 is "passed to a client" |
| Cloudflare | Not offered | Early Hints feature caches Link headers with preload/preconnect and emits 103 |
Go net/http | No push API in http.Server | w.WriteHeader(http.StatusEarlyHints) after setting Link; "1xx headers are sent immediately" |
| FrankenPHP / Laravel Octane | No | headers_send(103) (FrankenPHP); Laravel's AddLinkHeadersForPreloadedAssets adds Link for Vite assets |
| PHP-FPM | No | Cannot emit 1xx; only Link on the final response |
Fix / how to use it: remove push configuration; send 103 with at most a few critical preload and preconnect links from the handler, before slow work; keep the same Link headers on the final response; never put personalised or authenticated resources in hints that a CDN may cache (Cloudflare warns unauthenticated visitors "may receive a 103 response").
Negotiation and coalescing: ALPN, h2, h2c, connection reuse, 421 Important
In plain words: before any HTTP byte is sent, the client and server agree in the TLS handshake which HTTP version to speak (ALPN). And one HTTP/2 or HTTP/3 connection can serve several hostnames when the certificate and IP allow it.
Common misunderstanding: "If both sides support HTTP/2, they will use it." Only if it is offered in ALPN. In Go, a custom TLSClientConfig or DialContext silently drops h2 unless ForceAttemptHTTP2 is true; behind a TLS-terminating proxy the backend never sees ALPN at all, so the proxy's upstream setting decides.
Definition: ALPN (RFC 7301) is a TLS extension listing protocol IDs: http/1.1, h2, h3. RFC 9113 3.2: "HTTP/2 over TLS uses the "h2" protocol identifier"; cleartext HTTP/2 is h2c, started either by the deprecated Upgrade: h2c ("never widely deployed and is deprecated by this document") or by prior knowledge (section 3.3: the client sends the connection preface directly). RFC 9113 9.1.1 allows reusing a connection for another origin "as long as the origin server is authoritative": same IP for cleartext, and for https "a certificate that is valid for the host in the URI". A server that does not want that sends 421 (Misdirected Request).
Client Server / proxy
1 TLS ClientHello ALPN [h2, http/1.1] SNI api.example.com ->
2 <- ServerHello ALPN h2 cert SAN *.example.com
3 HTTP/2 preface + requests for api.example.com
4 needs img.example.com: same IP from DNS, cert covers it -> reuses the connection (coalescing)
5 <- 421 Misdirected Request (proxy routes by SNI)
6 opens a new connection for img.example.com and retries there
7 Internal hop: Go client with Protocols{UnencryptedHTTP2} sends the h2c preface to http://orders:8080Real scenario: a wildcard certificate on a CDN letting a browser use one connection for www and static; an ingress that routes by SNI and must answer 421 to coalesced requests; Envoy or an AWS ALB talking h2c or h2 to gRPC backends inside a VPC; a Go client that lost HTTP/2 after someone added a custom dialer.
What provides it:
| Product | ALPN / h2 | h2c |
|---|---|---|
Go net/http (1.24+) | Protocols.SetHTTP2(true), ForceAttemptHTTP2 when TLS/dialer customised | Protocols.SetUnencryptedHTTP2(true); "The deprecated "Upgrade: h2c" header is not supported" |
golang.org/x/net/http2/h2c | - | Deprecated: "Set the http.Server Protocols field to use unencrypted HTTP/2 instead" |
| NGINX | http2 on; with ssl | http2 on; on a plain listener (prior knowledge) |
| curl / PHP | CURL_HTTP_VERSION_2TLS (h2 for https, 1.1 for http) | CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE |
| gRPC | Requires h2 | Plaintext gRPC is h2c prior knowledge |
Fix / how to use it: check resp.Proto / CURLINFO_HTTP_VERSION in tests; set ForceAttemptHTTP2 whenever you customise a Go transport; use h2c only between a TLS-terminating proxy and a backend on a private network (or prefer mTLS, see mTLS); make SNI routing and certificate SANs agree or return 421.
HTTP/3 over QUIC: independent streams, connection migration, QPACK Must-know
In plain words: HTTP/3 keeps HTTP/2's ideas (streams, header compression, multiplexing) but runs on QUIC, a transport over UDP that encrypts everything, orders each stream separately and identifies a connection by an ID instead of by IP and port.
Common misunderstanding: "QUIC is UDP, so it is unreliable." QUIC implements retransmission, congestion control and flow control itself (RFC 9000); it is as reliable as TCP per stream. What changes is where it runs (user space, so it evolves without kernel upgrades) and what the network can see (almost nothing beyond connection IDs).
Definition: RFC 9114 abstract: QUIC has "stream multiplexing, per-stream flow control, and low-latency connection establishment". The handshake combines transport and TLS 1.3 (RFC 9001) into one round trip. RFC 9000 9: "The use of a connection ID allows connections to survive changes to endpoint addresses (IP address and port), such as those caused by an endpoint migrating to a new network." HTTP/3 uses ALPN h3, frames on QUIC streams (DATA, HEADERS, SETTINGS, GOAWAY...), and QPACK. Idle connections close after max_idle_timeout ("Idle timeout is disabled when both endpoints omit this transport parameter or specify a value of 0").
Phone (Wi-Fi 192.0.2.10) Edge (h3 on UDP 443)
1 QUIC Initial (TLS ClientHello, ALPN h3) ->
2 <- Handshake (cert) ; 1 RTT total
3 HEADERS on stream 0 (GET /feed), stream 4 (GET /avatar)
4 phone leaves Wi-Fi, now on LTE 198.51.100.7: same connection ID
5 PATH_CHALLENGE / PATH_RESPONSE validate the new path
6 <- streams 0 and 4 continue; no new handshake
7 packet for stream 4 lost: only /avatar waits; /feed keeps arrivingReal scenario: mobile apps on unstable networks that switch between Wi-Fi and LTE; a CDN edge that serves h3 to visitors and h2 to the origin (Cloudflare: "HTTP/3 connection to the origin is not yet supported"); an internal service that gains nothing from QUIC on a lossless data-centre network and pays more CPU.
What provides it:
| Product | HTTP/3 status (docs read for this page) |
|---|---|
Go net/http 1.27 | No HTTP/3; use github.com/quic-go/quic-go/http3 (http3.Server, http3.Transport) |
| quic-go | http3.Server{Addr, Handler, TLSConfig, QUICConfig, Port}, SetQUICHeaders for Alt-Svc, 0-RTT on by default in the server |
| NGINX | ngx_http_v3_module (since 1.25.0, "experimental", not built by default), listen 443 quic reuseport;, http3 on;, quic_retry |
| Cloudflare | Toggle per zone, visitor side only |
| AWS | CloudFront: viewers "must support TLSv1.3 and Server Name Indication (SNI)" and it "supports HTTP/3 connection migration"; ALB lists only routing.http2.enabled (no QUIC termination; inference from the attribute list) |
| curl / PHP | CURL_HTTP_VERSION_3 (PHP 8.4+, libcurl 7.66+ built with an HTTP/3 backend), CURL_HTTP_VERSION_3ONLY |
| FrankenPHP | Serves HTTP/3 (Caddy based) for Laravel Octane |
Fix / how to use it: enable HTTP/3 at the edge (CDN or a QUIC-capable proxy) for user-facing traffic; keep TCP versions on the same hostname; open UDP 443 in security groups and firewalls; leave internal service-to-service traffic on h2 unless you measured a benefit. The QUIC transport itself (congestion control, packet number spaces) is in TCP & UDP.
0-RTT and replay Important
In plain words: a client that talked to the server before can send its first request together with the handshake, saving a full round trip, but an attacker who recorded that first flight can send it again.
Common misunderstanding: "0-RTT is just a faster handshake, safe to switch on everywhere." The early data has no protection against replay: RFC 8470 opens with "Using TLS early data creates an exposure to the possibility of a replay attack." A replayed POST /transfer executes twice.
Definition: TLS 1.3 session resumption with early data (over TCP or inside QUIC). RFC 8470 adds the Early-Data: 1 request header (an intermediary that forwards early data "MUST send it with the Early-Data header field set to "1"") and the 425 (Too Early) status, which tells the client to retry after the handshake completes.
Client (has a session ticket) Edge (0-RTT on) Origin
1 QUIC Initial + 0-RTT: GET /feed -> forwards with Early-Data: 1 -> serves (safe GET)
2 attacker replays the same flight -> forwards again -> same GET, harmless
3 QUIC Initial + 0-RTT: POST /orders -> policy: no 0-RTT for POST
4 <- 425 Too Early
5 retries POST after the handshake completes (1 RTT); not replayableReal scenario: a news app's first GET /feed after opening; a payments API that must reject early data for every state-changing request; a CDN that accepts 0-RTT from browsers and marks requests to the origin.
What provides it:
| Product | 0-RTT behaviour |
|---|---|
| Cloudflare | Off by default; "We support 0-RTT for GET, HEAD, and OPTIONS requests"; adds Early-Data: 1 towards the origin |
| quic-go server | "By default, the http3.Server enables 0-RTT support"; handler checks r.TLS.HandshakeComplete |
| quic-go client | http3.MethodGet0RTT / MethodHead0RTT plus a tls.ClientSessionCache; "Support for the "Early-Data" header field, as well as the "Too Early" status code (425) ... is not yet implemented" |
Go crypto/tls / net/http | quic-go's docs: "Go doesn’t have 0-RTT support, neither in its crypto/tls nor in its net/http implementation" |
| NGINX | ssl_early_data on; (TLS 1.3); for HTTP/3 0-RTT needs OpenSSL 3.5.1+ per the v3 module docs |
Fix / how to use it: enable 0-RTT only for safe methods; in the origin, reject (425) any non-safe request that carries Early-Data: 1 or arrived before the handshake completed; keep idempotency keys on writes anyway.
Discovery: Alt-Svc, the HTTPS DNS record and UDP fallback Important
In plain words: a URL says https://, not "use QUIC", so the client first talks HTTP/2 over TCP, the server says "I also speak h3 on UDP 443", and the next connection tries QUIC; if UDP is blocked, the client stays on TCP.
Common misunderstanding: "Turning on HTTP/3 makes the first visit faster." The first visit usually arrives over TCP because the client has not learned about h3 yet (unless the DNS HTTPS record advertises it); the gain starts on later connections, and only for clients whose networks pass UDP.
Definition: RFC 9114 3.1.1: "An HTTP origin can advertise the availability of an equivalent HTTP/3 endpoint via the Alt-Svc HTTP response header field", for example Alt-Svc: h3=":443"; ma=86400. RFC 7838: an advertisement "is considered fresh for 24 hours from generation of the message" unless ma says otherwise; Alt-Svc: clear withdraws it. RFC 9460 (November 2023) defines the HTTPS DNS record type, which can carry alpn=h3,h2 before the first connection. RFC 9114 3.1: "Connectivity problems (e.g., blocking UDP) can result in a failure to establish a QUIC connection; clients SHOULD attempt to use TCP-based versions of HTTP in this case."
Browser example.com
1 DNS: A/AAAA + HTTPS record (alpn="h3,h2") <- (optional)
2 TCP + TLS, ALPN h2: GET / ->
3 <- 200, Alt-Svc: h3=":443"; ma=86400
4 next navigation: races QUIC to UDP 443 against the existing h2 connection
5 corporate firewall drops UDP: QUIC times out -> keeps using h2 (no user-visible error)
6 home network: QUIC succeeds -> later requests on h3; cache of Alt-Svc lasts 24 hReal scenario: a company VPN that blocks UDP 443 (HTTP/3 silently unused); a CDN that advertises h3 for an origin that only speaks h2; a migration where ma is short (300 s) during a trial so rollback is fast; an L4 load balancer that remaps UDP ports (quic-go's Port field exists exactly for this).
What provides it: NGINX add_header Alt-Svc 'h3=":8443"; ma=86400'; (from its v3 module example); quic-go server.SetQUICHeaders(w.Header()), which writes h3=":443"; ma=2592000; Cloudflare adds the header automatically when HTTP/3 is on (inference from its HTTP/3 toggle; the page read does not show the header); publishing an HTTPS record depends on your DNS provider supporting the RFC 9460 type.
Fix / how to use it: advertise h3 with Alt-Svc on every TCP response, start with a short ma, monitor the protocol mix in access logs (the lab has the query), and never make h3 the only path.
HTTPS everywhere: TLS termination, HSTS, ACME Must-know
In plain words: every hop that crosses a network you do not fully control is encrypted; certificates are issued and renewed by robots; and the site tells browsers never to try plain HTTP again.
Common misunderstanding: "TLS is expensive, so terminate once at the edge and send plain HTTP inside." The CPU cost of TLS 1.3 with session resumption is small next to the risk; zero-trust designs re-encrypt to the origin and between services (mTLS, see mTLS). Where TLS terminates is a design choice about who holds the keys and what each hop can inspect, not about speed.
Definition: TLS termination is the point where TLS is decrypted: the CDN, the load balancer, a sidecar or the application. HSTS (RFC 6797): the Strict-Transport-Security header makes the browser rewrite http:// to https:// for max-age seconds (includeSubDomains extends it; the preload list needs max-age "at least 31536000 seconds (1 year)", includeSubDomains and preload). Browsers ignore the header on plain-HTTP responses. ACME (RFC 8555) is the protocol by which a client proves control of a domain (challenges http-01, dns-01, and tls-alpn-01 from RFC 8737) and receives a certificate. The handshake itself is in TLS in Practice.
Browser CDN / edge (TLS 1) Load balancer (TLS 2) App (TLS 3 or h2c)
1 http://shop.example -> 301 to https (first visit only)
2 https://, ALPN h3/h2 -> terminates with the edge cert (ACME, auto-renewed)
3 re-encrypts to origin cert -> terminates (ACM / ACME cert)
4 -> mTLS or h2c inside a private subnet
5 <- 200 + Strict-Transport-Security: max-age=31536000; includeSubDomains
6 later: user types http://shop.example -> browser upgrades locally, no plain request leavesReal scenario: a shop moving from "TLS at the ALB, HTTP to instances" to end-to-end TLS for PCI scope; an HSTS rollout that broke an internal http:// subdomain because includeSubDomains was added too early (hstspreload.org recommends ramping max-age from 300 s to a week to a month); renewals failing silently after Let's Encrypt shortened lifetimes; X-Forwarded-Proto missing so Laravel generates http:// links behind the load balancer.
What provides it:
| Product | Termination and certificates |
|---|---|
| Cloudflare / CloudFront | Edge certificates managed by the provider; origin certificates or re-encryption to the origin |
| AWS ALB / NLB | ACM certificates, auto-renewed; ALB can re-encrypt to HTTPS targets; NLB can pass TLS through |
| NGINX / HAProxy / Envoy | Certificates from files or SDS; ACME via certbot, acme.sh, cert-manager in Kubernetes |
| Caddy / FrankenPHP | Built-in ACME and HTTPS by default |
| Go | crypto/tls; golang.org/x/crypto/acme/autocert for ACME |
| Laravel | Behind a proxy: trustProxies() so isSecure() and url() see https; HSTS via middleware or the proxy |
| Let's Encrypt | 90-day certificates today; default profile moves to 64 days on 10 February 2027 and 45 days on 16 February 2028; recommends ACME Renewal Information (ARI) |
Fix / how to use it: terminate TLS where certificates are automated and keys are protected; re-encrypt when the next network is shared; redirect HTTP to HTTPS once, then rely on HSTS; ramp max-age before includeSubDomains and preload; alert on certificate expiry; configure trusted proxies so the application knows the original scheme. Design-level PKI and secrets: Cryptography in Practice.
Compression and content negotiation: Accept-Encoding, gzip, Brotli, zstd, Vary Must-know
In plain words: the client lists the compressions it understands, the server picks one and says which, and caches must remember that the answer depends on what the client asked for.
Common misunderstanding: "Compress everything at the highest level." Images, video and already-compressed archives do not shrink; maximum Brotli levels cost a lot of CPU per dynamic response; and compressing secrets next to attacker-controlled text leaks them (BREACH). Pick a coding and level per content type and per static vs dynamic.
Definition: content negotiation (RFC 9110 section 12) chooses a representation from Accept, Accept-Encoding, Accept-Language with q-values (br;q=1.0, gzip;q=0.8, q=0 means "not acceptable"). The server answers with Content-Encoding and must send Vary: Accept-Encoding so caches keep one copy per coding. Codings: gzip (DEFLATE), br (RFC 7932: LZ77 plus Huffman, "efficiency comparable to the best currently available general-purpose compression methods"), zstd (RFC 8878, which "registers a media type, content encoding"; decoders should support windows of at least 8 MB). A compressed body is a different representation, so a strong ETag must differ per coding (weak ETags are common).
Client Server / CDN
1 GET /app.js Accept-Encoding: gzip, deflate, br, zstd ->
2 <- 200 Content-Encoding: zstd
Vary: Accept-Encoding
ETag: W/"app-9f1c"
3 old client: Accept-Encoding: gzip ->
4 <- 200 Content-Encoding: gzip (separate cache entry)
5 client sends no Accept-Encoding -> identity (uncompressed)Real scenario: a 1 MB JSON API response that drops to about 100 KB with gzip (text typically compresses 5-10x; measure your payloads); static bundles precompressed with Brotli at build time; a CDN that serves zstd to Chrome and gzip to curl; a cache that served gzip bytes to a client that did not ask for them because Vary was missing.
What provides it:
| Product | gzip | Brotli | zstd |
|---|---|---|---|
| Go stdlib | compress/gzip; Transport asks for gzip and decodes transparently unless DisableCompression | Third-party package | Third-party package (Go stdlib has none in 1.27) |
| NGINX | gzip on; | ngx_brotli module (third-party) | Third-party module |
| Cloudflare | Yes | Yes (to visitors) | Yes (to visitors) |
| FrankenPHP / Caddy | Yes | Yes | Yes (Octane docs: "Brotli, and Zstandard compression") |
| curl / Guzzle / Laravel | CURLOPT_ENCODING => '' advertises every coding libcurl was built with and decodes | If libcurl built with brotli | If libcurl built with zstd |
Fix / how to use it: compress text (HTML, CSS, JS, JSON, SVG) at the edge or proxy; precompress static assets with Brotli or zstd; keep gzip as the universal fallback; always add Vary: Accept-Encoding; skip compression for images and for responses that mix secrets with reflected input. Algorithms: Compression.
Conditional requests and caching headers: ETag, 304, Cache-Control Must-know
In plain words: the server labels each version of a resource (ETag or Last-Modified); the client sends the label back; if nothing changed the server answers 304 Not Modified with no body.
Common misunderstanding: "Cache-Control: no-cache means do not cache." It means "store, but revalidate before every use"; no-store means do not store. And a 304 still costs a round trip: freshness (max-age) avoids the request, validation (ETag) only avoids the body.
Definition: RFC 9110 section 13 defines If-None-Match (ETag, weak comparison for GET), If-Modified-Since, If-Match and If-Unmodified-Since (optimistic concurrency for writes, 412 Precondition Failed), and If-Range. 304: "a conditional GET or HEAD request has been received and would have resulted in a 200 (OK) response if it were not for the fact that the condition evaluated to false". RFC 9111 defines caches and Cache-Control directives: max-age, s-maxage (shared caches), public, private, no-cache, no-store, must-revalidate, immutable, stale-while-revalidate. Cache design (CDN tiers, invalidation, stampedes) is in Caching and CDNs.
Client API (products.version = 7)
1 GET /products/1 ->
2 <- 200 ETag: "p1-v7" Cache-Control: public, max-age=60
3 within 60 s: served from cache, no request at all
4 after 60 s: GET /products/1 If-None-Match: "p1-v7" ->
5 <- 304 Not Modified (no body, same ETag)
6 admin updates price: version 8
7 GET /products/1 If-None-Match: "p1-v7" -> 200 ETag: "p1-v8" + new body
8 PUT /products/1 If-Match: "p1-v7" (stale) -> 412 Precondition Failed (lost update avoided)Real scenario: a mobile app polling a catalogue every minute (304s save bandwidth and battery); a CDN serving /pricing for 5 minutes with s-maxage=300 and revalidating with ETag; two admins editing the same product where If-Match prevents the second from overwriting the first (Optimistic Locking).
What provides it:
| Product | Validators | Notes |
|---|---|---|
Go net/http | http.ServeContent / http.FileServer handle If-None-Match, If-Modified-Since, If-Range | Custom handlers compare ETags themselves (this page's server package) |
| Laravel | cache.headers middleware: "If etag is specified in the list of directives, an xxh128 hash of the response content will automatically be set as the ETag identifier"; Symfony isNotModified() | Hashing the body still renders the page; use a version column to skip work |
| NGINX | etag on; for static files, proxy_cache_revalidate on; | |
| Cloudflare / CloudFront | Honour Cache-Control, s-maxage, revalidate with origin | CDN-Cache-Control on Cloudflare |
Fix / how to use it: derive ETags from a version column or updated_at, not from hashing a rendered body, so a 304 skips the expensive work:
-- Version column that feeds the ETag and If-Match checks
CREATE TABLE products (
id bigint PRIMARY KEY,
name text NOT NULL,
price_cents integer NOT NULL,
version integer NOT NULL DEFAULT 1,
updated_at timestamptz NOT NULL DEFAULT now()
);
-- 304 path: read only the validator, not the row
SELECT version FROM products WHERE id = $1;
-- If-Match path: conditional write, 0 rows updated -> 412 Precondition Failed
UPDATE products
SET price_cents = $2, version = version + 1, updated_at = now()
WHERE id = $1 AND version = $3;Range requests and 206 Good to know
In plain words: ask for bytes 1,000,000 to 1,999,999 of a file instead of the whole file, to resume a download, seek in a video or fetch chunks in parallel.
Common misunderstanding: "Ranges are a CDN feature." They are core HTTP (RFC 9110 section 14) and every hop must agree: a proxy that compresses on the fly breaks byte ranges, which is why compressing middleware should skip requests with Range.
Definition: the client sends Range: bytes=0-99; the server answers 206 Partial Content with Content-Range: bytes 0-99/8000, or 416 Range Not Satisfiable when the range lies outside the file, or 200 with the full body if it ignores ranges. Accept-Ranges: bytes advertises support. If-Range makes the range conditional on an ETag or date so a resumed download does not splice two versions.
Downloader Object storage / server
1 HEAD /backup.tar -> 200 Content-Length: 4000000000, Accept-Ranges: bytes, ETag "b7"
2 GET Range: bytes=0-999999999 If-Range: "b7" -> 206 Content-Range: bytes 0-999999999/4000000000
3 GET Range: bytes=1000000000-1999999999 (parallel) -> 206
4 connection drops at 1.4 GB: resume with Range: bytes=1400000000- If-Range: "b7"
5 file replaced meanwhile (ETag "b8"): server sends 200 with the full new file instead
6 GET Range: bytes=9000000000- -> 416 Range Not SatisfiableReal scenario: video players seeking (HLS and DASH segments, MP4 byte ranges); resumable downloads of large exports; S3 multipart downloads with parallel ranges (Object Storage); PDF viewers loading page ranges.
What provides it: Go http.ServeContent (Range, If-Range, 206, 416, multipart/byteranges); NGINX for static files and slice module for caching large files in pieces; Amazon S3 GetObject with Range; Laravel response()->file() / download() through Symfony BinaryFileResponse, which supports ranges.
Fix / how to use it: serve large files through a component that implements ranges (object storage, CDN, ServeContent), not hand-written streaming; disable on-the-fly compression for range requests; send ETag so If-Range works.
Timeouts: connect, TLS, header, body, write, idle Must-know
In plain words: every phase of an HTTP exchange can hang, and each needs its own limit; on keep-alive connections the idle timeouts on the two ends must be ordered so the client gives up on an idle connection before the server closes it.
Common misunderstanding: "One overall timeout is enough." A total timeout of 30 s does not stop a slowloris client from holding a server connection open by sending one header byte every 10 s; that needs a header timeout. And a 30 s total timeout on the client cannot tell "server is slow" from "connection was dead before we started".
Definition:
| Timeout | Side | Protects against | Go knob | Others |
|---|---|---|---|---|
| Connect | Client | Unreachable host, SYN dropped | net.Dialer.Timeout | curl CURLOPT_CONNECTTIMEOUT_MS; Laravel connectTimeout() (default 10 s) |
| TLS handshake | Client | Stuck handshake | Transport.TLSHandshakeTimeout | |
| Response header (time to first byte) | Client | Server accepted but never answers | Transport.ResponseHeaderTimeout | Envoy route timeout, NGINX proxy_read_timeout (between reads) |
| Total | Client | Everything, including slow body | Client.Timeout or context deadline | Laravel timeout() (default 30 s); curl CURLOPT_TIMEOUT_MS |
| Request header | Server | Slowloris | Server.ReadHeaderTimeout | NGINX client_header_timeout (60 s) |
| Request body | Server | Slow uploads | Server.ReadTimeout, http.ResponseController.SetReadDeadline | NGINX client_body_timeout (60 s, between reads) |
| Response write | Server | Slow readers | Server.WriteTimeout | NGINX send_timeout |
| Idle (keep-alive) | Both | Dead or forgotten connections | Server IdleTimeout; client Transport.IdleConnTimeout | NGINX keepalive_timeout (75 s); AWS ALB idle timeout (60 s); QUIC max_idle_timeout |
| HTTP/2 health | Both | Silently dropped connections (NAT, LB) | HTTP2Config.SendPingTimeout, PingTimeout | gRPC keepalive pings |
Go client (IdleConnTimeout 55 s) AWS ALB (idle 60 s) Backend (keep-alive 75 s)
1 request 1 on connection C -> ALB connection D to backend ->
2 ... 58 s idle ...
3 client closes C at 55 s (first; no race)
4 wrong order: client idle 90 s, ALB idle 60 s: ALB closes at 60 s, client sends at 61 s
on the dead socket -> "server closed idle connection" / reset; GET retried, POST fails
5 behind the ALB: backend keep-alive must be LONGER than the ALB's 60 s, or the ALB
reuses a connection the backend just closed -> 502 to the userReal scenario: a Go service on AWS behind an ALB with IdleTimeout: 30s producing sporadic 502s; a PHP-FPM pool exhausted by a dependency that hangs without a timeout; a slowloris attack against a server with no header timeout; a mobile client whose NAT drops idle QUIC connections after 30 s, fixed with KeepAlivePeriod.
What provides it: see the table; the deadline-propagation side (how much of the user's budget each hop may use) is in Timeouts, Retries & Jitter.
Fix / how to use it: set every timeout explicitly (Go's zero values mean "none"); order idle timeouts client < load balancer < backend; keep the header timeout short (5-10 s) and the body/write timeouts sized for the largest legitimate transfer, or set them per handler with http.ResponseController.
Client connection pools and sizing Must-know
In plain words: a pool keeps warm connections per host; size it to the concurrency you actually send, and bound it so one slow host cannot use every socket.
Common misunderstanding: "Go's default client pools connections, so I am done." It does, but DefaultMaxIdleConnsPerHost is 2: a service sending 50 concurrent HTTP/1.1 requests to one host keeps 2 idle connections and closes 48 after each burst, then reopens them, burning handshakes and TIME_WAIT entries. With HTTP/2 the opposite surprise appears: one connection carries everything, so per-connection limits on the server or load balancer cap throughput.
Definition: for HTTP/1.1, pool size per host should be about the steady in-flight concurrency (Little's law: requests per second x latency; 200 rps x 0.05 s = 10 connections, a back-of-envelope estimate). For HTTP/2, one connection per host serves up to the peer's SETTINGS_MAX_CONCURRENT_STREAMS; Go's Transport opens another connection when all are at the limit. MaxConnsPerHost is a bulkhead: dials block when the limit is reached ("On limit violation, dials will block").
200 rps to billing, p50 latency 50 ms, HTTP/1.1
1 in flight ~ 200 x 0.05 = 10 connections needed
2 MaxIdleConnsPerHost = 2 (Go default): after each burst 8 connections close
3 next burst: 8 new TCP + TLS handshakes (2 RTT each), 8 more TIME_WAIT sockets
4 MaxIdleConnsPerHost = 64: 10 stay warm, zero handshakes in steady state
5 billing degrades to 2 s latency: in flight 400; MaxConnsPerHost = 50 caps sockets,
extra requests wait for a connection instead of exhausting file descriptorsReal scenario: an API gateway with a default Go client opening thousands of connections per minute to one backend; Laravel Horizon workers each holding their own connections (pool per process); PHP-FPM with 50 workers x 4 upstreams = up to 200 connections per server, none reused across requests; a database-style connection storm on a backend after a deploy (compare Connection Pooling).
What provides it:
| Product | Pool knobs | Defaults |
|---|---|---|
Go http.Transport | MaxIdleConns, MaxIdleConnsPerHost, MaxConnsPerHost, IdleConnTimeout | 100 / 2 / unlimited / 90 s (DefaultTransport) |
libcurl / PHP curl_multi | CURLMOPT_MAX_HOST_CONNECTIONS, CURLMOPT_MAX_TOTAL_CONNECTIONS, CURLMOPT_MAX_CONCURRENT_STREAMS, CURLMOPT_PIPELINING | unlimited / unlimited / 100 / CURLPIPE_MULTIPLEX |
| Guzzle | CurlMultiHandler with options (CURLMOPT_*), pool concurrency | Handler per client |
| Laravel HTTP client | Http::pool(..., concurrency: N), Http::batch() | One shared handler per pool; "concurrency argument ... determines the maximum number of HTTP requests that may be concurrently in-flight" |
| NGINX upstream | keepalive N, keepalive_requests, keepalive_timeout | 32 per worker (1.29.7+), 1000, 60 s |
| Envoy | Cluster circuit breakers max_connections, max_requests; max_concurrent_streams per h2 connection | See Envoy's cluster docs (not re-read for this page) |
Fix / how to use it: one client per upstream with MaxIdleConnsPerHost near expected concurrency and MaxConnsPerHost as a bulkhead; for PHP-FPM accept per-request pools and fan out with Http::pool, or move to Octane, or send through a local proxy that keeps upstream connections warm; watch new-connection rate, not just request rate.
gRPC and WebSockets over HTTP/2 Good to know
In plain words: gRPC is "RPC calls as HTTP/2 streams with Protobuf bodies and trailers"; WebSockets over HTTP/2 (RFC 8441) run a WebSocket inside one HTTP/2 stream instead of taking over a whole TCP connection.
Common misunderstanding: "gRPC works through any HTTP proxy." gRPC needs end-to-end HTTP/2 including trailers (grpc-status arrives in trailers) and the te: trailers header; a proxy that downgrades to HTTP/1.1 breaks it. Browsers cannot speak raw gRPC (no trailer access), hence gRPC-Web.
Definition: the gRPC wire protocol (grpc/grpc PROTOCOL-HTTP2.md) sends :method POST, :path /Service/Method, content-type: application/grpc, te: trailers, optional grpc-timeout, length-prefixed messages in DATA frames and status in trailers. RFC 8441 "defines a mechanism for running the WebSocket Protocol (RFC 6455) over a single stream of an HTTP/2 connection": the server sends SETTINGS_ENABLE_CONNECT_PROTOCOL = 1, the client sends an extended CONNECT with :protocol = websocket. RFC 9220 does the same for HTTP/3.
Client Server
1 (h2 connection already open, SETTINGS_ENABLE_CONNECT_PROTOCOL=1 received)
2 HEADERS stream 7: :method CONNECT :protocol websocket :path /chat ->
3 <- HEADERS stream 7: :status 200
4 DATA frames on stream 7 carry WebSocket frames; streams 1, 3, 5 keep serving REST
5 gRPC: HEADERS stream 9 POST /orders.Orders/Get te: trailers grpc-timeout: 800m
6 <- HEADERS :status 200, DATA (message), HEADERS (trailers: grpc-status 0)Real scenario: internal service calls with gRPC over h2c or mTLS h2 (gRPC & Protobuf); a chat feature sharing the page's HTTP/2 connection to the CDN instead of opening a second TCP connection (Real-Time Communication); an L4 load balancer that sends all gRPC streams of a client to one backend because the connection lives for hours.
What provides it: grpc-go (its own HTTP/2 transport, not net/http); Envoy, NGINX grpc_pass, AWS ALB gRPC target groups; RFC 8441 support in browsers, proxies and servers varies by product and version (check yours), so most WebSocket deployments still use the HTTP/1.1 Upgrade handshake (101 Switching Protocols). Laravel Reverb serves WebSockets over the classic upgrade.
Fix / how to use it: keep gRPC hops on h2 end to end, balance per request at L7 (or client-side), set grpc-timeout deadlines; treat WebSocket over h2 as an optimisation, not a requirement.
Mechanics
HTTP/2 and HTTP/3 frame types
| Frame | HTTP/2 type | HTTP/3 type | Purpose |
|---|---|---|---|
| DATA | 0x00 | 0x00 | Body bytes; END_STREAM flag ends a direction (HTTP/2) |
| HEADERS | 0x01 | 0x01 | Compressed header block (HPACK / QPACK) |
| PRIORITY | 0x02 (deprecated) | - | RFC 7540 tree; replaced by RFC 9218 |
| RST_STREAM | 0x03 | QUIC RESET_STREAM | Abort one stream with an error code |
| SETTINGS | 0x04 | 0x04 | Connection parameters, sent first |
| PUSH_PROMISE | 0x05 | 0x05 | Server push (unused by browsers) |
| PING | 0x06 | QUIC PING | Liveness and RTT |
| GOAWAY | 0x07 | 0x07 | Graceful shutdown; last processed stream ID |
| WINDOW_UPDATE | 0x08 | QUIC MAX_DATA / MAX_STREAM_DATA | Flow-control credit |
| CONTINUATION | 0x09 | - | More header block |
Settings and defaults
| Setting | Meaning | Default / recommendation |
|---|---|---|
SETTINGS_HEADER_TABLE_SIZE (0x01) | HPACK dynamic table size | 4,096 octets |
SETTINGS_ENABLE_PUSH (0x02) | Allow PUSH_PROMISE | Browsers send 0 or ignore push |
SETTINGS_MAX_CONCURRENT_STREAMS (0x03) | Streams the peer may open | Unlimited initially; recommended at least 100; NGINX 128; Go server "at least 100" (this page uses 250) |
SETTINGS_INITIAL_WINDOW_SIZE (0x04) | Per-stream flow-control window | 65,535 octets |
SETTINGS_MAX_FRAME_SIZE (0x05) | Largest frame payload | 16,384 octets initially |
SETTINGS_MAX_HEADER_LIST_SIZE (0x06) | Advisory header size limit | Unlimited initially |
SETTINGS_ENABLE_CONNECT_PROTOCOL (0x08, RFC 8441) | Extended CONNECT for WebSockets | 0 |
QUIC max_idle_timeout | Idle close | Disabled if both omit it; quic-go MaxIdleTimeout |
QUIC initial_max_streams_bidi | Concurrent request streams | Implementation default (quic-go MaxIncomingStreams) |
SETTINGS_QPACK_MAX_TABLE_CAPACITY, SETTINGS_QPACK_BLOCKED_STREAMS | QPACK table and blocking | 0 (no dynamic table, never block) |
Error codes
| HTTP/2 code | HTTP/3 code | Meaning | What the client does |
|---|---|---|---|
NO_ERROR 0x00 | H3_NO_ERROR 0x0100 | Graceful close (often with GOAWAY) | Retry unprocessed streams on a new connection |
PROTOCOL_ERROR 0x01 | H3_GENERAL_PROTOCOL_ERROR 0x0101 | Peer broke the protocol | Bug; do not retry blindly |
INTERNAL_ERROR 0x02 | H3_INTERNAL_ERROR 0x0102 | Implementation error | Retry only if idempotent |
FLOW_CONTROL_ERROR 0x03 | QUIC FLOW_CONTROL_ERROR | Window violated | Bug |
SETTINGS_TIMEOUT 0x04 | H3_MISSING_SETTINGS 0x010a | SETTINGS not acknowledged / missing | Reconnect |
STREAM_CLOSED 0x05 | H3_FRAME_UNEXPECTED 0x0105 | Frame on a closed stream | Bug |
FRAME_SIZE_ERROR 0x06 | H3_FRAME_ERROR 0x0106 | Bad frame size | Bug |
REFUSED_STREAM 0x07 | H3_REQUEST_REJECTED 0x010b | Not processed at all | Safe to retry, even POST |
CANCEL 0x08 | H3_REQUEST_CANCELLED 0x010c | Stream no longer needed | Nothing (client cancelled) |
COMPRESSION_ERROR 0x09 | QPACK decompression errors | Header table broken | Reconnect |
CONNECT_ERROR 0x0a | H3_CONNECT_ERROR 0x010f | Tunnel failed | Surface |
ENHANCE_YOUR_CALM 0x0b | H3_EXCESSIVE_LOAD 0x0107 | Peer thinks you are abusive | Back off |
INADEQUATE_SECURITY 0x0c | - | TLS too weak for h2 | Fix TLS config |
HTTP_1_1_REQUIRED 0x0d | H3_VERSION_FALLBACK 0x0110 | Use another version | Retry over HTTP/1.1 |
Knobs by product
| Product | Knob | Default | Recommendation |
|---|---|---|---|
| Go client | MaxIdleConnsPerHost | 2 | Near expected concurrency per host (this page: 64) |
| Go client | ForceAttemptHTTP2 | true in DefaultTransport, false in a new Transport | true whenever you set DialContext or TLSClientConfig |
| Go client | ResponseHeaderTimeout, Client.Timeout | none | 2 s / 5 s for internal calls (adjust to SLO) |
| Go server | ReadHeaderTimeout, IdleTimeout | none (falls back to ReadTimeout) | 5 s / 120 s |
| NGINX | keepalive_timeout, client_header_timeout, client_body_timeout | 75 s, 60 s, 60 s | Keep above the LB's idle timeout when NGINX is behind an LB |
| NGINX | proxy_http_version | 1.1 (since 1.29.7; 1.0 before) | 1.1 or 2 (1.29.4+) for upstream keep-alive |
| AWS ALB | idle_timeout.timeout_seconds | 60 | Backend keep-alive longer than this |
| Laravel HTTP client | timeout(), connectTimeout() | 30 s, 10 s | Set both per upstream |
| libcurl | CURLMOPT_PIPELINING | CURLPIPE_MULTIPLEX | Leave; add CURLOPT_PIPEWAIT to prefer one h2 connection |
Error messages you will actually see
| Where | Message | Meaning |
|---|---|---|
| Go client | net/http: timeout awaiting response headers | ResponseHeaderTimeout fired |
| Go client | context deadline exceeded (Client.Timeout exceeded while awaiting headers) | Client.Timeout fired |
| Go client | net/http: TLS handshake timeout | TLSHandshakeTimeout fired |
| Go client | http: server closed idle connection | Server closed a pooled connection; idle timeouts mis-ordered |
| Go client | http2: server sent GOAWAY and closed the connection | Server shutdown or connection limit; unprocessed streams retried |
| Go server log | http: TLS handshake error from 192.0.2.10:51234: ... | Client spoke plain HTTP to TLS, or bad certificate |
| Go server | http: superfluous response.WriteHeader call | Handler wrote headers twice (common with wrapping middleware) |
| curl / Laravel | cURL error 28: Operation timed out | timeout() or connectTimeout() exceeded (ConnectionException) |
| curl | HTTP/2 stream 1 was not closed cleanly: PROTOCOL_ERROR (err 1) | Peer reset the stream |
| NGINX | upstream prematurely closed connection while reading response header from upstream | Backend closed a keep-alive connection; often timeout ordering |
| AWS ALB / NGINX | 502 Bad Gateway | Upstream connection failed or closed early |
| Browser DevTools | net::ERR_HTTP2_PROTOCOL_ERROR, ERR_QUIC_PROTOCOL_ERROR | Stream reset; often a proxy or header problem |
Go
The Go module (academy/http-evolution) uses the standard library for HTTP/1.1, HTTP/2 and h2c (Go 1.24 Protocols and HTTP2Config) and github.com/quic-go/quic-go v0.59.0 for HTTP/3 (the newest quic-go release whose go.mod still says go 1.24). All tests run offline on loopback.
Before
A client that compiles, works on a laptop and fails under load: a Transport per call, no timeouts, a custom TLS config that silently disables h2, and bodies not drained on errors.
// Package before shows a typical first HTTP client: it works on a laptop
// and falls over under load. Nothing here is broken code; it is bad design.
package before
import (
"crypto/tls"
"errors"
"fmt"
"net/http"
)
// FetchStatus calls url and returns the status line.
//
// Problems, in the order they hurt in production:
// 1. A new Transport per call: every call pays TCP + TLS handshakes,
// because the idle-connection pool dies with the Transport.
// 2. No timeouts at all: a slow server holds the goroutine forever.
// 3. A custom TLSClientConfig without ForceAttemptHTTP2 silently
// disables HTTP/2 negotiation (ALPN offers only http/1.1).
// 4. On non-200 the body is closed without being read, so even a
// shared Transport could not reuse the connection.
func FetchStatus(url string, roots *tls.Config) (string, error) {
client := &http.Client{
Transport: &http.Transport{TLSClientConfig: roots},
}
resp, err := client.Get(url)
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", errors.New(resp.Status)
}
return fmt.Sprintf("%s %s", resp.Proto, resp.Status), nil
}After
A tuned, shared client. Pool sized per host, ForceAttemptHTTP2 because the dialer and TLS config are custom, every phase bounded, HTTP/2 health pings, and a Get helper that always drains the body so the connection returns to the pool. Stats counts new vs reused connections through httptrace.
// Package client builds one long-lived, tuned HTTP client per upstream.
package client
import (
"context"
"crypto/tls"
"fmt"
"io"
"net"
"net/http"
"net/http/httptrace"
"sync/atomic"
"time"
)
// Config holds the knobs that matter for one upstream service.
type Config struct {
// Pool sizing. For HTTP/1.1, MaxIdleConnsPerHost should be close to the
// steady-state concurrency towards that host; the Go default is 2.
MaxIdleConns int
MaxIdleConnsPerHost int
MaxConnsPerHost int // 0 = unlimited; a bulkhead when > 0
// Keep idle connections for less time than the server or load balancer
// does (NGINX keepalive_timeout 75s, AWS ALB idle timeout 60s), so the
// client closes first and never writes into a half-closed socket.
IdleConnTimeout time.Duration
DialTimeout time.Duration // TCP connect
TCPKeepAlive time.Duration // OS-level keep-alive probes
TLSHandshakeTimeout time.Duration
ResponseHeaderTimeout time.Duration // header timeout (time to first byte)
RequestTimeout time.Duration // whole exchange, including the body
// HTTP/2 health check: ping a connection after this much silence.
PingAfter time.Duration
TLS *tls.Config // nil means system roots
}
// Defaults are a reasonable starting point for service-to-service calls.
func Defaults() Config {
return Config{
MaxIdleConns: 200,
MaxIdleConnsPerHost: 64,
MaxConnsPerHost: 0,
IdleConnTimeout: 55 * time.Second,
DialTimeout: 2 * time.Second,
TCPKeepAlive: 30 * time.Second,
TLSHandshakeTimeout: 3 * time.Second,
ResponseHeaderTimeout: 2 * time.Second,
RequestTimeout: 5 * time.Second,
PingAfter: 15 * time.Second,
}
}
// NewTransport returns a Transport that pools connections, negotiates h2
// through ALPN even with a custom TLS config, and bounds every phase.
func NewTransport(c Config) *http.Transport {
dialer := &net.Dialer{Timeout: c.DialTimeout, KeepAlive: c.TCPKeepAlive}
protocols := new(http.Protocols)
protocols.SetHTTP1(true)
protocols.SetHTTP2(true) // offered as "h2" in ALPN on https:// URLs
return &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: dialer.DialContext,
TLSClientConfig: c.TLS,
ForceAttemptHTTP2: true, // needed because DialContext/TLS are custom
Protocols: protocols,
MaxIdleConns: c.MaxIdleConns,
MaxIdleConnsPerHost: c.MaxIdleConnsPerHost,
MaxConnsPerHost: c.MaxConnsPerHost,
IdleConnTimeout: c.IdleConnTimeout,
TLSHandshakeTimeout: c.TLSHandshakeTimeout,
ResponseHeaderTimeout: c.ResponseHeaderTimeout,
ExpectContinueTimeout: time.Second,
HTTP2: &http.HTTP2Config{
SendPingTimeout: c.PingAfter,
PingTimeout: 5 * time.Second,
},
}
}
// New returns a Client; create it once and share it.
func New(c Config) *http.Client {
return &http.Client{Transport: NewTransport(c), Timeout: c.RequestTimeout}
}
// Stats counts what happened on the wire.
type Stats struct {
NewConns atomic.Int64
ReusedConns atomic.Int64
}
// Trace attaches an httptrace hook that records connection reuse.
func (s *Stats) Trace(ctx context.Context) context.Context {
return httptrace.WithClientTrace(ctx, &httptrace.ClientTrace{
GotConn: func(info httptrace.GotConnInfo) {
if info.Reused {
s.ReusedConns.Add(1)
} else {
s.NewConns.Add(1)
}
},
})
}
// Get performs a GET and always drains the body (up to max bytes) so the
// connection goes back to the pool even for error statuses.
func Get(ctx context.Context, c *http.Client, url string, max int64) (int, string, []byte, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return 0, "", nil, err
}
resp, err := c.Do(req)
if err != nil {
return 0, "", nil, fmt.Errorf("get %s: %w", url, err)
}
defer resp.Body.Close()
body, err := io.ReadAll(io.LimitReader(resp.Body, max))
if err != nil {
return resp.StatusCode, resp.Proto, nil, err
}
// Anything beyond max is discarded so the stream or connection is reusable.
_, _ = io.Copy(io.Discard, resp.Body)
return resp.StatusCode, resp.Proto, body, nil
}Tests that count connections. The "before" client opens 10 connections for 10 calls and stays on HTTP/1.1; the tuned client reuses one; 50 concurrent requests share one HTTP/2 connection; HTTP/1.1 needs a connection per in-flight request (capped by MaxConnsPerHost); a stuck server trips ResponseHeaderTimeout.
package client
import (
"context"
"crypto/tls"
"crypto/x509"
"net"
"net/http"
"net/http/httptest"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"academy/http-evolution/before"
)
// newTLSServer starts an HTTPS test server and counts accepted connections.
func newTLSServer(t *testing.T, h2 bool, h http.Handler) (*httptest.Server, *atomic.Int64, *tls.Config) {
t.Helper()
var conns atomic.Int64
srv := httptest.NewUnstartedServer(h)
srv.EnableHTTP2 = h2
srv.Config.ConnState = func(_ net.Conn, s http.ConnState) {
if s == http.StateNew {
conns.Add(1)
}
}
srv.StartTLS()
t.Cleanup(srv.Close)
pool := x509.NewCertPool()
pool.AddCert(srv.Certificate())
return srv, &conns, &tls.Config{RootCAs: pool}
}
func ok(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte("ok")) }
func TestBeforeOpensOneConnectionPerCall(t *testing.T) {
srv, conns, roots := newTLSServer(t, true, http.HandlerFunc(ok))
for range 10 {
status, err := before.FetchStatus(srv.URL, roots)
if err != nil {
t.Fatal(err)
}
if !strings.HasPrefix(status, "HTTP/1.1") {
t.Fatalf("custom TLS config without ForceAttemptHTTP2 should stay on HTTP/1.1, got %q", status)
}
}
if got := conns.Load(); got != 10 {
t.Fatalf("want 10 connections (one per call), got %d", got)
}
}
func TestTunedClientReusesOneConnection(t *testing.T) {
srv, conns, roots := newTLSServer(t, false, http.HandlerFunc(ok)) // HTTP/1.1 only
cfg := Defaults()
cfg.TLS = roots
c := New(cfg)
var st Stats
for range 10 {
code, proto, _, err := Get(st.Trace(context.Background()), c, srv.URL, 1<<20)
if err != nil || code != 200 || proto != "HTTP/1.1" {
t.Fatalf("code=%d proto=%s err=%v", code, proto, err)
}
}
if conns.Load() != 1 || st.ReusedConns.Load() != 9 {
t.Fatalf("want 1 connection and 9 reuses, got %d and %d", conns.Load(), st.ReusedConns.Load())
}
}
func TestHTTP2MultiplexesConcurrentRequests(t *testing.T) {
slow := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
time.Sleep(20 * time.Millisecond)
ok(w, r)
})
srv, conns, roots := newTLSServer(t, true, slow)
cfg := Defaults()
cfg.TLS = roots
c := New(cfg)
// Warm up: the first request learns via ALPN that the server speaks h2.
if _, proto, _, err := Get(context.Background(), c, srv.URL, 1<<20); err != nil || proto != "HTTP/2.0" {
t.Fatalf("proto=%s err=%v", proto, err)
}
var wg sync.WaitGroup
for range 50 {
wg.Add(1)
go func() {
defer wg.Done()
if _, proto, _, err := Get(context.Background(), c, srv.URL, 1<<20); err != nil || proto != "HTTP/2.0" {
t.Errorf("proto=%s err=%v", proto, err)
}
}()
}
wg.Wait()
if got := conns.Load(); got != 1 {
t.Fatalf("50 concurrent h2 requests should share 1 connection, got %d", got)
}
}
func TestHTTP1ConcurrencyNeedsManyConnections(t *testing.T) {
slow := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
time.Sleep(20 * time.Millisecond)
ok(w, r)
})
srv, conns, roots := newTLSServer(t, false, slow)
cfg := Defaults()
cfg.TLS = roots
cfg.MaxConnsPerHost = 8 // bulkhead: at most 8 sockets to this host
c := New(cfg)
var wg sync.WaitGroup
for range 50 {
wg.Add(1)
go func() {
defer wg.Done()
if _, _, _, err := Get(context.Background(), c, srv.URL, 1<<20); err != nil {
t.Error(err)
}
}()
}
wg.Wait()
if got := conns.Load(); got < 2 || got > 8 {
t.Fatalf("HTTP/1.1 needs one connection per in-flight request, capped at 8; got %d", got)
}
}
func TestResponseHeaderTimeout(t *testing.T) {
stuck := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
select {
case <-time.After(time.Second):
case <-r.Context().Done():
}
})
srv, _, roots := newTLSServer(t, false, stuck)
cfg := Defaults()
cfg.TLS = roots
cfg.ResponseHeaderTimeout = 50 * time.Millisecond
_, _, _, err := Get(context.Background(), New(cfg), srv.URL, 1<<20)
if err == nil || !strings.Contains(err.Error(), "timeout awaiting response headers") {
t.Fatalf("want header timeout, got %v", err)
}
}A server with every timeout, h2 and opt-in h2c, HSTS and Alt-Svc middleware, Accept-Encoding negotiation with q-values, gzip with a weakened ETag, conditional GET with 304, range requests through http.ServeContent, and 103 Early Hints.
// Package server is an HTTP/1.1 + HTTP/2 server with explicit timeouts,
// h2c for trusted hops, HSTS, Alt-Svc, content negotiation, conditional
// requests, range requests and 103 Early Hints.
package server
import (
"bytes"
"compress/gzip"
"fmt"
"net/http"
"strconv"
"strings"
"sync"
"time"
)
// New returns a server with every timeout set. h2c enables HTTP/2 with
// prior knowledge on cleartext ports (RFC 9113 section 3.3): use it only
// behind a TLS-terminating proxy on a trusted network.
func New(addr string, h http.Handler, h2c bool) *http.Server {
p := new(http.Protocols)
p.SetHTTP1(true)
p.SetHTTP2(true) // "h2" via ALPN when served with TLS
p.SetUnencryptedHTTP2(h2c) // "h2c" prior knowledge on plain TCP
return &http.Server{
Addr: addr,
Handler: h,
Protocols: p,
ReadHeaderTimeout: 5 * time.Second, // header timeout: stops slowloris
ReadTimeout: 30 * time.Second, // whole request incl. body
WriteTimeout: 30 * time.Second, // whole response
IdleTimeout: 120 * time.Second, // keep-alive idle timeout
MaxHeaderBytes: 64 << 10,
HTTP2: &http.HTTP2Config{
MaxConcurrentStreams: 250,
SendPingTimeout: 30 * time.Second,
},
}
}
// Secure adds HSTS on TLS responses and advertises HTTP/3 via Alt-Svc.
// altSvc is e.g. `h3=":443"; ma=86400`; empty disables the header.
func Secure(next http.Handler, altSvc string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.TLS != nil {
// RFC 6797: a UA ignores this header when it arrives over plain HTTP.
w.Header().Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
}
if altSvc != "" && r.ProtoMajor < 3 {
w.Header().Set("Alt-Svc", altSvc)
}
next.ServeHTTP(w, r)
})
}
// Negotiate picks the best coding from Accept-Encoding among supported,
// honouring q-values, q=0 and "*". It returns "" for identity.
func Negotiate(accept string, supported ...string) string {
q := map[string]float64{}
for _, part := range strings.Split(accept, ",") {
fields := strings.Split(strings.TrimSpace(part), ";")
name := strings.ToLower(strings.TrimSpace(fields[0]))
if name == "" {
continue
}
weight := 1.0
for _, f := range fields[1:] {
if v, ok := strings.CutPrefix(strings.TrimSpace(f), "q="); ok {
if w, err := strconv.ParseFloat(v, 64); err == nil {
weight = w
}
}
}
q[name] = weight
}
best, bestQ := "", 0.0
for _, s := range supported { // supported is in server preference order
w, ok := q[s]
if !ok {
w, ok = q["*"]
}
if ok && w > bestQ {
best, bestQ = s, w
}
}
return best
}
type gzipWriter struct {
http.ResponseWriter
zw *gzip.Writer
wroteHeader bool
}
func (g *gzipWriter) Write(p []byte) (int, error) {
if !g.wroteHeader {
g.WriteHeader(http.StatusOK)
}
return g.zw.Write(p)
}
func (g *gzipWriter) WriteHeader(code int) {
if g.wroteHeader {
return
}
g.wroteHeader = true
h := g.ResponseWriter.Header()
// A gzip body is a different representation: a strong ETag must change.
// The 304 must carry the same validator the 200 would have carried.
if et := h.Get("ETag"); et != "" && !strings.HasPrefix(et, "W/") {
h.Set("ETag", "W/"+et)
}
if code != http.StatusNotModified && code >= 200 {
h.Del("Content-Length")
h.Set("Content-Encoding", "gzip")
}
g.ResponseWriter.WriteHeader(code)
}
// Compress gzips responses for clients that accept it. Brotli and zstd need
// third-party packages in Go, or a proxy/CDN (NGINX, Caddy, Cloudflare).
func Compress(next http.Handler) http.Handler {
pool := sync.Pool{New: func() any { return gzip.NewWriter(nil) }}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Vary", "Accept-Encoding")
if r.Header.Get("Range") != "" || Negotiate(r.Header.Get("Accept-Encoding"), "gzip") != "gzip" {
next.ServeHTTP(w, r)
return
}
zw := pool.Get().(*gzip.Writer)
var buf bytes.Buffer
zw.Reset(&buf)
rec := &recorder{header: http.Header{}, code: http.StatusOK}
next.ServeHTTP(&gzipWriter{ResponseWriter: rec, zw: zw}, r)
_ = zw.Close()
pool.Put(zw)
for k, v := range rec.header {
w.Header()[k] = v
}
w.WriteHeader(rec.code)
if rec.code != http.StatusNotModified {
_, _ = w.Write(buf.Bytes())
}
})
}
// recorder buffers status and headers so Compress can rewrite them.
type recorder struct {
header http.Header
code int
}
func (r *recorder) Header() http.Header { return r.header }
func (r *recorder) Write(p []byte) (int, error) { return len(p), nil }
func (r *recorder) WriteHeader(code int) { r.code = code }
// Product is a tiny catalogue entry; Version feeds the ETag.
type Product struct {
ID int
Name string
Version int
}
// Routes wires the examples used by the tests and the lab.
func Routes(catalog map[int]Product, export []byte, exportMod time.Time) http.Handler {
mux := http.NewServeMux()
mux.Handle("GET /products/{id}", Compress(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
id, _ := strconv.Atoi(r.PathValue("id"))
p, ok := catalog[id]
if !ok {
http.NotFound(w, r)
return
}
etag := fmt.Sprintf(`"p%d-v%d"`, p.ID, p.Version)
w.Header().Set("ETag", etag)
w.Header().Set("Cache-Control", "public, max-age=60, stale-while-revalidate=30")
if matches(r.Header.Get("If-None-Match"), etag) {
w.WriteHeader(http.StatusNotModified) // 304: no body, same validators
return
}
w.Header().Set("Content-Type", "application/json")
_, _ = fmt.Fprintf(w, `{"id":%d,"name":%q,"version":%d,"padding":%q}`,
p.ID, p.Name, p.Version, strings.Repeat("x", 2048))
})))
// http.ServeContent implements Range, If-Range, 206 and 416 for us.
mux.HandleFunc("GET /export.csv", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/csv")
http.ServeContent(w, r, "export.csv", exportMod, bytes.NewReader(export))
})
// 103 Early Hints: send Link hints before the slow part of the page.
mux.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Link", "</static/app.css>; rel=preload; as=style")
w.Header().Add("Link", "<https://cdn.example.com>; rel=preconnect")
w.WriteHeader(http.StatusEarlyHints) // sent immediately, header map kept
time.Sleep(30 * time.Millisecond) // database, templates...
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("Cache-Control", "no-cache")
_, _ = w.Write([]byte(`<!doctype html><link rel="stylesheet" href="/static/app.css">`))
})
return mux
}
// matches implements the weak comparison If-None-Match uses (RFC 9110 13.1.2).
func matches(header, etag string) bool {
if header == "" {
return false
}
if strings.TrimSpace(header) == "*" {
return true
}
want := strings.TrimPrefix(etag, "W/")
for _, c := range strings.Split(header, ",") {
if strings.TrimPrefix(strings.TrimSpace(c), "W/") == want {
return true
}
}
return false
}package server
import (
"compress/gzip"
"context"
"io"
"net"
"net/http"
"net/http/httptest"
"net/http/httptrace"
"net/textproto"
"strings"
"testing"
"time"
)
var (
catalog = map[int]Product{1: {ID: 1, Name: "Kettle", Version: 7}}
export = []byte(strings.Repeat("id,name\n", 1000)) // 8000 bytes
mod = time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC)
)
func handler() http.Handler {
return Secure(Routes(catalog, export, mod), `h3=":443"; ma=86400`)
}
// startH2C runs New() on loopback with HTTP/2 prior knowledge enabled.
func startH2C(t *testing.T) string {
t.Helper()
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
srv := New(ln.Addr().String(), handler(), true)
go func() { _ = srv.Serve(ln) }()
t.Cleanup(func() { _ = srv.Close() })
return "http://" + ln.Addr().String()
}
func TestH2CPriorKnowledge(t *testing.T) {
base := startH2C(t)
p := new(http.Protocols)
p.SetUnencryptedHTTP2(true) // only h2c: the client speaks HTTP/2 at once
c := &http.Client{Transport: &http.Transport{Protocols: p}, Timeout: 2 * time.Second}
resp, err := c.Get(base + "/products/1")
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
if resp.Proto != "HTTP/2.0" {
t.Fatalf("want HTTP/2.0 over cleartext, got %s", resp.Proto)
}
if resp.Header.Get("Strict-Transport-Security") != "" {
t.Fatal("HSTS must not be sent over plain HTTP")
}
if resp.Header.Get("Alt-Svc") == "" {
t.Fatal("expected Alt-Svc advertisement")
}
}
func TestSameServerStillSpeaksHTTP1(t *testing.T) {
base := startH2C(t)
resp, err := http.Get(base + "/products/1") // default client: HTTP/1.1 on http://
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
if resp.Proto != "HTTP/1.1" {
t.Fatalf("got %s", resp.Proto)
}
}
func TestHSTSOnTLS(t *testing.T) {
srv := httptest.NewUnstartedServer(handler())
srv.EnableHTTP2 = true
srv.StartTLS()
defer srv.Close()
resp, err := srv.Client().Get(srv.URL + "/products/1")
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
if resp.ProtoMajor != 2 || resp.TLS.NegotiatedProtocol != "h2" {
t.Fatalf("want h2 via ALPN, got %s / %q", resp.Proto, resp.TLS.NegotiatedProtocol)
}
if !strings.Contains(resp.Header.Get("Strict-Transport-Security"), "max-age=31536000") {
t.Fatal("missing HSTS")
}
}
func TestConditionalGetReturns304(t *testing.T) {
ts := httptest.NewServer(handler())
defer ts.Close()
tr := &http.Transport{DisableCompression: true}
c := &http.Client{Transport: tr}
req, _ := http.NewRequest(http.MethodGet, ts.URL+"/products/1", nil)
req.Header.Set("Accept-Encoding", "br;q=1.0, gzip;q=0.8")
first, err := c.Do(req)
if err != nil {
t.Fatal(err)
}
body, _ := io.ReadAll(first.Body)
first.Body.Close()
etag := first.Header.Get("ETag")
if first.Header.Get("Content-Encoding") != "gzip" || !strings.HasPrefix(etag, `W/"p1-v7"`) {
t.Fatalf("want gzip + weak ETag, got %q %q", first.Header.Get("Content-Encoding"), etag)
}
zr, err := gzip.NewReader(strings.NewReader(string(body)))
if err != nil {
t.Fatal(err)
}
plain, _ := io.ReadAll(zr)
if len(body) >= len(plain) {
t.Fatalf("gzip should shrink the body: %d >= %d", len(body), len(plain))
}
req2, _ := http.NewRequest(http.MethodGet, ts.URL+"/products/1", nil)
req2.Header.Set("Accept-Encoding", "gzip")
req2.Header.Set("If-None-Match", etag)
second, err := c.Do(req2)
if err != nil {
t.Fatal(err)
}
n, _ := io.Copy(io.Discard, second.Body)
second.Body.Close()
if second.StatusCode != http.StatusNotModified || n != 0 || second.Header.Get("ETag") != etag {
t.Fatalf("want 304 with empty body and same ETag, got %d, %d bytes, %q", second.StatusCode, n, second.Header.Get("ETag"))
}
}
func TestRangeRequestReturns206(t *testing.T) {
ts := httptest.NewServer(handler())
defer ts.Close()
req, _ := http.NewRequest(http.MethodGet, ts.URL+"/export.csv", nil)
req.Header.Set("Range", "bytes=0-99")
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
b, _ := io.ReadAll(resp.Body)
resp.Body.Close()
if resp.StatusCode != http.StatusPartialContent || len(b) != 100 ||
resp.Header.Get("Content-Range") != "bytes 0-99/8000" {
t.Fatalf("got %d, %d bytes, %q", resp.StatusCode, len(b), resp.Header.Get("Content-Range"))
}
bad, _ := http.NewRequest(http.MethodGet, ts.URL+"/export.csv", nil)
bad.Header.Set("Range", "bytes=9000-")
resp, err = http.DefaultClient.Do(bad)
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusRequestedRangeNotSatisfiable {
t.Fatalf("want 416, got %d", resp.StatusCode)
}
}
func TestEarlyHints(t *testing.T) {
ts := httptest.NewServer(handler())
defer ts.Close()
var hints []string
trace := &httptrace.ClientTrace{
Got1xxResponse: func(code int, h textproto.MIMEHeader) error {
if code == http.StatusEarlyHints {
hints = append(hints, h.Values("Link")...)
}
return nil
},
}
req, _ := http.NewRequestWithContext(httptrace.WithClientTrace(context.Background(), trace), http.MethodGet, ts.URL+"/", nil)
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
if resp.StatusCode != 200 || len(hints) != 2 || !strings.Contains(hints[0], "rel=preload") {
t.Fatalf("status %d, hints %v", resp.StatusCode, hints)
}
}
func TestNegotiate(t *testing.T) {
cases := []struct{ accept, want string }{
{"gzip, deflate, br, zstd", "zstd"},
{"br;q=1.0, gzip;q=0.8, *;q=0.1", "br"},
{"gzip;q=0", ""},
{"*", "zstd"},
{"", ""},
{"identity", ""},
}
for _, c := range cases {
if got := Negotiate(c.accept, "zstd", "br", "gzip"); got != c.want {
t.Errorf("Negotiate(%q) = %q, want %q", c.accept, got, c.want)
}
}
}
func TestServerTimeoutsAreSet(t *testing.T) {
s := New(":0", http.NotFoundHandler(), false)
if s.ReadHeaderTimeout == 0 || s.IdleTimeout == 0 || s.WriteTimeout == 0 {
t.Fatal("every server timeout must be explicit")
}
if s.Protocols.UnencryptedHTTP2() {
t.Fatal("h2c must be opt-in")
}
}HTTP/3 with quic-go: one handler served on TCP (h1/h2, advertising h3 through SetQUICHeaders) and UDP (h3), a 0-RTT guard returning 425, and an HTTP/3 client. It builds and vets; it was not run here (it needs a certificate).
// Command h3 serves the same handler over HTTP/1.1, HTTP/2 (TCP) and
// HTTP/3 (QUIC over UDP) with github.com/quic-go/quic-go, advertises h3
// through Alt-Svc, and can act as an HTTP/3 client.
//
// CERT=cert.pem KEY=key.pem go run ./h3 serve
// go run ./h3 get https://localhost:8443/
//
// It exits immediately when the certificate is missing, so it builds and
// vets without any setup.
package main
import (
"context"
"crypto/tls"
"errors"
"fmt"
"io"
"log"
"net/http"
"os"
"time"
"github.com/quic-go/quic-go"
"github.com/quic-go/quic-go/http3"
)
const addr = ":8443" // same port number on TCP (h1/h2) and UDP (h3)
func main() {
if len(os.Args) < 2 {
log.Fatal("usage: h3 serve | h3 get URL")
}
switch os.Args[1] {
case "serve":
if err := serve(os.Getenv("CERT"), os.Getenv("KEY")); err != nil {
log.Fatal(err)
}
case "get":
if len(os.Args) < 3 {
log.Fatal("usage: h3 get URL")
}
if err := get(os.Args[2]); err != nil {
log.Fatal(err)
}
}
}
func serve(certFile, keyFile string) error {
if certFile == "" || keyFile == "" {
return errors.New("set CERT and KEY (for example with mkcert localhost)")
}
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return err
}
mux := http.NewServeMux()
mux.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) {
// r.TLS.HandshakeComplete is false for a request that arrived in
// 0-RTT early data: treat it as replayable (RFC 8470).
if r.ProtoMajor == 3 && !r.TLS.HandshakeComplete && r.Method != http.MethodGet {
w.WriteHeader(http.StatusTooEarly) // 425
return
}
fmt.Fprintf(w, "hello over %s\n", r.Proto)
})
h3 := &http3.Server{
Addr: addr,
Handler: mux,
TLSConfig: http3.ConfigureTLSConfig(&tls.Config{Certificates: []tls.Certificate{cert}}),
QUICConfig: &quic.Config{
MaxIdleTimeout: 30 * time.Second, // QUIC idle timeout
KeepAlivePeriod: 10 * time.Second, // keeps NAT bindings alive
Allow0RTT: true,
},
Port: 443, // the port clients see if a UDP load balancer remaps it
}
// TCP listener for HTTP/1.1 and h2; every response advertises h3.
tcp := &http.Server{
Addr: addr,
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_ = h3.SetQUICHeaders(w.Header()) // Alt-Svc: h3=":443"; ma=2592000
mux.ServeHTTP(w, r)
}),
TLSConfig: &tls.Config{Certificates: []tls.Certificate{cert}},
ReadHeaderTimeout: 5 * time.Second,
IdleTimeout: 120 * time.Second,
}
errs := make(chan error, 2)
go func() { errs <- h3.ListenAndServe() }()
go func() { errs <- tcp.ListenAndServeTLS("", "") }()
return <-errs
}
func get(url string) error {
tr := &http3.Transport{
TLSClientConfig: &tls.Config{
NextProtos: []string{http3.NextProtoH3},
ClientSessionCache: tls.NewLRUClientSessionCache(64), // resumption, 0-RTT
},
QUICConfig: &quic.Config{MaxIdleTimeout: 30 * time.Second},
}
defer tr.Close()
c := &http.Client{Transport: tr, Timeout: 5 * time.Second}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return err
}
resp, err := c.Do(req)
if err != nil {
// UDP blocked or no h3 listener: a real client falls back to TCP.
return fmt.Errorf("h3 failed (fall back to h2): %w", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
fmt.Printf("%s %s", resp.Proto, body)
return err
}The lab program that produced the numbers in the Lab:
// Command lab measures connection reuse, HTTP/1.1 vs HTTP/2 concurrency
// and application-level head-of-line blocking on loopback. It needs no
// network and no certificates: httptest generates them.
package main
import (
"context"
"crypto/tls"
"crypto/x509"
"fmt"
"net"
"net/http"
"net/http/httptest"
"sync"
"sync/atomic"
"time"
"academy/http-evolution/before"
"academy/http-evolution/client"
)
type server struct {
*httptest.Server
conns atomic.Int64
roots *tls.Config
}
func start(h2 bool) *server {
s := &server{}
s.Server = httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/slow" {
time.Sleep(300 * time.Millisecond)
} else {
time.Sleep(5 * time.Millisecond)
}
_, _ = w.Write([]byte("ok"))
}))
s.EnableHTTP2 = h2
s.Config.ConnState = func(_ net.Conn, st http.ConnState) {
if st == http.StateNew {
s.conns.Add(1)
}
}
s.StartTLS()
pool := x509.NewCertPool()
pool.AddCert(s.Certificate())
s.roots = &tls.Config{RootCAs: pool}
return s
}
func newClient(s *server, maxConns int) *http.Client {
cfg := client.Defaults()
cfg.TLS = s.roots
cfg.MaxConnsPerHost = maxConns
return client.New(cfg)
}
func parallel(n int, f func(i int)) time.Duration {
t0 := time.Now()
var wg sync.WaitGroup
for i := range n {
wg.Add(1)
go func() { defer wg.Done(); f(i) }()
}
wg.Wait()
return time.Since(t0)
}
func main() {
ctx := context.Background()
// 1. New Transport per call vs one shared, tuned client (20 sequential GETs).
s := start(false)
t0 := time.Now()
for range 20 {
_, _ = before.FetchStatus(s.URL, s.roots)
}
fmt.Printf("1a before (transport per call): %2d connections, %v\n", s.conns.Load(), time.Since(t0).Round(time.Millisecond))
s.Close()
s = start(false)
c := newClient(s, 0)
t0 = time.Now()
for range 20 {
_, _, _, _ = client.Get(ctx, c, s.URL, 1<<20)
}
fmt.Printf("1b tuned shared client: %2d connections, %v\n", s.conns.Load(), time.Since(t0).Round(time.Millisecond))
s.Close()
// 2. 100 concurrent requests: HTTP/1.1 opens a socket per in-flight request.
s = start(false)
c = newClient(s, 0)
d := parallel(100, func(int) { _, _, _, _ = client.Get(ctx, c, s.URL, 1<<20) })
fmt.Printf("2a HTTP/1.1, 100 concurrent: %3d connections, %v\n", s.conns.Load(), d.Round(time.Millisecond))
s.Close()
s = start(true)
c = newClient(s, 0)
_, _, _, _ = client.Get(ctx, c, s.URL, 1<<20) // learn h2 via ALPN first
d = parallel(100, func(int) { _, _, _, _ = client.Get(ctx, c, s.URL, 1<<20) })
fmt.Printf("2b HTTP/2, 100 concurrent: %3d connections, %v\n", s.conns.Load(), d.Round(time.Millisecond))
s.Close()
// 3. Head-of-line blocking: one slow request, then 5 fast ones, one connection.
for _, h2 := range []bool{false, true} {
s = start(h2)
c = newClient(s, 1) // a single connection to the host
_, _, _, _ = client.Get(ctx, c, s.URL, 1<<20)
go func() { _, _, _, _ = client.Get(ctx, c, s.URL+"/slow", 1<<20) }()
time.Sleep(10 * time.Millisecond) // the slow request is now in flight
var worst atomic.Int64
parallel(5, func(int) {
t := time.Now()
_, _, _, _ = client.Get(ctx, c, s.URL+"/fast", 1<<20)
if e := time.Since(t).Milliseconds(); e > worst.Load() {
worst.Store(e)
}
})
name := "HTTP/1.1"
if h2 {
name = "HTTP/2 "
}
fmt.Printf("3 %s one connection: slowest fast request waited ~%d ms\n", name, worst.Load())
s.Close()
}
}The Go angle
| Go feature | Use | Note |
|---|---|---|
http.Transport | Connection pool, ALPN, h2 | "Transports should be reused instead of created as needed." |
Transport.Protocols, Server.Protocols (1.24) | Choose HTTP/1, HTTP/2, unencrypted HTTP/2 | h2c uses prior knowledge; "Upgrade: h2c" is not supported |
http.HTTP2Config (1.24) | MaxConcurrentStreams, receive buffers, SendPingTimeout, PingTimeout, WriteByteTimeout | Same struct for client and server |
golang.org/x/net/http2 | Low-level framer, legacy ConfigureServer | "As of Go 1.27, the source of truth has moved to the standard library package net/http/internal/http2." |
x/net/http2/h2c | Old h2c handler | Deprecated in favour of Server.Protocols |
httptrace.ClientTrace | GotConn (reused?), Got1xxResponse (103), DNS/TLS timings | How the tests count connections |
http.ResponseController | Per-request SetReadDeadline, SetWriteDeadline, Flush, EnableFullDuplex | Override server-wide timeouts for one handler |
http.ServeContent | Range, If-Range, If-None-Match, 206, 304, 416 | Use for files and exports |
ResponseWriter.WriteHeader(103) | Early Hints | "Any number of 1xx headers may be written" |
GODEBUG=http2client=0, http2server=0, http2debug=1 | Disable or debug HTTP/2 | Documented in the net/http package |
quic-go http3.Server / http3.Transport | HTTP/3 | Go stdlib has no HTTP/3 in 1.27 |
Deeper TLS, mTLS and h2load/wrk benchmarking in Go: HTTP/2, HTTPS, TLS & mTLS in Go.
Laravel
Before
Four upstream calls in sequence, each building a new Guzzle client (no reuse), the 30 s default timeout, HTTP/1.1 only.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Http;
/**
* Before: four upstream calls, one after another.
*
* - Each Http:: call builds a fresh Guzzle client and handler, so nothing
* is reused between calls: four TCP + TLS handshakes per page.
* - The default timeout is 30 seconds: one stuck upstream holds a PHP-FPM
* worker for 30 s, and a handful of those exhaust the pool.
* - HTTP/1.1 only (Guzzle's default 'version' is 1.1).
* - Total latency is the SUM of the four calls.
*/
class DashboardBeforeController extends Controller
{
public function __invoke(int $userId): JsonResponse
{
$base = config('services.internal.url');
$profile = Http::get("{$base}/users/{$userId}")->json();
$orders = Http::get("{$base}/users/{$userId}/orders")->json();
$wallet = Http::get("{$base}/users/{$userId}/wallet")->json();
$offers = Http::get("{$base}/offers", ['user' => $userId])->json();
return response()->json(compact('profile', 'orders', 'wallet', 'offers'));
}
}After
Concurrent calls through one pool. Laravel's Pool creates one Guzzle handler (Utils::chooseHandler()) and every pooled request uses it, so requests share libcurl's connection cache; 'version' => 2.0 asks for h2 and the pooled requests multiplex. Each request gets its own timeouts because pool() "cannot be chained with other HTTP client methods". Connection failures arrive as ConnectionException entries instead of responses.
<?php
namespace App\Services;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Client\Pool;
use Illuminate\Http\Client\Response;
use Illuminate\Support\Facades\Http;
use Throwable;
/**
* After: the four calls run concurrently through one Http::pool().
*
* The pool shares one Guzzle handler (one curl multi handle), so requests
* to the same host reuse connections; with 'version' => 2.0 libcurl
* negotiates h2 through ALPN and multiplexes the pooled requests as streams
* on one TLS connection (CURLMOPT_PIPELINING defaults to CURLPIPE_MULTIPLEX).
* Latency becomes roughly the SLOWEST call instead of the sum.
*/
class InternalApi
{
/** @var array<string, mixed> */
private const OPTIONS = [
'version' => 2.0,
// libcurl sends Accept-Encoding with every coding it was built with
// (gzip, deflate, br, zstd) and decodes the response transparently.
'decode_content' => true,
];
public function __construct(private readonly string $base) {}
/**
* @return array<string, mixed>
*/
public function dashboard(int $userId): array
{
$responses = Http::pool(fn (Pool $pool) => [
$this->request($pool, 'profile')->get("{$this->base}/users/{$userId}"),
$this->request($pool, 'orders')->get("{$this->base}/users/{$userId}/orders"),
$this->request($pool, 'wallet')->get("{$this->base}/users/{$userId}/wallet"),
$this->request($pool, 'offers')->get("{$this->base}/offers", ['user' => $userId]),
], concurrency: 4);
$result = [];
foreach ($responses as $name => $response) {
$result[$name] = $this->decode($name, $response);
}
return $result;
}
private function request(Pool $pool, string $name): PendingRequest
{
// pool() cannot be chained with withHeaders()/timeout(): configure each request.
return $pool->as($name)
->withOptions(self::OPTIONS)
->connectTimeout(1) // TCP + TLS connect
->timeout(2) // whole request, per call
->acceptJson();
}
private function decode(string $name, Response|Throwable $response): mixed
{
// A connection-level failure (timeout, DNS, refused) arrives as a
// ConnectionException instead of a Response.
if ($response instanceof Throwable) {
report($response);
return $name === 'offers' ? [] : null; // optional widget degrades
}
if ($response->failed()) {
return null;
}
return $response->json();
}
}Early Hints, HSTS and validators in one middleware. headers_send(103) exists only under FrankenPHP (Laravel Octane's FrankenPHP server, which the Octane docs describe as supporting "early hints, Brotli, and Zstandard compression"); under PHP-FPM the hints still ride on the final response as Link headers.
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* Sends 103 Early Hints before the controller runs (FrankenPHP / Octane),
* then adds HSTS and validators to the final response.
*/
class EarlyHintsAndCaching
{
/** @var list<string> */
private const HINTS = [
'</build/assets/app.css>; rel=preload; as=style',
'<https://cdn.example.com>; rel=preconnect',
];
public function handle(Request $request, Closure $next): Response
{
// headers_send() is provided by FrankenPHP; PHP-FPM has no way to
// emit a 1xx response, so the hints simply ride on the final response.
if ($request->isMethod('GET') && function_exists('headers_send')) {
foreach (self::HINTS as $link) {
header('Link: '.$link, false);
}
headers_send(103);
header_remove('Link'); // the final response sets its own Link header
}
$response = $next($request);
$response->headers->set('Link', implode(', ', self::HINTS), false);
if ($request->isSecure()) {
// isSecure() is only true behind a TLS-terminating proxy when
// trustProxies() is configured (X-Forwarded-Proto: https).
$response->headers->set('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
}
if ($request->isMethodCacheable() && $response->isSuccessful() && ! $response->headers->has('ETag')) {
$content = (string) $response->getContent();
if ($content !== '') {
$response->setEtag(hash('xxh128', $content), weak: true);
$response->setCache(['private' => true, 'max_age' => 0, 'must_revalidate' => true]);
// Turns the response into a 304 with an empty body when
// If-None-Match matches (Symfony HttpFoundation).
$response->isNotModified($request);
}
}
return $response;
}
}Trusted proxies (TLS terminates at the load balancer) and the middleware alias:
<?php
use App\Http\Middleware\EarlyHintsAndCaching;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Request;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware): void {
// TLS terminates at the load balancer; trust its X-Forwarded-* headers
// so $request->isSecure() and url() see https.
$middleware->trustProxies(at: ['10.0.0.0/8'], headers: Request::HEADER_X_FORWARDED_FOR |
Request::HEADER_X_FORWARDED_HOST |
Request::HEADER_X_FORWARDED_PORT |
Request::HEADER_X_FORWARDED_PROTO);
$middleware->alias(['early.hints' => EarlyHintsAndCaching::class]);
})
->withExceptions(function (Exceptions $exceptions): void {
//
})->create();Routes: the built-in cache.headers middleware for public pages, the custom middleware for personalised ones:
<?php
use App\Http\Controllers\DashboardBeforeController;
use App\Services\InternalApi;
use Illuminate\Support\Facades\Route;
// Public, shared-cacheable pages: Laravel's built-in cache.headers middleware
// sets Cache-Control and an xxh128 ETag, then answers 304 on a match.
Route::middleware('cache.headers:public;max_age=60;s_maxage=300;stale_while_revalidate=600;etag')
->group(function () {
Route::get('/pricing', fn () => view('pricing'));
Route::get('/docs/{page}', fn (string $page) => view('docs.page', ['page' => $page]));
});
// Personalised page: early hints + private validators.
Route::get('/dashboard/{userId}', function (int $userId, InternalApi $api) {
return view('dashboard', $api->dashboard($userId));
})->middleware(['auth', 'early.hints']);
Route::get('/dashboard-before/{userId}', DashboardBeforeController::class);Plain PHP curl_multi for when you want to see the protocol: four requests over one HTTP/2 connection with CURLMOPT_MAX_HOST_CONNECTIONS = 1 and CURLOPT_PIPEWAIT, printing the negotiated version per transfer:
<?php
// Plain PHP: four GETs multiplexed over ONE HTTP/2 connection with curl_multi.
// Run: php curl_multi_h2.php https://example.com
declare(strict_types=1);
$base = $argv[1] ?? 'https://example.com';
$paths = ['/', '/a', '/b', '/c'];
$mh = curl_multi_init();
curl_multi_setopt($mh, CURLMOPT_PIPELINING, CURLPIPE_MULTIPLEX); // default since libcurl 7.62
curl_multi_setopt($mh, CURLMOPT_MAX_HOST_CONNECTIONS, 1); // force sharing one connection
$handles = [];
foreach ($paths as $path) {
$ch = curl_init($base.$path);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_2TLS, // h2 via ALPN on https, 1.1 on http
CURLOPT_PIPEWAIT => true, // wait for the h2 connection instead of opening another
CURLOPT_ENCODING => '', // advertise every built-in coding (gzip, br, zstd)
CURLOPT_CONNECTTIMEOUT_MS => 1000,
CURLOPT_TIMEOUT_MS => 3000,
CURLOPT_TCP_KEEPALIVE => 1,
]);
curl_multi_add_handle($mh, $ch);
$handles[$path] = $ch;
}
do {
$status = curl_multi_exec($mh, $running);
if ($running > 0) {
curl_multi_select($mh, 1.0);
}
} while ($running > 0 && $status === CURLM_OK);
foreach ($handles as $path => $ch) {
$version = match (curl_getinfo($ch, CURLINFO_HTTP_VERSION)) {
CURL_HTTP_VERSION_1_1 => 'HTTP/1.1',
CURL_HTTP_VERSION_2_0 => 'HTTP/2',
default => 'other',
};
printf(
"%-3s %s %d connect=%.3fs total=%.3fs\n",
$path,
$version,
curl_getinfo($ch, CURLINFO_RESPONSE_CODE),
curl_getinfo($ch, CURLINFO_CONNECT_TIME),
curl_getinfo($ch, CURLINFO_TOTAL_TIME),
);
curl_multi_remove_handle($mh, $ch);
}
curl_multi_close($mh);The Laravel angle
| Laravel 13 / PHP feature | Use | Note |
|---|---|---|
Http::pool(fn (Pool $pool) => [...], concurrency: N) | Fan-out with bounded concurrency | One shared handler; results keyed by as() |
Http::batch() | Pool with before, progress, then, catch, finally callbacks | Same transport behaviour |
Http::withOptions(['version' => 2.0]) | Ask for HTTP/2 | Guzzle maps 2.0 to CURL_HTTP_VERSION_2_0; 'curl' => [CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_3] for h3 if libcurl supports it |
Http::timeout(), connectTimeout() | Total and connect limits | Defaults 30 s and 10 s |
Http::globalOptions([...]) | Defaults for every request | Set in AppServiceProvider::boot |
cache.headers middleware (SetCacheHeaders) | Cache-Control, ETag (xxh128), automatic 304 via isNotModified() | Only for cacheable methods and successful responses |
AddLinkHeadersForPreloadedAssets | Link: rel=preload for Vite assets | Pair with Cloudflare Early Hints or NGINX early_hints |
trustProxies(at:, headers:) | Correct scheme and client IP behind TLS termination | AWS: Request::HEADER_X_FORWARDED_AWS_ELB |
| Laravel Octane (FrankenPHP, Swoole, RoadRunner) | Long-lived workers: clients and connections survive between requests | FrankenPHP adds HTTP/3, 103, Brotli/zstd at the server |
| PHP-FPM | One process per request lifecycle | No connection reuse across web requests; put a proxy with upstream keep-alive in front of hot upstreams |
curl_multi_*, CURLMOPT_*, CURL_HTTP_VERSION_* | Raw control | CURL_HTTP_VERSION_3 needs PHP 8.4+ and libcurl built with HTTP/3 |
Solving the classic problems
A handshake per request
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Shared client | One *http.Client per upstream; Http::pool in Laravel | Zero handshakes in steady state | Must drain bodies; per-process pools |
Raise MaxIdleConnsPerHost | 2 -> expected concurrency | Pool survives bursts | More idle sockets on the server |
| HTTP/2 | One connection, many streams | Even fewer sockets | L4 balancing becomes uneven |
| Local proxy for PHP-FPM | NGINX/Envoy sidecar with upstream keepalive | Reuse across FPM requests | Extra hop to operate |
Symptom: new-connection rate equals request rate; TIME_WAIT count in the thousands (ss -s); p50 latency includes 2 RTT. The lab shows 20 connections for 20 calls before the fix and 1 after.
Sporadic 502 behind a load balancer
1 ALB idle timeout 60 s, backend (Go) IdleTimeout 30 s
2 t=0 request on ALB->backend connection D
3 t=30 backend closes D (idle); FIN in flight
4 t=30.001 ALB reuses D for a new request -> reset -> 502 to the user
5 fix: backend IdleTimeout 75-120 s (> ALB 60 s); client-side idle timeouts below the ALB's| Solution | How | Advantage | Cost |
|---|---|---|---|
| Order idle timeouts | client < LB < backend | Removes the race | Idle sockets live longer |
| Retry idempotent requests on reset | Go does it automatically for used connections | Users see nothing for GETs | Not for POST without a key |
| HTTP/2 to the backend | GOAWAY tells the LB which streams were not processed | Safe retries | Needs h2 support on both |
Slow page built from several services
Sequential calls sum their latencies (4 x 120 ms = 480 ms); Http::pool or Go goroutines make it the maximum (about 120 ms plus the slowest tail). Bound concurrency, give each call its own timeout, degrade optional widgets (offers returns []). Budget arithmetic: Latency Budgets.
HTTP/2 overloads one backend
One h2 connection from a gateway carries thousands of streams to whichever backend an L4 load balancer (AWS NLB, kube-proxy) picked when it opened. Fix: balance per request at L7 (Envoy, NGINX, AWS ALB, a service mesh), cap MaxConcurrentStreams, and recycle connections (GOAWAY after N requests or minutes; NGINX keepalive_requests/keepalive_time). gRPC specifics: gRPC & Protobuf.
Push configured, nothing faster
Remove http2_push/push code; send Link: rel=preload on the response and 103 Early Hints from the server or CDN; use rel=preconnect for third-party origins; verify in DevTools that preloaded resources are used (Chrome warns when they are not).
HTTP/3 enabled, nobody uses it
Check: Alt-Svc present on TCP responses; UDP 443 open in the security group, firewall and any L4 load balancer; certificate valid for TLS 1.3; then read the protocol mix from logs (the lab's SQL). Expect TCP on first visits and on networks that block UDP; that is by design.
A replayed request
0-RTT enabled at the edge and a POST replayed: limit 0-RTT to GET/HEAD/OPTIONS (Cloudflare's policy), return 425 for anything else carrying Early-Data: 1, and keep idempotency keys on writes.
Too many bytes
| Solution | How | Advantage | Cost |
|---|---|---|---|
| Compression | Brotli/zstd/gzip by Accept-Encoding, Vary | 3-10x smaller text (typical; measure) | CPU; BREACH with secrets |
| Freshness | Cache-Control: max-age, s-maxage, immutable for hashed assets | No request at all | Staleness |
| Validation | ETag from a version column, 304 | No body | Still one RTT |
| Ranges | ServeContent, object storage | Resume and parallel download | Not with on-the-fly compression |
Choosing
Which version on which hop
| Hop | Recommendation | Extra technique | Reason |
|---|---|---|---|
| Browser / mobile app to edge | HTTP/3 with HTTP/2 and HTTP/1.1 fallback | Alt-Svc, HTTPS DNS record, 0-RTT for GET only | Lossy last mile, network changes, handshake cost |
| Edge (CDN) to origin | HTTP/2 over TLS, or HTTP/1.1 keep-alive | Origin shield, connection reuse | Low loss, few long-lived connections; most CDNs do not speak h3 to origins |
| Load balancer to application | HTTP/1.1 keep-alive or h2/h2c | Idle timeout ordering | Simplicity; h2 if gRPC or many concurrent requests |
| Service to service, RPC | gRPC over h2 (mTLS) | L7 or client-side balancing, deadlines | Multiplexing, streaming, contracts |
| Service to service, REST | HTTP/1.1 keep-alive or h2 with a shared pool | Timeouts, retries for idempotent calls | Mature tooling everywhere |
| Third-party APIs | Whatever they offer; h2 when available | Per-vendor pools and bulkheads | You do not control the server |
| Large file transfer | HTTP/1.1 or h2 with ranges, or object storage presigned URLs | Parallel ranges | Throughput per connection matters more than multiplexing |
| Real-time | WebSocket (HTTP/1.1 upgrade or RFC 8441), SSE over h2 | See the real-time chapter | Long-lived streams |
Which timeouts
| Situation | Connect | Header | Total | Idle |
|---|---|---|---|---|
| Internal call, same region | 0.5-1 s | 1-2 s | Remaining deadline | Below the server's / LB's |
| Third-party payment API | 2-3 s | Vendor's p99 + margin | 10-30 s with idempotency key | 30-55 s |
| Browser-facing server | - | Server header timeout 5-10 s | Write timeout sized to largest response | 60-120 s (above the LB's) |
| Behind AWS ALB (60 s idle) | - | - | - | Backend 75-120 s |
Which compression
| Content | Coding | Where | Reason |
|---|---|---|---|
| Hashed static assets | Brotli or zstd, precompressed at build | CDN / static server | Best ratio, zero runtime CPU |
| Dynamic HTML/JSON | Brotli low level, zstd or gzip | Edge or proxy | Ratio vs CPU per response |
| API to old clients | gzip | Anywhere | Universal |
| Images, video, archives | None | - | Already compressed |
| Responses mixing secrets and user input | None, or separate the secret | - | BREACH |
In architecture: from a single process to a distributed system
The same request, "a user opens the order dashboard", crosses more HTTP hops as the system grows. The decisions stay the same (version per hop, pool, timeouts, TLS, bytes); what changes is how many hops make them and who owns each.
Monolith: one process, one database
How it shows up: one hop that matters, browser to server. TLS at NGINX or the load balancer, HTTP/2 to the browser, HTTP/1.1 keep-alive or FastCGI behind it, plus outbound calls to a payment provider.
Simplest correct usage: HTTPS with HSTS, HTTP/2 on the edge, compression and Cache-Control for static assets, ETags on hot reads, explicit server timeouts, and one HTTP client with timeouts for the payment API.
Example (simple): a Laravel shop on PHP-FPM behind NGINX: http2 on;, Let's Encrypt via certbot, gzip on;, cache.headers on /pricing, Http::timeout(10)->connectTimeout(3) with an idempotency key towards Stripe.
Example (production-shaped): the same app behind Cloudflare with HTTP/3 and Early Hints, AddLinkHeadersForPreloadedAssets for Vite, Octane on FrankenPHP so outbound connections survive between requests, and trustProxies() so links stay https://.
Modular monolith: boundaries without the network
How it shows up: modules call each other in process, so no HTTP between them; HTTP appears only at the edge and for external APIs. The design work is preparing contracts that could become HTTP later: idempotent methods, versionable resources, ETags on reads.
| Concern | In process now | When a module is extracted |
|---|---|---|
| Call | Method call | HTTP/gRPC over a pooled client |
| Failure | Exception | Timeout, reset, 502/503/504 |
| Retry safety | Not needed | Safe/idempotent methods, keys, HTTP/2 GOAWAY |
| Caching | In-memory | Cache-Control, ETag, CDN |
| Security | Same process | TLS or mTLS on the new hop |
Example: the catalog module's read API is already shaped as GET /catalog/products/{id} with a version column; extracting it means adding a route, a Go or Laravel client with a pool, and an ETag check, not redesigning callers.
Microservices: every hop negotiates its own HTTP
How it shows up: a request crosses edge, gateway and several services; each hop picks its version, has its own pool and timeouts, and terminates or forwards TLS.
Browser -> Cloudflare (h3, TLS 1) -> AWS ALB (h2, TLS 2) -> gateway (Go)
1 gateway -> orders (gRPC over h2, mTLS via mesh sidecar, deadline 800 ms)
2 gateway -> profile (REST, HTTP/1.1 keep-alive pool, MaxIdleConnsPerHost 64, timeout 300 ms)
3 orders -> payments provider (HTTPS h2, Idempotency-Key, timeout 5 s, no retry without key)
4 gateway assembles the response; ETag from max(version) of parts; Cache-Control: private
5 Cloudflare compresses with Brotli for this browser, zstd for another; Vary: Accept-EncodingWhat survives across hops: semantics (method, status, validators), trace headers, deadlines you propagate. What does not: the HTTP version, the TLS session, connection reuse, ALPN, client IP (unless forwarded with X-Forwarded-For / Forwarded). Gateway and mesh responsibilities: API Gateway, BFF & Service Mesh, Service Mesh.
Distributed data: replicas, caches, regions
How it shows up: CDNs and HTTP caches are distributed copies of your responses; conditional requests and Cache-Control are their consistency protocol. Across regions, handshakes dominate: a fresh TLS 1.3 connection over a 150 ms transatlantic RTT costs about 300 ms before the first byte (back-of-envelope), so connection reuse and edge termination matter more than server speed.
| Effect | Where it hurts | Mitigation |
|---|---|---|
| Stale CDN copy | After a deploy or price change | Short s-maxage + stale-while-revalidate, purge by tag, versioned asset URLs |
| ETag differs per replica | Validators built from hostnames or file inodes | Derive ETags from content versions, not machines |
| Cross-region handshakes | First request per connection | Terminate TLS at the edge, keep warm pools edge to origin, 0-RTT for reads |
| Long-lived h2/gRPC connections pinned to one region or replica | Uneven load after failover | Max connection age, GOAWAY, client-side balancing |
| Range downloads across replicas | Different object versions | If-Range with a strong ETag |
Scaling path: 1x, 10x, 100x
| Load | What changes | Example |
|---|---|---|
| 1x | HTTPS + HSTS, HTTP/2 at the edge, shared clients, explicit timeouts, ETags on hot reads | One Laravel app behind NGINX, one Go service |
| 10x | CDN with HTTP/3 and compression, Early Hints, origin keep-alive pools tuned, idle-timeout ordering audited, L7 balancing for h2/gRPC, Octane or sidecar proxies for PHP | 10-20 services, Cloudflare or CloudFront, AWS ALB, Envoy |
| 100x | Connection budgets per service (sockets and streams), max connection age and GOAWAY rotation, protocol-mix and new-connection-rate dashboards, Rapid Reset style limits at the edge, certificate automation with ARI and short-lived certs | Mesh with mTLS everywhere, multi-region edges, h3 for all user traffic |
Lab: count connections and streams yourself
Everything in steps 1-3 runs offline on loopback and was run while writing this page; steps 4-6 need network access or a certificate and are written with expected output (expected, not run).
Setup.
cd docs/snippets/system-design/http-evolution/go
go vet ./... && go test ./...1. Connection reuse and multiplexing (run). go run ./lab starts in-process TLS servers and prints:
1 1a before (transport per call): 20 connections, 157ms
2 1b tuned shared client: 1 connections, 132ms
3 2a HTTP/1.1, 100 concurrent: 97 connections, 39ms
4 2b HTTP/2, 100 concurrent: 1 connections, 7ms
5 3 HTTP/1.1 one connection: slowest fast request waited ~322 ms
6 3 HTTP/2 one connection: slowest fast request waited ~6 msRead it as: (1) a Transport per call pays a handshake per call; (2) HTTP/1.1 concurrency costs one socket per in-flight request (97-100 depending on timing), HTTP/2 needs one; (3) on one HTTP/1.1 connection fast requests wait behind a slow one (application-level head-of-line blocking), on HTTP/2 they do not. Loopback has no packet loss, so TCP-level blocking does not appear here; timings vary by machine.
2. Semantics tests (run). go test ./server -run 'Conditional|Range|EarlyHints|H2C' -v shows 304 with an empty body and the same weak ETag, 206 with Content-Range: bytes 0-99/8000, 416 for an out-of-range request, two Link hints in a 103, and HTTP/2 over cleartext via prior knowledge.
3. Timeout test (run). go test ./client -run ResponseHeaderTimeout -v fails fast with net/http: timeout awaiting response headers.
4. Inspect a real site with curl (expected, not run).
curl -sI --http2 https://www.example.com -o /dev/null -w '%{http_version}\n'
# expected: 2
curl -sI https://www.example.com | grep -i -E 'alt-svc|strict-transport|content-encoding'
# expected (site dependent): alt-svc: h3=":443"; ma=86400
curl -sI --http3-only https://www.example.com -o /dev/null -w '%{http_version}\n'
# expected: 3 if UDP 443 is open and curl was built with HTTP/3; otherwise an error
curl -s -o /dev/null -w 'connect=%{time_connect} tls=%{time_appconnect} ttfb=%{time_starttransfer}\n' \
https://www.example.com https://www.example.com
# expected: the second URL reuses the connection: connect and tls near 05. HTTP/3 server (expected, not run). mkcert localhost then CERT=localhost.pem KEY=localhost-key.pem go run ./h3 serve, and in another terminal go run ./h3 get https://localhost:8443/ prints HTTP/3.0 hello over HTTP/3.0; curl -sI https://localhost:8443/ shows alt-svc: h3=":443"; ma=2592000.
6. Protocol mix from access logs (expected, not run). Load NGINX logs that include $server_protocol (and $http3) into a table and measure what clients really use:
CREATE TABLE http_access_log (
ts timestamptz NOT NULL,
protocol text NOT NULL, -- 'HTTP/1.1', 'HTTP/2.0', 'HTTP/3.0'
status integer NOT NULL,
bytes_sent bigint NOT NULL,
request_time numeric NOT NULL, -- seconds
connection_id bigint NOT NULL, -- NGINX $connection
connection_requests integer NOT NULL -- NGINX $connection_requests
);
-- Protocol mix and p95 per protocol over the last day
SELECT protocol,
count(*) AS requests,
round(100.0 * count(*) / sum(count(*)) OVER (), 1) AS pct,
percentile_cont(0.95) WITHIN GROUP (ORDER BY request_time) AS p95_s
FROM http_access_log
WHERE ts > now() - interval '1 day'
GROUP BY protocol
ORDER BY requests DESC;
-- Connection reuse: requests per connection (1.0 means no keep-alive at all)
SELECT protocol, round(avg(max_req), 1) AS requests_per_connection
FROM (SELECT protocol, connection_id, max(connection_requests) AS max_req
FROM http_access_log
WHERE ts > now() - interval '1 hour'
GROUP BY protocol, connection_id) per_conn
GROUP BY protocol;Expected shape: most browser traffic on HTTP/2 and HTTP/3, API clients and health checks on HTTP/1.1, requests per connection well above 1 for HTTP/2; a value near 1 for HTTP/1.1 means a client or proxy is closing connections.
Common misconceptions
| Belief | Reality |
|---|---|
| HTTP/2 is always faster | It removes HTTP-level blocking but keeps TCP-level head-of-line blocking; on lossy links one connection can be slower than several |
| HTTP/3 replaces HTTP/2 | It is discovered via Alt-Svc or DNS and falls back to TCP when UDP is blocked; every deployment keeps h2 |
| QUIC is unreliable because it is UDP | QUIC does retransmission, congestion and flow control per stream (RFC 9000) |
| HTTP keep-alive and TCP keep-alive are the same | HTTP keep-alive reuses a connection; TCP keep-alive probes idle sockets; Go's docs call them "unrelated" |
| Persistent connections are automatic | Clients must share a pool and drain bodies; PHP-FPM loses pools at the end of every request |
| Pipelining is HTTP/1.1 multiplexing | Responses are strictly ordered; libcurl removed it; nobody relies on it |
| Server push is the best way to preload | Chrome 106 and Firefox 132 disabled it; use 103 Early Hints and rel=preload |
Cache-Control: no-cache means no caching | It means revalidate before use; no-store means do not store |
| A 304 is free | It saves the body, not the round trip; max-age saves the request |
| One total timeout is enough | Slowloris needs a header timeout; idle timeouts must be ordered across hops |
| The Go default client is production-ready | No timeout, 2 idle connections per host |
| h2c is fine anywhere inside the company | Cleartext; only between a TLS-terminating proxy and a backend on a trusted network |
| 0-RTT is a free speed-up | Early data can be replayed; only safe methods (RFC 8470, 425 Too Early) |
| HSTS can be enabled with preload on day one | Ramp max-age, check subdomains first; preload removal is slow |
| Domain sharding speeds up sites | It helped HTTP/1.1's six-connection limit; with HTTP/2 it defeats multiplexing and coalescing |
Cheat sheet
| Topic | Remember |
|---|---|
| Versions | 1.1 = one exchange per connection at a time; 2 = streams over TCP; 3 = streams over QUIC/UDP |
| Semantics | RFC 9110 for all versions; safe = GET/HEAD/OPTIONS/TRACE; idempotent = safe + PUT/DELETE |
| Head-of-line | 1.1: response order; 2: TCP loss; 3: only the stream that lost a packet |
| Handshakes | TCP+TLS 1.3 = 2 RTT, QUIC = 1 RTT, 0-RTT for replay-safe requests only |
| Keep-alive | Shared client, drained bodies, client idle < LB idle < backend idle |
| Go pool | MaxIdleConnsPerHost default 2: raise it; ForceAttemptHTTP2 with custom TLS/dialer |
| Go server | ReadHeaderTimeout, ReadTimeout, WriteTimeout, IdleTimeout, Protocols, HTTP2 |
| Laravel | Http::pool(..., concurrency:), withOptions(['version' => 2.0]), timeout()/connectTimeout(), Octane for reuse |
| ALPN | http/1.1, h2, h3; h2c = cleartext with prior knowledge |
| Coalescing | Same IP + certificate valid for both hosts; 421 to refuse |
| Push | Dead; 103 Early Hints + rel=preload / rel=preconnect |
| HTTP/3 discovery | Alt-Svc: h3=":443"; ma=86400, HTTPS DNS record; fallback to TCP |
| HTTPS | Terminate where certs are automated (ACME); HSTS 1 year + includeSubDomains, ramp first |
| Compression | br/zstd/gzip by Accept-Encoding; Vary: Accept-Encoding; weak ETag per coding |
| Validation | ETag from a version column; If-None-Match -> 304; If-Match -> 412 |
| Ranges | Range: bytes=a-b -> 206 / 416; If-Range; no on-the-fly compression |
| gRPC | h2 end to end, trailers, te: trailers, L7 balancing |
| HTTP/2 retries | GOAWAY last-stream-id and REFUSED_STREAM = not processed, safe to retry |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Why does HTTP/2 still suffer from head-of-line blocking, and how does HTTP/3 avoid it? Must-know
Answer
Answer: All HTTP/2 streams share one TCP byte stream; when a segment is lost, TCP withholds every later byte until the retransmission arrives, so all streams stall (RFC 9113: "TCP head-of-line blocking is not addressed by this protocol"). QUIC orders each stream separately: "only streams with data in that packet are blocked" (RFC 9000 13). See Head-of-line blocking.
2 — A Go service makes 200 requests per second to one HTTP/1.1 backend with 50 ms latency using http.DefaultClient. What two problems does it have, and how do you fix them? Must-know
Answer
Answer: No timeout at all, and MaxIdleConnsPerHost = 2 while about 10 connections are in flight, so connections are closed and reopened after every burst (handshakes, TIME_WAIT). Use a dedicated Transport with MaxIdleConnsPerHost around 10-64, ResponseHeaderTimeout, Client.Timeout, and drain bodies. See Client pools.
3 — Your Go client sets a custom TLSClientConfig and suddenly every response is HTTP/1.1. Why? Important
Answer
Answer: A Transport with a custom TLS config, Dial or DialContext disables HTTP/2 by default; set ForceAttemptHTTP2: true (or configure Protocols). See Negotiation.
4 — Users behind an AWS ALB see occasional 502s; the Go backend has IdleTimeout: 30s. What is happening? Important
Answer
Answer: The ALB keeps idle backend connections for 60 s; the backend closes them at 30 s, and the ALB sometimes reuses a connection at the moment it is being closed. Make the backend's idle timeout longer than the ALB's (for example 75-120 s). See Sporadic 502.
5 — Which requests may a client retry after an HTTP/2 GOAWAY with last-stream-id 5, if it had streams 3, 5 and 7 open? Good to know
Answer
Answer: Stream 7 (higher than the last processed ID) is guaranteed unprocessed and may be retried, even a POST. Streams 3 and 5 may have been processed: retry only if idempotent or keyed. RFC 9113 8.7.
6 — Why did browsers remove HTTP/2 server push, and what replaces it? Good to know
Answer
Answer: Few sites used it (1.25% per Chrome), it often pushed cached or unneeded bytes, and results showed no clear gain. 103 Early Hints and rel=preload / rel=preconnect let the browser decide. See Push and hints.
7 — How does a browser find out a site supports HTTP/3, and what happens if UDP is blocked? Important
Answer
Answer: From Alt-Svc: h3=":443" on an HTTP/1.1 or HTTP/2 response (or an HTTPS DNS record with alpn=h3); it then tries QUIC on later connections. If UDP is blocked the QUIC attempt fails and the client keeps using TCP (RFC 9114 3.1). See Discovery.
8 — What is wrong with enabling 0-RTT for all requests? Important
Answer
Answer: Early data can be replayed by an attacker; a replayed POST executes twice. Allow 0-RTT only for safe methods and answer 425 Too Early otherwise (RFC 8470). See 0-RTT.
9 — A gzip middleware is added and conditional requests stop producing 304s for some clients, or caches serve gzip to clients that did not ask. What two headers need attention? Important
Answer
Answer: Vary: Accept-Encoding so caches keep separate copies, and ETag: a compressed representation needs a different (or weak) ETag, and the 304 must carry the same validator the 200 would. See Compression and the server package.
10 — A Laravel app on PHP-FPM calls four internal services per page. Why does Http::pool help, and what does it not fix? Must-know
Answer
Answer: The pool runs the calls concurrently on one shared Guzzle/curl handler, so latency becomes the slowest call and connections (and h2 streams with version 2.0) are shared within the pool. It does not keep connections between web requests: each FPM request starts cold. Octane or a local proxy with upstream keep-alive fixes that. See Laravel.
11 — Where should TLS terminate, and what must the application be told when it terminates at a load balancer? Must-know
Answer
Answer: Where certificates are automated and keys protected (edge, load balancer, or sidecar), re-encrypting across shared networks. The application must trust the proxy's X-Forwarded-Proto / Forwarded headers (trustProxies() in Laravel) or it will think requests are plain HTTP. See HTTPS everywhere.
12 — Why can a single HTTP/2 or gRPC client overload one backend behind an L4 load balancer? Important
Answer
Answer: The L4 balancer chooses a backend per connection; one long-lived h2 connection carries every stream of that client to the same backend. Balance per request at L7, cap concurrent streams and rotate connections with GOAWAY. See HTTP/2 overloads one backend.
Glossary
| Term | Meaning |
|---|---|
| HTTP semantics | Methods, status codes, fields and caching shared by every version (RFC 9110, 9111) |
| HTTP/1.0 | RFC 1945; one request per connection unless the unofficial keep-alive is used |
| HTTP/1.1 | RFC 9112; persistent connections by default, text messages, Host required |
| HTTP/2 | RFC 9113; binary frames, streams multiplexed over one TCP connection, HPACK |
| HTTP/3 | RFC 9114; HTTP over QUIC streams, QPACK |
| QUIC | RFC 9000; encrypted, multiplexed transport over UDP with TLS 1.3 built in |
| Persistent connection | A connection reused for several request/response exchanges |
| Keep-alive | Common name for persistent connections; also the HTTP/1.0 Connection: keep-alive option |
| TCP keep-alive | OS-level probes on idle sockets; unrelated to HTTP keep-alive |
| Pipelining | Sending several HTTP/1.1 requests without waiting; responses in order |
| Head-of-line blocking | The first item in a queue stalls everything behind it (HTTP order, TCP order) |
| Chunked transfer encoding | HTTP/1.1 body as length-prefixed chunks, ending with a zero chunk and optional trailers |
| Trailers | Fields sent after the body (gRPC status) |
| Host header | Names the target site; mandatory in HTTP/1.1, :authority in h2/h3 |
Expect: 100-continue | Asks the server to approve headers before a large body is sent |
| Request smuggling | Hiding a request inside another by exploiting framing disagreements between hops |
| Binary framing | HTTP/2's 9-byte-header frames (DATA, HEADERS, SETTINGS...) |
| Stream | One request/response exchange inside an HTTP/2 or QUIC connection |
| Multiplexing | Interleaving frames of many streams on one connection |
| HPACK | RFC 7541 header compression for HTTP/2: static table, dynamic table, Huffman |
| QPACK | RFC 9204 header compression for HTTP/3 that reduces head-of-line blocking |
| Flow control | Per-stream and per-connection windows refilled by WINDOW_UPDATE (h2) or MAX_STREAM_DATA (QUIC) |
| Prioritisation | Telling the server what matters first; RFC 7540 tree deprecated, RFC 9218 Priority header |
| Server push | Server-initiated responses via PUSH_PROMISE; disabled in Chrome 106 and Firefox 132 |
| 103 Early Hints | RFC 8297 interim response carrying Link headers before the final response |
| preload | rel=preload link: fetch this resource now (as=style, script, font) |
| preconnect | rel=preconnect link: open DNS, TCP and TLS to an origin now |
| ALPN | TLS extension (RFC 7301) negotiating http/1.1, h2 or h3 |
| h2 | HTTP/2 over TLS (ALPN identifier) |
| h2c | Cleartext HTTP/2, today started by prior knowledge |
| Prior knowledge | Client starts HTTP/2 directly with the connection preface (RFC 9113 3.3) |
| Connection preface | Fixed string plus SETTINGS that opens every HTTP/2 connection |
| Connection coalescing | Reusing one h2/h3 connection for several hostnames with the same IP and a valid certificate |
| 421 Misdirected Request | Server refuses a request that arrived on a coalesced connection |
| GOAWAY | Frame announcing shutdown and the last stream that may have been processed |
| RST_STREAM | Frame aborting one HTTP/2 stream with an error code |
| REFUSED_STREAM | Error code meaning "not processed": safe to retry |
| Rapid Reset | CVE-2023-44487: flooding a server with stream open-and-cancel |
| Connection ID | QUIC identifier that lets a connection survive address changes |
| Connection migration | Moving a QUIC connection to a new IP/port without a new handshake |
| 0-RTT | Sending data in the first flight of a resumed TLS 1.3/QUIC handshake; replayable |
| Early-Data | Header marking requests received as early data (RFC 8470) |
| 425 Too Early | Status asking the client to retry after the handshake completes |
| Alt-Svc | Header advertising an alternative endpoint, e.g. h3=":443"; ma=86400 (RFC 7838) |
| HTTPS DNS record | SVCB-type record (RFC 9460) advertising ALPN and endpoints before connecting |
| HTTPS | HTTP over TLS (https scheme) |
| TLS termination | Point where TLS is decrypted (edge, load balancer, sidecar, app) |
| HSTS | Strict-Transport-Security: browser uses only HTTPS for max-age seconds (RFC 6797) |
| HSTS preload | Browser-shipped list of HSTS hosts; needs 1-year max-age, includeSubDomains, preload |
| ACME | RFC 8555 protocol for automated certificate issuance (Let's Encrypt) |
| ARI | ACME Renewal Information: the CA tells clients when to renew |
| SNI | TLS extension carrying the hostname; used for routing and certificate choice |
| Content negotiation | Choosing a representation from Accept* headers and q-values |
| Accept-Encoding | Request header listing acceptable content codings |
| Content-Encoding | Response header naming the coding applied (gzip, br, zstd) |
| Vary | Response header listing request headers that change the response; cache key input |
| gzip | DEFLATE-based content coding, universal |
| Brotli | br coding (RFC 7932), better ratio for text |
| zstd | Zstandard coding (RFC 8878), fast with good ratio |
| ETag | Validator identifying a representation version; strong or weak (W/) |
| Conditional request | Request with If-None-Match, If-Modified-Since, If-Match... |
| 304 Not Modified | Validation succeeded; no body |
| 412 Precondition Failed | If-Match failed; protects against lost updates |
| Cache-Control | Directives for caches: max-age, s-maxage, no-cache, no-store, private, immutable |
| Range request | Range: bytes=a-b for part of a representation |
| 206 Partial Content | Range served; Content-Range says which bytes |
| 416 Range Not Satisfiable | Requested range outside the representation |
| Safe method | Read-only by definition: GET, HEAD, OPTIONS, TRACE |
| Idempotent method | Repeating it has the same intended effect: safe methods, PUT, DELETE |
| Status code | Three-digit result; families 1xx-5xx |
| Idle timeout | How long an unused keep-alive or QUIC connection stays open |
| Header timeout | Limit on receiving request headers (server) or response headers (client) |
| MaxIdleConnsPerHost | Go Transport limit on idle pooled connections per host; default 2 |
| MaxConnsPerHost | Go Transport cap on all connections per host; a bulkhead |
| ForceAttemptHTTP2 | Go Transport flag keeping h2 when TLS config or dialer is customised |
| HTTP client pool | Set of reusable connections (and in Laravel, Http::pool for concurrent requests) |
| curl multi | libcurl interface running many transfers concurrently and multiplexing h2 |
| Guzzle | PHP HTTP client under Laravel's HTTP client; curl handlers |
| Laravel Octane | Long-lived Laravel workers (FrankenPHP, Swoole, RoadRunner) |
| gRPC | RPC framework over HTTP/2 with Protobuf and trailers |
| WebSocket over h2 | RFC 8441 extended CONNECT with :protocol websocket on one stream |
| Extended CONNECT | CONNECT with a :protocol pseudo-header, enabled by SETTINGS_ENABLE_CONNECT_PROTOCOL |
| Domain sharding | Spreading assets over hostnames to get more HTTP/1.1 connections; obsolete with h2 |
| Request coalescing | Collapsing identical concurrent requests into one upstream fetch (CDN collapsed forwarding, Go singleflight) |
| Slowloris | Attack holding connections open by sending headers very slowly |
References
- RFC 9110 HTTP Semantics, RFC 9111 HTTP Caching, RFC 9112 HTTP/1.1, RFC 9113 HTTP/2, RFC 9114 HTTP/3, all June 2022
- RFC 1945 HTTP/1.0 (May 1996); RFC 2068 HTTP/1.1 (January 1997); RFC 7540 HTTP/2 (May 2015)
- RFC 7541 HPACK; RFC 9204 QPACK; RFC 9218 Extensible Prioritization Scheme for HTTP
- RFC 9000 QUIC; RFC 9001 Using TLS to Secure QUIC; RFC 7838 HTTP Alternative Services; RFC 9460 SVCB and HTTPS DNS records; RFC 7301 ALPN
- RFC 8441 Bootstrapping WebSockets with HTTP/2; RFC 9220 Bootstrapping WebSockets with HTTP/3; RFC 8470 Using Early Data in HTTP; RFC 8297 103 Early Hints
- RFC 6797 HSTS; RFC 8555 ACME; RFC 8737 ACME TLS-ALPN-01; hstspreload.org; Let's Encrypt, "Decreasing Certificate Lifetimes to 45 Days", 2 December 2025
- RFC 7932 Brotli; RFC 8878 Zstandard
- Chrome for Developers, Remove HTTP/2 Server Push from Chrome and Early Hints; MDN, Firefox 132 release notes, 103 Early Hints, Alt-Svc, Strict-Transport-Security, rel=preconnect, rel=preload
- NVD, CVE-2023-44487 (HTTP/2 Rapid Reset)
- Go:
net/http,golang.org/x/net/http2,x/net/http2/h2c, Go 1.24 release notes,transport.go,server.go - quic-go: HTTP/3, Serving HTTP/3, Dialing HTTP/3
- Laravel 13: HTTP Client, Responses (cache.headers), Middleware, Requests (trusted proxies), Octane, Vite; framework source
PendingRequest,Pool,SetCacheHeaders,AddLinkHeadersForPreloadedAssets - PHP and curl:
curl_multi_init,curl_multi_exec,curl_multi_setopt, cURL constants, libcurl CURLMOPT_PIPELINING, curl HTTP/3; Guzzle request options,CurlFactory,CurlMultiHandler; FrankenPHP Early Hints - NGINX: ngx_http_core_module, ngx_http_v2_module, ngx_http_v3_module, ngx_http_upstream_module, ngx_http_proxy_module; Envoy protocol options
- Cloud: AWS ALB attributes, CloudFront distribution settings (HTTP/3), Cloudflare HTTP/3, Early Hints, 0-RTT
- gRPC: Core concepts, gRPC over HTTP/2 protocol