Skip to content
Commitwise
Menu
Networking

HTTP/1.1, HTTP/2 and HTTP/3

How each HTTP version moves requests over the network and why the next one was needed. Covers keep-alive and the six-connection limit, head-of-line blocking, HTTP/2 streams, header compression and the death of server push, a new client per request that throws multiplexing away, QUIC and HTTP/3 over UDP, connection migration, ALPN and Alt-Svc, and 0-RTT replay.

intermediate

The core idea with one simple example.Step by step, with more examples and exercises.A cheat sheet: key APIs, gotchas and trade-offs.Internals, trade-offs and production pitfalls.

The meaning of HTTP hasn’t changed since the 1990s: methods, status codes and headers from HTTP: methods, status codes and headers work the same in every version. What changed is how requests travel: one at a time as text over TCP, then many at once in binary frames over one TCP connection, and now over QUIC on UDP.

Each version fixed the main performance problem of the one before, and each fix explains a piece of advice you’ll hear: reuse one HTTP client, stop bundling everything into one file, expect mobile apps to switch networks mid-request. Interviews ask “what’s the difference between HTTP/1.1, 2 and 3?” constantly; the good answer is about head-of-line blocking at different layers. This lesson builds on TCP vs UDP.

New to some of these? Open what you need, or skip ahead.

Basics:TCP connections and round trips

TCP gives a reliable, ordered connection, opened with a handshake that costs one round trip (a message there and back). TLS adds another. When a packet is lost, TCP resends it and holds back everything after it until it arrives. See TCP vs UDP.

Basics:An HTTP request

An HTTP request is a method and path (GET /api/orders), headers like Host and Authorization, and an optional body. The response has a status code, headers and a body. See HTTP: methods, status codes and headers.

Part Not started

HTTP/1.1: one request at a time

HTTP/1.1 (1997, still everywhere) is plain text over a TCP connection, and a connection carries one request at a time: send a request, wait for the whole response, then send the next.

Early HTTP opened a new connection for every request. HTTP/1.1 made keep-alive the default: after a response, the connection stays open and the next request reuses it, skipping the TCP and TLS handshakes. On a mobile network that saves two round trips, often 100 to 300 ms, per request.

The remaining problem is waiting in line. If the first response is slow (a big image, a slow database query), everything queued behind it on that connection waits. This is head-of-line blockingHead-of-line blockingWhen the first item in a queue is slow and everything behind it has to wait.Open in glossary →: the request at the front of the line holds up the rest.

Browsers work around it by opening several connections to the same host, usually six. A page with 60 small images on one host downloads them six at a time. Web developers built tricks around that limit:

  • Bundling: combine all JavaScript into one big file and all CSS into another.
  • Sprites: put many small icons into one image and show parts of it.
  • Domain sharding: spread files over img1.shop.example, img2.shop.example… to get six connections per name.

They all reduce the number of requests, because with HTTP/1.1 every request costs a place in a short queue.

  • Wire format: text start line and headers, \r\n separators, bodies framed by Content-Length or chunked encoding. Header names and values repeat in full on every request (cookies and tokens can be several KB per request).
  • Keep-alive is default in 1.1 (Connection: close opts out). Servers and proxies close idle connections after their own timeout; clients that reuse a just-closed connection get a reset (retry idempotent requests).
  • Pipelining (sending several requests without waiting) was in the spec but responses must come back in order, so one slow response still blocks the rest, and buggy proxies broke it. Browsers never enabled it by default.
  • Per-host connection limits: about 6 in browsers; each connection pays its own handshakes and its own TCP slow start, and competes with the others for bandwidth.
  • HTTP/1.1 is still the norm between many internal services, load balancers and back ends, and for curl-style tools. It’s simple to debug and has no stream-level complexity, which is why it survives.

Predict the output

curl downloads the same URL twice in one command. What does the verbose output say before the second request?

curl -sv -o /dev/null -o /dev/null https://example.com/ https://example.com/ 2>&1 \
  | grep -iE 'Connected to|re-using|using HTTP'
GET /api/orders?page=2 HTTP/1.1
Host: shop.example
Accept: application/json
Accept-Encoding: gzip, br
Authorization: Bearer eyJhbGciOi...
Connection: keep-alive

HTTP/1.1 200 OK
Content-Type: application/json
Content-Encoding: gzip
Content-Length: 1834
Keep-Alive: timeout=5

(1,834 bytes of gzip-compressed JSON)

Worked example: a product page over HTTP/1.1

A product page needs the HTML, one CSS file, one JavaScript bundle and 12 product images, all from shop.example. The round trip is 100 ms, and each file takes about one round trip to download.

  1. First connection. DNS, the TCP handshake and the TLS handshake: about 300 ms before the first byte of the request.
  2. The HTML. Request and response on that connection: 100 ms more. Now the browser knows what else it needs.
  3. More connections. It opens up to five more connections to the same host (each paying its own handshakes, in parallel) and starts the CSS and JavaScript.
  4. Images in waves. Twelve images over six connections: two waves of six, about 200 ms, if nothing is slow.
  5. One slow image. If one image takes a second (a big file, a slow server), the requests queued behind it on that connection wait. The page looks half-loaded.
  6. Total. Roughly 700 to 800 ms for a small page, mostly spent waiting for round trips, not downloading.

That’s the situation HTTP/2 was designed to fix: fewer connections, no queue per connection.

Deep diveWhich HTTP/1.1 optimizations to undoInterview favorite

“We’re moving to HTTP/2. Which front-end performance tricks still make sense?” The tricks existed because requests were expensive; with multiplexing they’re cheap, so some tricks now hurt.

  • Domain sharding: remove it. Extra hostnames mean extra DNS lookups, TCP and TLS handshakes, and separate congestion windows that compete. With HTTP/2, one connection does better. (Browsers can coalesce connections across names that share an IP and certificate, which partly rescues old sharding.)
  • Sprites and inlining: mostly remove. One huge sprite is cached and invalidated as a whole, and inlined images or CSS can’t be cached separately. Individual files cache better and cost little to request.
  • Bundling: keep, but smaller. One giant bundle means a one-line change invalidates everything in the cache. Split per route and per rarely changing vendor code. Very many tiny files still have per-request overhead (headers, server work, priority handling), so “hundreds of unbundled modules” isn’t free either.
  • Still matters: compression, caching headers, fewer sequential round trips (a request chain where each call needs the previous result can’t be parallelized by any protocol), image sizes, and putting the server close to users.

For mobile APIs the same logic applies: under HTTP/2, a few parallel small requests are fine, and a screen that waits for five calls one after another is slow on every version.

  • Text protocol; one request in flight per connection; keep-alive default; pipelining unusable (in-order responses).
  • About 6 connections per host in browsers, each with its own handshakes and slow start.
  • Sharding, sprites and inlining were HTTP/1.1 workarounds; under HTTP/2 remove sharding and sprites, keep moderate bundling.
  • Sequential request chains are slow on every version.
curl -sv --http1.1 -o /dev/null https://example.com/ 2>&1 | grep -i alpn
# * ALPN: curl offers http/1.1
# * ALPN: server accepted http/1.1

Check this part

  1. What does keep-alive save?

  2. Why do browsers open several connections to one host under HTTP/1.1?

  3. Why was HTTP/1.1 pipelining never enabled by default in browsers?

  4. After moving to HTTP/2, what should happen to domain sharding?

HTTP/1.1 sends text requests one at a time per connection. Keep-alive reuses a connection for later requests, but a slow response blocks the ones queued behind it (head-of-line blocking), so browsers open about six connections per host. Workarounds like bundling, sprites and domain sharding came from this limit.

Part Not started

HTTP/2: many requests on one connection

HTTP/2 (2015) keeps everything about HTTP’s meaning and changes the delivery. Instead of text, each request and response is cut into small binary frames, and each request gets a numbered stream. Frames from different streams are mixed on one connection:

one TCP connection:
  [stream 1: headers] [stream 3: headers] [stream 1: data] [stream 5: headers] [stream 3: data] ...

So the browser or app sends all its requests at once, and responses come back in whatever order they’re ready. A slow response no longer blocks a fast one. This is multiplexing, and it means one connection per host is enough.

Two more improvements:

  • Header compression (HPACK): headers like Authorization, User-Agent and cookies repeat on every request. HTTP/2 remembers headers it has already sent on the connection and sends a short reference instead, which helps a lot when a token is 1 KB.
  • Priorities: the client can hint which responses matter most (the CSS before images below the fold).

The browser and server agree on HTTP/2 during the TLS handshake (a step called ALPN), so the URL stays https:// and nothing changes for the app’s code. In practice HTTP/2 is only used over TLS.

For apps, the lesson is simple: create one HTTP client and reuse it. The connection, and with it the multiplexing, lives inside the client.

  • Framing: HEADERS, DATA, SETTINGS, WINDOW_UPDATE, RST_STREAM, GOAWAY, PING frames; per-stream and per-connection flow control; SETTINGS_MAX_CONCURRENT_STREAMS (often 100 to 250) caps parallel requests per connection.
  • HPACK uses a static and a dynamic table per connection; it was designed to resist CRIME-style attacks that broke compression-based header schemes.
  • TCP head-of-line blocking remains: all streams share one TCP byte stream, so one lost packet stalls every stream until retransmission. On lossy mobile links with a few percent loss, HTTP/2 on one connection can be slower than HTTP/1.1 on six.
  • Server push (sending resources before they’re asked for) is gone: rarely helped, often wasted bandwidth on cached files. Chrome removed it in 2022 and Firefox in 2024; use 103 Early Hints and <link rel=preload> instead.
  • Prioritization: the original dependency tree was complex and poorly implemented; RFC 9218 replaced it with a simple Priority header (urgency and incremental).
  • Operations: GOAWAY for graceful shutdown; L4 load balancers pin all of a client’s streams to one back end (gRPC); a single connection is one point of failure, so clients need health pings and reconnection. Attacks like Rapid Reset (2023: open and cancel streams in a loop) required server-side limits.
  • h2c (HTTP/2 without TLS) exists for internal traffic and gRPC; browsers don’t support it.

Predict the output

The server supports HTTP/2 and curl offers it. What does the first line of the response headers say?

curl -sI https://example.com/ | head -1
// URLSession.shared, or one configured session kept for the app's lifetime
final class Http {
    static let session: URLSession = {
        let config = URLSessionConfiguration.default
        config.timeoutIntervalForRequest = 30
        return URLSession(configuration: config)    // HTTP/2 and HTTP/3 negotiated automatically
    }()
}
// one OkHttpClient for the app (or one per base configuration), shared everywhere
object Http {
    val client: OkHttpClient = OkHttpClient.Builder()
        .connectTimeout(10, TimeUnit.SECONDS)
        .readTimeout(30, TimeUnit.SECONDS)
        .build()                                    // HTTP/2 is negotiated automatically over TLS
}

// a variation shares the connection pool and threads
val uploads = Http.client.newBuilder().writeTimeout(5, TimeUnit.MINUTES).build()
// one HttpClient for the application; it is thread-safe and keeps the connections
final class Http {
    static final HttpClient CLIENT = HttpClient.newBuilder()
            .version(HttpClient.Version.HTTP_2)     // prefers h2, falls back to HTTP/1.1
            .connectTimeout(Duration.ofSeconds(10))
            .build();
}

The app that never reused a connection

Spot the bugLoading a product

Tap the line with the bug.

func loadProduct(id: Int) async throws -> Product {
    let session = URLSession(configuration: .default)
    let url = URL(string: "https://api.shop.example/products/\(id)")!
    let (data, _) = try await session.data(from: url)
    return try JSONDecoder().decode(Product.self, from: data)
}
suspend fun loadProduct(id: Long): Product = withContext(Dispatchers.IO) {
    val client = OkHttpClient()
    val request = Request.Builder()
        .url("https://api.shop.example/products/$id")
        .build()
    client.newCall(request).execute().use { response ->
        Json.decodeFromString(response.body!!.string())
    }
}
Product loadProduct(long id) throws Exception {
    HttpClient client = HttpClient.newHttpClient();
    HttpRequest request = HttpRequest.newBuilder(
            URI.create("https://api.shop.example/products/" + id)).build();
    HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
    return mapper.readValue(response.body(), Product.class);
}

Deep diveWhen HTTP/2 is slower than HTTP/1.1Interview favorite

“We enabled HTTP/2 and some users got slower. How?” A few real mechanisms:

  • Packet loss: all streams share one TCP connection, so each lost packet stalls all of them, and congestion control halves the single window. Six HTTP/1.1 connections lose only one sixth of their capacity per loss event. On mobile networks with a few percent loss, the single connection can lose. This is the main argument for HTTP/3.
  • Bad prioritization: the server sends large images interleaved with critical CSS, so the page renders later even though bytes arrive sooner. Many CDNs and servers implemented the old priority tree poorly.
  • One big download hogs the connection: a large file and small API calls on one connection share one congestion window; flow-control windows that are too small cap throughput on high-latency links (window / RTT).
  • Proxies in between: an L7 proxy that speaks HTTP/2 to the client and HTTP/1.1 to the origin with few connections reintroduces queueing at the back.
  • Connection coalescing surprises: browsers reuse a connection for another hostname on the same IP and certificate, and a server that routes by Host in a way that doesn’t expect it may return 421 Misdirected Request.

The answer that impresses: measure per network type (RUM data split by connection type and loss), keep critical resources small and early, check that the CDN implements RFC 9218 priorities, and enable HTTP/3 for the lossy mobile tail rather than turning HTTP/2 off.

  • Binary frames on numbered streams over one connection; HPACK; flow control per stream; max concurrent streams.
  • Fixes HTTP-level HOL blocking, not TCP-level: one loss stalls every stream; worse than 6 connections on lossy links.
  • Server push removed (use 103 Early Hints, preload); RFC 9218 priorities; ALPN h2; h2c only internal.
  • Reuse one client (pool lives in it); GOAWAY, L4 pinning, Rapid Reset limits.
val client = OkHttpClient()            // once per app; HTTP/2 via ALPN
val api = client.newBuilder()          // variants share pool and dispatcher
    .readTimeout(60, TimeUnit.SECONDS).build()

Check this part

  1. What lets HTTP/2 send many requests at once on one connection?

  2. Why should an app keep one HTTP client instead of creating one per request?

  3. What problem does HTTP/2 NOT solve?

  4. What replaced HTTP/2 server push in browsers?

HTTP/2 splits requests into binary frames on numbered streams, so many requests share one TCP connection at the same time, with compressed headers (HPACK). It removes HTTP-level head-of-line blocking, but a lost TCP packet still stalls every stream. Server push is gone. Clients must reuse one connection, which means one HTTP client instance.

Part Not started

HTTP/3: HTTP over QUIC

HTTP/2 fixed waiting in line inside HTTP, but all its streams still ride on one TCP connection, and TCP delivers bytes strictly in order. When one packet is lost, TCP holds back everything after it, including data for other streams that arrived fine. On a train, in an elevator, on a weak mobile signal, that happens all the time.

HTTP/3 (2022) replaces TCP with QUICQUICA transport protocol over UDP with reliable streams and TLS 1.3 built in; the base of HTTP/3.Open in glossary →, a new transport protocol that runs on top of UDP. QUIC does the reliable delivery itself, per stream: a lost packet only delays the stream it belonged to.

It brings three more advantages:

  • Faster setup: QUIC includes TLS 1.3 in its own handshake, so a new connection needs one round trip instead of two or three (TCP plus TLS). Returning to a server you’ve used before can even send the request with the very first packet (0-RTT).
  • Connection migration: a TCP connection is tied to your IP address and port, so walking out of Wi‑Fi onto mobile data breaks every connection. A QUIC connection has its own connection ID, so it can continue on the new network.
  • Always encrypted: even most of QUIC’s own control information is encrypted.

How does a client know a server speaks HTTP/3? The first visit uses HTTP/2, and the server answers with a header like alt-svc: h3=":443"; ma=86400 (“I also speak HTTP/3 on port 443, remember it for a day”). Newer clients can learn it earlier from a DNS HTTPS record. Some networks block UDP, so clients always keep HTTP/2 as a fallback.

On mobile, URLSession (iOS 15 and later) and Chrome’s Cronet library on Android use HTTP/3 automatically when the server supports it.

  • QUIC: streams with independent reliability and flow control, TLS 1.3 integrated (QUIC packets are encrypted, headers largely too), congestion control in user space (CUBIC or BBR, easy to update without kernel changes), connection IDs for migration and NAT rebinding, QPACK header compression (HPACK adapted to out-of-order delivery).
  • Handshake: 1 RTT for a new connection; 0-RTT on resumption sends early data that an attacker can replay. Servers must accept it only for idempotent requests or reject it; RFC 8470 defines Early-Data: 1 and status 425 Too Early for origins behind a proxy.
  • Discovery: Alt-Svc header (first visit is HTTP/2), DNS HTTPS/SVCB records with alpn="h3"; clients race QUIC against TCP and remember failures, because some networks block or throttle UDP.
  • Costs: more CPU per byte than kernel TCP with hardware offload (improving with GSO and better libraries); load balancers must route by connection ID, not by 4-tuple, to keep migrated connections on the same back end; observability tools see less, since packets are encrypted.
  • Support: all major browsers, Cloudflare, Google, Fastly, Akamai and NGINX; iOS URLSession; Android via Cronet (OkHttp doesn’t do HTTP/3); Java’s HttpClient added it in JDK 26 as an opt-in (HttpClient.Version.HTTP_3; HTTP/2 stays the default). Origins often keep HTTP/1.1 or HTTP/2 behind a CDN that terminates HTTP/3 at the edge.

Predict the output

A client fetches a page twice from a server that supports HTTP/3. The first response, over HTTP/2, includes the header below. What does a browser usually use for the second request a minute later?

$ curl -sI https://www.cloudflare.com/ | grep -i alt-svc
alt-svc: h3=":443"; ma=86400
# does the server advertise HTTP/3?
curl -sI https://www.cloudflare.com/ | grep -i alt-svc

# DNS HTTPS record (type 65): alpn list, IP hints (older dig prints it as hex)
dig +short TYPE65 cloudflare.com        # newer dig: dig +short HTTPS cloudflare.com

# with a curl built with HTTP/3 support (curl -V lists "HTTP3")
curl -sI --http3-only https://www.cloudflare.com/ | head -1      # HTTP/3 200

# which version each request used (browser): DevTools > Network > Protocol column (h2, h3)

Practice: counting round trips

Exerciseeasy

How long until the first byte?

A phone opens a brand-new connection to api.shop.example (DNS already cached) and sends one GET. The round-trip time is 80 ms. Ignoring server processing time, how long until the first byte of the response arrives with:

  1. HTTP/1.1 over TCP with TLS 1.2 (2 round trips for TLS)?
  2. HTTP/2 over TCP with TLS 1.3 (1 round trip for TLS)?
  3. HTTP/3 over QUIC (transport and TLS together in 1 round trip)?
  4. HTTP/3 with 0-RTT to a server the phone has used before?
›

Count: the TCP handshake, then the TLS handshake, then one more round trip for the request and the start of the response.

SolutionTry it yourself first
  1. TCP 1 + TLS 2 + request 1 = 4 round trips, 320 ms.
  2. TCP 1 + TLS 1 + request 1 = 3 round trips, 240 ms.
  3. QUIC with TLS 1 + request 1 = 2 round trips, 160 ms.
  4. The request travels in the first flight of packets: 1 round trip, 80 ms.

The HTTP version itself doesn’t make the request faster; the savings come from fewer handshakes. That’s also why reusing a connection, which skips them all, matters even more than the version: a reused connection is always 1 round trip.

Deep dive0-RTT and the replay problemInterview favorite

“0-RTT sounds free. What’s the catch?” With TLS 1.3 session resumption (and in QUIC), a client can send application data in its very first flight, encrypted with a key from the previous session. The server can’t yet prove that this flight is fresh: an attacker who captured it can send the same bytes again, and the server will decrypt and process them again. TLS 1.3 forward secrecy also doesn’t cover early data the same way.

So 0-RTT data must be treated as possibly replayed:

  • Accept only idempotent, safe requests in early data: GET /products is fine, POST /payments is not. Many servers and CDNs allow only GET without a query or with an allow-list, or disable 0-RTT entirely.
  • Behind a CDN, the edge forwards early data with Early-Data: 1; the origin can answer 425 Too Early to make the client retry after the handshake completes.
  • Servers can limit replay with single-use tickets or a replay cache, which doesn’t scale well across many servers, which is why the rule above is the real defence.

It’s a good example of a protocol trade-off: one round trip saved for returning users, in exchange for a guarantee you now have to provide at the application level. Idempotency, from the HTTP methods lesson, is again the property that decides what’s safe.

  • QUIC over UDP: per-stream reliability (no TCP HOL), TLS 1.3 built in, 1-RTT setup, 0-RTT resumption, connection IDs for migration, QPACK, user-space congestion control.
  • 0-RTT is replayable: idempotent requests only, Early-Data + 425 Too Early.
  • Discovery via Alt-Svc or DNS HTTPS records; race against TCP; fall back when UDP is blocked.
  • Costs: CPU, connection-ID-aware load balancing, less visibility. iOS URLSession and Cronet support it; OkHttp doesn’t.
HTTP/2 200
alt-svc: h3=":443"; ma=86400

Check this part

  1. What does HTTP/3 run on?

  2. A user walks from Wi-Fi onto mobile data during a download. Which version can keep the same connection?

  3. Which requests are safe to accept as 0-RTT early data?

  4. Why does a client still keep HTTP/2 available when the server supports HTTP/3?

HTTP/3 runs over QUIC, a transport on UDP with TLS 1.3 built in. Each stream is delivered independently, so a lost packet only delays its own stream; setup takes one round trip (zero on resumption, with replay risk), and connections survive switching from Wi-Fi to mobile. Clients discover it through Alt-Svc or DNS HTTPS records and fall back to HTTP/2 where UDP is blocked.

Key takeaways

  • HTTP/1.1: one request at a time per connection; keep-alive reuses connections; browsers open about six per host.
  • HTTP/2: many requests at once on one connection (streams), compressed headers.
  • HTTP/3: QUIC over UDP, a lost packet delays only its own stream, faster setup, survives network switches.
  • The meaning of HTTP (methods, codes, headers) is the same in all versions.
  • Reuse one HTTP client: that’s where connections, and all these benefits, live.
  • HOL blocking moved: HTTP/1.1 per connection, HTTP/2 at the TCP layer, HTTP/3 removes it across streams.
  • Undo sharding and sprites under HTTP/2; sequential request chains stay slow on every version.
  • Server push is dead; use Early Hints and preload; RFC 9218 priorities.
  • QUIC: 1-RTT, replayable 0-RTT, connection migration, Alt-Svc or HTTPS-record discovery, TCP fallback.
  • HTTP/2 can lose to HTTP/1.1 on lossy links; HTTP/3 is the fix for that tail.

Finished this page?Nice work, this page is complete!

Mark it as done to track your progress. It's saved in this browser, no account needed.

Its cards are now in your Bites review ⚡
Esc

Type to search the whole site.