HTTP/1.1, HTTP/2, HTTP/3
- Explain the problem each HTTP version solves: persistent connections, multiplexing, header compression, transport-level head-of-line blocking
- Describe HTTP/2 framing, streams, HPACK and flow control, and why server push was abandoned
- Explain how QUIC delivers 1-RTT/0-RTT setup and connection migration, and the risk of 0-RTT replay for payments
- Choose
Cache-Control,ETagandVarysettings for product pages, static assets and account balances - Configure cookies (
Secure,HttpOnly,SameSite, prefixes) and CORS correctly for a banking web app
TL;DR
- HTTP/1.1: text protocol, persistent connections by default, one request at a time per connection. Pipelining exists but is effectively dead (responses must come back in order). Browsers open ≈6 connections per origin to get parallelism.
- HTTP/2: same semantics (methods, headers, status codes), new wire format — binary frames on multiplexed streams over one TCP connection, HPACK header compression, per-stream flow control. Fixes HTTP-level head-of-line blocking but not TCP's. Server push is deprecated; use
103 Early Hintsor preload. - HTTP/3: HTTP over QUIC over UDP. TLS 1.3 is built in, setup is 1 RTT (0 RTT on resumption), streams are independent at the transport layer, and connection IDs let a phone move from Wi-Fi to 4G without reconnecting.
- 0-RTT data can be replayed. Only allow it for safe, idempotent requests — never for "create payment".
- Caching:
no-storefor sensitive data (balances, statements), longmax-age+immutablefor fingerprinted assets,s-maxage+stale-while-revalidatefor CDN-cached pages,ETagfor cheap revalidation. - Cookies: session cookies should be
Secure; HttpOnly; SameSite=Lax(orStrict) and ideally__Host-prefixed. - CORS is a browser relaxation of the same-origin policy, not a server security control. Allowlist origins explicitly; never reflect arbitrary origins with credentials.
Why it matters
HTTP is the API surface of nearly every bank and e-commerce system: mobile apps, web checkout, partner APIs, webhooks. The version and the headers you choose show up directly in user-facing numbers and in security reviews:
- A product listing page that loads 80 assets over HTTP/1.1 on a mobile network waits on connection limits; HTTP/2 or HTTP/3 removes most of that queuing.
- A misconfigured
Cache-Controlon an account endpoint can let a shared cache serve one customer's balance to another — a data breach, not a bug. - A lax CORS policy on an internet banking API lets any website read authenticated responses in a victim's browser.
- Enabling TLS 1.3 0-RTT on the payments endpoint without replay protection can create duplicate charges.
Interviewers use HTTP to test depth: "What does HTTP/2 actually change?", "Why is HTTP/3 on UDP?", "How would you cache a product page during a flash sale?"
Core concepts
The protocol stacks
The semantics (methods, status codes, headers, caching rules) are shared across versions and defined once in RFC 9110 and RFC 9111. Only the wire format and transport change. That is why a reverse proxy can speak HTTP/3 to browsers and HTTP/1.1 to your Go backend.
HTTP/1.1
GET /v1/products/TSHIRT-42 HTTP/1.1
Host: shop.example.com
Accept: application/json
Accept-Encoding: gzip, br
Cookie: __Host-sid=8f3a...
HTTP/1.1 200 OK
Content-Type: application/json
Content-Encoding: br
Cache-Control: public, max-age=30, s-maxage=60
ETag: "a1b2c3"
Content-Length: 182
Key features and their limits:
- Persistent connections are the default (
Connection: closeopts out). This removed the per-request TCP handshake of HTTP/1.0. Hostheader is mandatory, enabling many sites on one IP (virtual hosting).- Chunked transfer encoding lets a server stream a response of unknown length.
- One outstanding request per connection in practice. Pipelining allows sending several requests without waiting, but responses must return in request order, so one slow response blocks the rest (application-level head-of-line blocking). Buggy proxies made it unreliable, and browsers never enabled it by default.
- Browsers compensate with ≈6 parallel connections per origin, which led to hacks: domain sharding, sprite sheets, concatenated bundles, inlined assets. Most of these are counter-productive on HTTP/2.
- Headers are uncompressed text, repeated on every request. Cookies and auth tokens can make headers larger than small API bodies.
HTTP/2
HTTP/2 (RFC 9113, originally RFC 7540) keeps HTTP semantics and replaces the wire format.
Binary framing. Everything is a frame with a 9-byte header (length, type, flags, stream ID). Important frame types:
| Frame | Purpose |
|---|---|
HEADERS (+ CONTINUATION) | Request/response headers, HPACK-compressed |
DATA | Body bytes |
SETTINGS | Connection parameters (max concurrent streams, initial window size, max frame size) |
WINDOW_UPDATE | Flow control credit, per stream and per connection |
RST_STREAM | Cancel one stream without closing the connection |
PING | Liveness and RTT measurement |
GOAWAY | Graceful shutdown: "finish streams up to ID N, open no new ones" |
PUSH_PROMISE | Server push (deprecated in practice) |
Streams and multiplexing. Each request/response pair is a stream with its own ID (client-initiated streams are odd). Frames from many streams interleave on one TCP connection, so a slow response no longer blocks others at the HTTP layer. Servers cap concurrency with SETTINGS_MAX_CONCURRENT_STREAMS (commonly 100–250).
HPACK header compression (RFC 7541) uses a static table of 61 common header fields, a per-connection dynamic table of recently sent headers, and Huffman coding. A repeated authorization or cookie header costs a few bytes after the first request. The compression state is per connection, which is one reason HTTP/2 prefers one long-lived connection per origin.
Flow control applies per stream and per connection via WINDOW_UPDATE. The default initial window is 65,535 bytes; on high-latency links, large uploads crawl unless the implementation raises it.
Server push let the server send resources the client had not requested. In practice it often pushed assets the browser already had cached, wasted bandwidth and was hard to tune. Chrome removed it (2022) and it is effectively dead. Alternatives: Link: rel=preload headers and 103 Early Hints, which let the CDN tell the browser what to fetch while the origin is still computing the page.
What HTTP/2 does not fix: all streams share one TCP connection, so one lost TCP segment stalls all streams until it is retransmitted (TCP head-of-line blocking). On a clean data-center network this rarely matters; on lossy mobile networks it can.
Other notes:
- Browsers only use HTTP/2 over TLS (
h2, negotiated with ALPN). Cleartexth2cexists and is used internally (e.g. gRPC without TLS inside a mesh). - Connection coalescing: a browser may reuse one HTTP/2 connection for
static.example.comandwww.example.comif they resolve to the same IP and the certificate covers both. - Security: multiplexing creates new abuse patterns. The 2023 "Rapid Reset" attack (CVE-2023-44487) opened and immediately cancelled streams to exhaust servers; patch your proxies and set stream limits.
HTTP/3 and QUIC
HTTP/3 (RFC 9114) maps HTTP semantics onto QUIC (RFC 9000), a transport built on UDP.
| Feature | How QUIC provides it | Why it matters |
|---|---|---|
| Faster setup | Transport and TLS 1.3 handshakes combined: 1 RTT for a new connection (TCP + TLS 1.3 needs 2) | ≈100 ms saved per new connection at 100 ms RTT |
| 0-RTT resumption | Client sends encrypted application data in its first flight using a resumption secret | Fastest repeat visits — but replayable |
| No transport HOL blocking | Each stream has independent ordering and loss recovery | A lost packet only stalls the stream it belongs to |
| Connection migration | Connections identified by connection IDs, not the 4-tuple | Phone switches Wi-Fi → cellular without a new handshake |
| Encrypted transport headers | Almost all of the QUIC header is encrypted | Middleboxes cannot ossify the protocol (and cannot inspect it) |
| Header compression | QPACK, a variant of HPACK tolerant of out-of-order delivery | Same savings, no cross-stream blocking |
Discovery: browsers start on HTTP/1.1 or HTTP/2 over TCP, see an Alt-Svc: h3=":443" response header (or a DNS HTTPS record), and use HTTP/3 on the next connection. If UDP is blocked (common on corporate networks), they silently fall back to TCP — so you always serve both.
Costs: QUIC runs in user space, so it uses more CPU per byte than kernel TCP; load balancers must route UDP by connection ID; observability tools that read TCP headers see nothing useful. Most teams terminate HTTP/3 at the CDN or edge proxy and speak HTTP/1.1 or HTTP/2 to origin.
0-RTT data can be captured and replayed by an attacker, and the server cannot fully prevent it across a distributed fleet. Servers should accept 0-RTT only for safe, idempotent requests (GET of public data) and reject others with 425 Too Early. For any money-moving request, also require an idempotency key — see Idempotency & Exactly-Once.
Version comparison
| HTTP/1.1 | HTTP/2 | HTTP/3 | |
|---|---|---|---|
| Transport | TCP | TCP | QUIC over UDP |
| Encoding | Text | Binary frames | Binary frames |
| Concurrency per connection | 1 request at a time | Many streams | Many streams |
| Header compression | None | HPACK | QPACK |
| Head-of-line blocking | HTTP and TCP level | TCP level only | Per stream only |
| Setup cost (new, with TLS 1.3) | 2 RTT | 2 RTT | 1 RTT (0 RTT resumed) |
| Connection migration | No | No | Yes |
| Typical place in architecture | Backend services, legacy partners | Browser ↔ edge, gRPC, service mesh | Browser/mobile ↔ CDN/edge |
Methods, idempotency and status codes architects care about
| Method | Safe | Idempotent | Note |
|---|---|---|---|
GET, HEAD | Yes | Yes | Cacheable; never change state |
PUT | No | Yes | Replace a resource; retries are safe |
DELETE | No | Yes | Second call returns 404 or 204 but state is the same |
POST | No | No | Create payment / order — needs an Idempotency-Key for safe retries |
PATCH | No | Not necessarily | Depends on the patch format |
Status codes that matter in design reviews: 304 Not Modified (revalidation), 409 Conflict (version mismatch, duplicate), 422 (validation), 425 Too Early (0-RTT rejected), 429 Too Many Requests with Retry-After, 502 Bad Gateway (proxy got an invalid response or connection reset from upstream), 503 Service Unavailable (overload, maintenance), 504 Gateway Timeout (upstream too slow).
Caching headers
HTTP caching (RFC 9111) happens in browsers (private caches) and CDNs/proxies (shared caches).
| Directive / header | Meaning |
|---|---|
Cache-Control: max-age=N | Fresh for N seconds in any cache |
s-maxage=N | Overrides max-age for shared caches (CDN) |
no-cache | May store, but must revalidate with the origin before each use |
no-store | Must not store at all — use for balances, statements, PII |
private | Only the browser may cache (per-user content) |
public | Shared caches may store, even for authenticated requests |
must-revalidate | Once stale, never serve without revalidating |
stale-while-revalidate=N | Serve stale up to N s while refreshing in the background |
stale-if-error=N | Serve stale up to N s if the origin errors — great for resilience |
immutable | The content will never change at this URL; skip revalidation |
ETag / If-None-Match | Version validator; origin answers 304 with no body if unchanged |
Last-Modified / If-Modified-Since | Time-based validator (1-second resolution) |
Vary: Accept-Encoding | Cache key includes these request headers |
Age | How long the response has been in a shared cache |
Recipes:
| Content | Header | Why |
|---|---|---|
Fingerprinted JS/CSS/images (app.3f9a1c.js) | public, max-age=31536000, immutable | New deploy = new URL; cache forever |
| Product detail page (public) | public, max-age=30, s-maxage=60, stale-while-revalidate=30, stale-if-error=600 | CDN absorbs flash-sale traffic; short staleness acceptable |
| Price / stock shown at checkout | no-cache with ETag, or not cached | Must be fresh; revalidation keeps it cheap |
| Account balance, statements, KYC documents | no-store | Never in any cache, including the browser disk |
| Logged-in user's cart | private, no-cache | Per-user; never in a shared cache |
If a response has no explicit freshness information, caches may apply heuristic freshness (often a fraction of the time since Last-Modified). Always set Cache-Control explicitly on API responses. See Caching and CDN & Edge.
Cookies
A cookie is set with Set-Cookie and sent back automatically on matching requests.
Set-Cookie: __Host-sid=8f3a2c...; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=1800
| Attribute | Effect | Recommendation for session cookies |
|---|---|---|
Secure | Only sent over HTTPS | Always |
HttpOnly | Not readable from JavaScript (limits XSS token theft) | Always |
SameSite=Strict | Never sent on cross-site requests, even top-level navigation | Internet banking (users arrive by typing the URL) |
SameSite=Lax | Sent on top-level cross-site navigations (GET), not on cross-site subrequests or POSTs | Default for most apps; Chrome treats cookies without SameSite as Lax |
SameSite=None | Sent cross-site; requires Secure | Only for genuine third-party embeds (payment iframes, SSO) |
Domain | Shares the cookie with subdomains | Avoid for session cookies — every subdomain can read it |
__Host- prefix | Browser enforces Secure, Path=/, no Domain | Use for session cookies |
Max-Age / Expires | Persistent cookie; omit for session-only | Short lifetimes for banking (plus server-side idle timeout) |
Practical limits: ≈4 KB per cookie, and every cookie is sent on every matching request — large cookies inflate every API call and static asset fetch. Serve static assets from a cookieless domain or CDN path. Browsers increasingly restrict third-party cookies; design SSO and embedded payment flows to not depend on them.
CORS
The same-origin policy stops a script on https://evil.example from reading responses from https://api.bank.example. An origin is the triple (scheme, host, port). CORS lets a server tell the browser which other origins may read its responses.
- Simple requests (
GET/HEAD/POSTwith only safelisted headers and a form-style ortext/plaincontent type) are sent directly; the browser checksAccess-Control-Allow-Originon the response before exposing it to the script. - Anything else (JSON
POST,PUT,DELETE, custom headers likeAuthorizationorIdempotency-Key) triggers a preflightOPTIONSrequest first.
Rules that keep you safe:
- Allowlist exact origins.
Access-Control-Allow-Origin: *is fine for truly public, unauthenticated data and is not allowed together withAccess-Control-Allow-Credentials: true. - Never reflect the request
Originblindly with credentials — that is equivalent to disabling the same-origin policy for your API. - Add
Vary: Originwhen the response depends on the origin, or a CDN will cache one origin's CORS headers for everyone. - Use
Access-Control-Max-Ageto cache preflights (browsers cap it — Chromium at 2 hours), saving an RTT per request. - CORS is not authentication and not CSRF protection.
curlignores it. CSRF defenses areSameSitecookies, anti-CSRF tokens and checkingOriginon state-changing requests. - The cheapest CORS is none: serve the API under the same origin (
shop.example.com/api) via the edge proxy.
Trade-offs
| Option | Strengths | Weaknesses | Choose when |
|---|---|---|---|
| HTTP/1.1 everywhere | Universal support, easy debugging, simple proxies | Connection-per-request concurrency, header overhead | Legacy partners, simple internal services behind a pool |
| HTTP/2 at edge, HTTP/1.1 to origin | Browser gets multiplexing; backends stay simple | Two protocol behaviours to reason about | Most web and mobile platforms |
| HTTP/2 end-to-end (incl. gRPC) | Few connections, multiplexed RPC, streaming | L4 load balancing becomes uneven; TCP HOL on lossy links | Internal service-to-service, service mesh |
| HTTP/3 at CDN/edge | Faster setup, better on lossy mobile networks, migration | UDP may be blocked, more CPU, newer tooling | Consumer mobile apps, global e-commerce |
| 0-RTT enabled | Lowest latency on resumption | Replay risk | Only public, idempotent GETs |
Aggressive CDN caching with stale-while-revalidate | Huge origin offload during spikes | Users can see slightly stale data | Catalog, content, flash-sale landing pages |
no-store | No risk of cached sensitive data | Every request hits the origin | Balances, PII, payment details |
In practice
Go server with caching, ETag and a strict CORS allowlist. Go's net/http serves HTTP/2 automatically when you use TLS (negotiated via ALPN). HTTP/3 is not in the standard library at the time of writing; use a library such as quic-go or, more commonly, let the edge proxy/CDN handle it.
package main
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"log"
"net/http"
"time"
)
var allowedOrigins = map[string]bool{
"https://shop.example.com": true,
"https://admin.example.com": true,
}
func cors(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
origin := r.Header.Get("Origin")
w.Header().Add("Vary", "Origin")
if allowedOrigins[origin] {
h := w.Header()
h.Set("Access-Control-Allow-Origin", origin)
h.Set("Access-Control-Allow-Credentials", "true")
if r.Method == http.MethodOptions && r.Header.Get("Access-Control-Request-Method") != "" {
h.Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE")
h.Set("Access-Control-Allow-Headers", "Content-Type, Authorization, Idempotency-Key")
h.Set("Access-Control-Max-Age", "7200")
w.WriteHeader(http.StatusNoContent)
return
}
}
next.ServeHTTP(w, r)
})
}
type product struct {
SKU string `json:"sku"`
Name string `json:"name"`
PriceMinor int64 `json:"price_minor"` // cents
Currency string `json:"currency"`
}
func getProduct(w http.ResponseWriter, r *http.Request) {
p := product{SKU: r.PathValue("sku"), Name: "T-shirt", PriceMinor: 1999, Currency: "USD"}
body, err := json.Marshal(p)
if err != nil {
http.Error(w, "encode error", http.StatusInternalServerError)
return
}
sum := sha256.Sum256(body)
etag := `"` + hex.EncodeToString(sum[:8]) + `"`
h := w.Header()
h.Set("ETag", etag)
h.Set("Cache-Control", "public, max-age=30, s-maxage=60, stale-while-revalidate=30")
// Simplified: real If-None-Match may carry a list or weak validators.
if r.Header.Get("If-None-Match") == etag {
w.WriteHeader(http.StatusNotModified)
return
}
h.Set("Content-Type", "application/json")
_, _ = w.Write(body)
}
func getBalance(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-store")
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"available_minor":1250000,"currency":"USD"}`))
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("GET /v1/products/{sku}", getProduct)
mux.HandleFunc("GET /v1/accounts/{id}/balance", getBalance)
srv := &http.Server{
Addr: ":8443",
Handler: cors(mux),
ReadHeaderTimeout: 5 * time.Second,
IdleTimeout: 120 * time.Second,
}
log.Fatal(srv.ListenAndServeTLS("server.crt", "server.key"))
}
Operational knobs worth knowing (approximate, vendor-specific):
- HTTP/2
MAX_CONCURRENT_STREAMS: commonly 100–250. Too low throttles multiplexed clients; too high amplifies abuse. - Keep the backend's HTTP keep-alive idle timeout longer than the load balancer's to avoid 502s on reused connections.
- Enable Brotli or gzip for text at the edge; never compress already-compressed images. Be aware of compression side-channel attacks (BREACH) when secrets and attacker-controlled input share a compressed response.
- For flash sales, put the landing page and catalog behind the CDN with
stale-if-errorso the store stays up even if the origin struggles.
Common pitfalls
- Domain sharding on HTTP/2. Splitting assets across
img1/img2subdomains forces extra connections and TLS handshakes and splits HPACK state. Symptom: HTTP/2 rollout shows no gain or a regression. - Missing
Cache-Controlon authenticated APIs. Symptom: a CDN or corporate proxy serves cached responses across users; one customer sees another's data. Varyforgotten. Symptom: some users receive gzip responses they cannot decode, or CORS failures for one origin after another origin warmed the cache.Vary: User-AgentorVary: Cookieon CDN content. Symptom: cache hit ratio collapses because every variant is a separate entry.- Reflecting
Originwith credentials. Symptom: a penetration test reads account data from a malicious page. - Preflight on every request. Symptom: double the RTTs for a SPA calling a different-origin API. Fix with
Access-Control-Max-Ageor same-origin routing. - Large cookies. Symptom: 431 / 400 "request header too large" from proxies after a marketing tool adds tracking cookies.
- Assuming HTTP/2 balances well behind an L4 load balancer. One client's connection pins all its requests to one backend. Symptom: one pod at 90% CPU, others idle.
- 0-RTT enabled globally at the edge. Symptom: rare duplicate side effects that only appear on resumed connections.
Interview angle
- "What changed from HTTP/1.1 to HTTP/2 to HTTP/3?" A strong answer is structured by problem: HTTP-level HOL blocking and header overhead (HTTP/2: streams, HPACK), TCP-level HOL blocking and setup latency (HTTP/3: QUIC, 1-RTT, per-stream recovery), mobility (connection IDs). Mention what stayed the same: semantics.
- "How would you make the product page fast during a flash sale?" CDN with
s-maxage,stale-while-revalidate,stale-if-error, fingerprinted immutable assets, HTTP/2 or HTTP/3 at the edge, separate the dynamic stock/price call with short TTL or no caching. - "Explain CORS." Same-origin policy, simple vs preflight, credentials rules,
Vary: Origin, and the explicit statement that CORS is enforced by browsers only. - Follow-ups: why server push failed, 0-RTT replay, why gRPC needs HTTP/2, connection coalescing,
no-cachevsno-store. - Red flags: "HTTP/2 is faster because it is binary", thinking CORS protects the API from attackers,
no-cachemeaning "do not cache", or caching personalized responses aspublic.
Self-check
1. HTTP/2 multiplexes requests on one connection. Why can it still perform worse than HTTP/1.1 on a lossy mobile network?
All HTTP/2 streams share one TCP connection, and TCP delivers bytes in order. A single lost segment blocks delivery of every stream until it is retransmitted. With six HTTP/1.1 connections, a loss on one stalls only that connection. HTTP/3 fixes this by giving each stream independent loss recovery in QUIC.
2. What is the difference between no-cache and no-store, and which do you use for an account balance?
no-cache allows storing but requires revalidation with the origin before every use (cheap with an ETag and 304). no-store forbids storing the response anywhere, including browser disk caches. An account balance is sensitive and per-user, so use no-store.
3. Why was HTTP/2 server push abandoned, and what replaced it?
The server rarely knew what the client already had cached, so it often pushed redundant bytes, competed with more important requests for bandwidth, and was hard to configure well. Measured gains were small. Browsers removed support; Link: rel=preload and 103 Early Hints let the client decide what to fetch using its own cache knowledge.
4. What does QUIC connection migration give a mobile banking app, and how does it work?
QUIC identifies a connection by connection IDs rather than the (IP, port) 4-tuple, so when the phone moves from Wi-Fi to cellular and its IP changes, the client can continue the same connection after path validation, without a new handshake. In-flight requests survive the network switch instead of failing and being retried.
5. A SPA on app.bank.example calls api.bank.example with an Authorization header and every call takes two round trips. Why, and how do you fix it?
Different host means different origin, and the Authorization header makes the request non-simple, so the browser sends a CORS preflight OPTIONS before each request. Fix by returning Access-Control-Max-Age so preflights are cached, or better, route the API through the same origin (app.bank.example/api) at the edge so no CORS is needed.
6. Why should a payments endpoint reject TLS 1.3 / QUIC 0-RTT data?
0-RTT data is sent before the handshake proves freshness, so an attacker who captured it can replay it to the server (possibly to a different node in the fleet). A replayed "create payment" request could charge twice. Accept 0-RTT only for safe, idempotent requests, reply 425 Too Early for others, and require idempotency keys on money-moving calls.
7. Choose cookie attributes for an internet banking session cookie and justify each.
__Host-sid=...; Path=/; Secure; HttpOnly; SameSite=Strict with a short lifetime. Secure keeps it off plaintext connections, HttpOnly stops JavaScript (and XSS) from reading it, SameSite=Strict blocks it on cross-site requests (CSRF), the __Host- prefix forbids Domain so no subdomain can read or overwrite it, and a short lifetime plus server-side idle timeout limit damage from theft.
Exercise
Part A — compare versions with curl.
curl -sv --http1.1 -o /dev/null https://www.cloudflare.com 2>&1 | grep -E '^(< HTTP|\* ALPN)'
curl -sv --http2 -o /dev/null https://www.cloudflare.com 2>&1 | grep -E '^(< HTTP|\* ALPN)'
curl -sI https://www.cloudflare.com | grep -i alt-svc
# Requires a curl build with HTTP/3 support (check: curl -V | grep -i http3)
curl -sv --http3 -o /dev/null https://www.cloudflare.com 2>&1 | grep -E '^< HTTP'
Then open your favourite e-commerce site in Chrome DevTools → Network, enable the Protocol column, and record which resources use h2 vs h3 and which come from the CDN cache (Age, cf-cache-status, x-cache or similar headers).
Part B — caching and CORS in Go. Run the Go server from this page (generate a self-signed cert with openssl req -x509 -newkey rsa:2048 -nodes -keyout server.key -out server.crt -days 1 -subj /CN=localhost). Verify:
curl -sk -D - https://localhost:8443/v1/products/TSHIRT-42 -o /dev/null
curl -sk -D - -H 'If-None-Match: "<etag-from-above>"' https://localhost:8443/v1/products/TSHIRT-42 -o /dev/null
curl -sk -D - -X OPTIONS -H 'Origin: https://shop.example.com' \
-H 'Access-Control-Request-Method: POST' https://localhost:8443/v1/products/TSHIRT-42 -o /dev/null
curl -sk -D - -H 'Origin: https://evil.example' https://localhost:8443/v1/products/TSHIRT-42 -o /dev/null
Done when: you get a 304 on revalidation, the allowed origin receives CORS headers, the evil origin does not, and you can write the correct Cache-Control for five endpoints of a bank app (login page, balance, statement PDF, branch locator, static JS bundle) with a one-line justification each.
Further reading
- High Performance Browser Networking — Ilya Grigorik, chapters on HTTP/1.x and HTTP/2 (hpbn.co).
- RFC 9110 — HTTP Semantics and RFC 9111 — HTTP Caching.
- RFC 9113 — HTTP/2 and RFC 9114 — HTTP/3.
- RFC 9000 — QUIC.
- HTTP/3 explained — Daniel Stenberg (author of curl), free online booklet.
- MDN Web Docs — "HTTP caching", "Using HTTP cookies" and "Cross-Origin Resource Sharing (CORS)".
Related
- TCP & UDP — head-of-line blocking, slow start and connection reuse underneath HTTP.
- TLS & HTTPS — ALPN, TLS 1.3 and 0-RTT.
- RPC & gRPC — gRPC's use of HTTP/2 streams and trailers.
- CDN & Edge — where HTTP caching headers pay off.
- Caching — cache strategies beyond HTTP.
- API Design (REST, gRPC, GraphQL) — resource design, idempotency keys, versioning.
- Security for Architects — CSRF, XSS and session management.
Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).