HTTP Protocol and Web Fundamentals Questions
HTTP semantics that underpin web and API behavior: methods (safe vs idempotent, retries), the status codes that drive caching, conditional and range behavior, request and response headers, content negotiation and Vary, HTTP caching (Cache-Control, private vs shared caches, ETag, conditional requests), cookies and credentialed cross-origin requests (SameSite, CORS and preflight at the header level), large responses (range requests, resuming a download), connection reuse and message framing (keep-alive, chunked transfer, pipelining), and HTTP/1.1 vs HTTP/2 vs HTTP/3 differences such as multiplexing, flow control and head-of-line blocking. Includes TLS at the request level (handshake overview, session resumption, termination at the edge vs passthrough) and how proxies and load balancers change requests, including forwarded client addresses. Excludes TCP/UDP and OSI-layer networking, attack-focused web security, resource and endpoint design, and CDN or edge-cache operations.
Explain the main HTTP methods (GET, POST, PUT, PATCH, DELETE): which are safe, which are idempotent, which responses are cacheable, and when a client should choose POST versus PUT. How do those properties decide what a client may automatically retry after a dropped connection or timeout?
Sample Answer
The idea in plain words
Each HTTP method (the verb at the start of a request, such as GET) comes with promises defined in RFC 9110. A method is safe if the client is asking only to read, not to change anything on the server. A method is idempotent if sending the same request several times leaves the server in the same state as sending it once (the response may differ; the effect must not). Every safe method is idempotent, but not the other way round. These promises decide what a client may do on its own when a connection drops: if a request is idempotent, resending it cannot cause extra damage, so a library may retry automatically. If it is not, the client does not know whether the first attempt was processed, and a blind retry may do the work twice.
The five methods
| Method | Meaning | Safe | Idempotent | Response cacheable |
|---|---|---|---|---|
| GET | Read a resource | Yes | Yes | Yes |
| POST | Process the body: create a subordinate resource, run an action | No | No | Defined as cacheable only with explicit freshness information, and in practice almost never cached |
| PUT | Replace the whole resource at this URL (create it if absent) | No | Yes | No. A successful PUT invalidates stored copies of that URL |
| PATCH | Apply a partial change described in the body | No | No by definition; it depends on the patch format | No in practice |
| DELETE | Remove the resource at this URL | No | Yes | No |
Reading the last column: a response is cacheable when a cache may store it and answer later requests from the stored copy without asking the origin again. A POST response is cacheable only when it carries explicit freshness information (for example Cache-Control: max-age=60) and a Content-Location header equal to the POST's own URL; it can then answer later GET or HEAD requests for that URL (RFC 9110, the HTTP semantics specification, section 9.3.3). Few deployments rely on that, hence "almost never cached". When a cache sees a successful PUT, POST, PATCH or DELETE to a URL it discards its stored copies of that URL, so the next GET fetches the new state (RFC 9111, section 4.4). A subordinate resource is one that lives under the target, such as an order created under /orders.
Two clarifications. Idempotent concerns the server's state, not the status code: a second DELETE of the same URL may return 404 Not Found instead of 204 No Content, yet the state (resource gone) is the same, so DELETE is still idempotent. And these are properties of the method as the protocol defines it; the server's code has to honour them. A GET handler that deletes rows breaks the promise and will be triggered by crawlers, link prefetchers and retries.
HEAD and OPTIONS are also safe and idempotent; they are outside the five asked about.
POST versus PUT
Choose by who decides the URL.
- PUT when the client already knows the full address of the thing and sends its complete desired state:
PUT /users/42/profilereplaces the profile. Repeating it gives the same final state, which is what makes it retryable. - POST when the server assigns the identity or the operation is an action:
POST /orderscreates an order whose id the server chooses, and replies201 Createdwith aLocationheader naming it. Two identical POSTs normally create two orders.
PATCH sits between them. A patch that says "set quantity to 3" is idempotent in effect; one that says "add 2 to quantity" is not. Worked numbers: quantity starts at 1. "Set to 3" applied once or twice gives 3 both times. "Add 2" applied once gives 1 + 2 = 3; applied twice (a retry) gives 1 + 2 + 2 = 5. So PATCH is retried automatically only when you know your patch format is idempotent.
How this decides retries after a dropped connection or timeout
The key fact: after a timeout the client cannot tell whether the request never arrived, arrived and was processed with the reply lost, or is still running. Three cases:
| What happened | Safe to retry automatically? |
|---|---|
| The request was never sent (connection refused, DNS failure) | Yes for any method, nothing reached the server |
| Request may have been processed, method idempotent (GET, PUT, DELETE) | Yes, with backoff (waiting longer between attempts, with random jitter so many clients do not retry in lockstep) and a cap on attempts |
| Request may have been processed, method not idempotent (POST, most PATCH) | No, unless the request carries an idempotency key |
An idempotency key is a unique value the client generates once per logical action and repeats on every retry (commonly an Idempotency-Key header; that header is an IETF draft, not a finished RFC, and servers must be built to support it). The server stores the key with the result of the first attempt and replays that result for repeats.
Illustrative exchange (invented API, not a real capture). The first attempt times out on the client:
POST /orders HTTP/1.1
Host: api.example.test
Content-Type: application/json
Idempotency-Key: 6b1f2c9e-3d4a-4c58-9a11-0e7f5d2a8c34
Content-Length: 25
{"sku":"A1","quantity":2}
The server did create order 1043 but the reply was lost. The client retries with the identical key and body. The server finds the key, creates nothing, and replays the stored result:
HTTP/1.1 201 Created
Location: /orders/1043
Content-Type: application/json
Content-Length: 24
{"id":1043,"quantity":2}
Without the key, the retry creates a second order: 2 + 2 = 4 units purchased instead of 2. With it, one order of 2 units exists however many retries arrive. (The Content-Length values above are the byte lengths of those two bodies: 25 and 24.)
Other rules when retrying:
- If the server answered
429 Too Many Requestsor503 Service UnavailablewithRetry-After, wait at least that long. By convention these codes mean the server refused the request before doing the work, so a retry is usually reasonable, but the standard does not guarantee it (a gateway can return503after the origin already acted), so for a POST still send an idempotency key. A bare timeout says nothing. - Idempotent does not mean conflict-free. Two clients each doing a PUT can overwrite each other. Use a conditional request:
If-Match: "v17"with the ETag you read, and a412 Precondition Failedtells you someone else changed it first. - Cap total retries and spread them with jitter, so retries from many clients do not become a second wave of load.
Common mistakes
- Treating PUT as "update one field". PUT replaces the whole resource; PATCH is for partial updates.
- Retrying POST automatically because "retries are good".
- Putting side effects behind GET.
- Confusing safe with idempotent: DELETE is idempotent but not safe.
- Assuming a
404on a repeated DELETE means the first attempt failed.
Compare HTTP/1.1, HTTP/2 and HTTP/3 for a client on an unreliable, battery-constrained network. Cover multiplexing, header compression, connection reuse and keep-alive, CPU and battery cost, middlebox compatibility, and how QUIC changes the picture. Give a case where HTTP/2 helps and one where it causes problems.
Sample Answer
The idea in plain words
All three versions carry the same HTTP meaning (methods, status codes, headers); they differ in how those messages are packed onto the network. On a slow, lossy, battery-limited link, two things dominate: how many round trips happen before useful bytes flow, and how much one lost packet delays. HTTP/1.1 sends one request at a time per connection, so a client opens several connections. HTTP/2 puts many requests on one connection. HTTP/3 keeps that idea but runs on QUIC (a transport built on UDP that has its own loss recovery and encryption), so a lost packet no longer stalls every request. My recommendation: serve all three, let the client negotiate, and design the app for one connection per host with batched requests.
Comparison across the named dimensions
| Dimension | HTTP/1.1 | HTTP/2 (RFC 9113) | HTTP/3 (RFC 9114) |
|---|---|---|---|
| Wire format | Text | Binary frames | Binary frames over QUIC streams |
| Multiplexing (several requests in flight on one connection) | No. One response at a time per connection. Pipelining exists but is blocked in order and rarely used, so clients open several connections (commonly around six per host) | Yes. Many streams interleaved on one TCP connection | Yes. Streams are independent inside QUIC |
| Header compression | None. Cookies and other headers are resent in full each request | HPACK (RFC 7541): a shared table so repeated headers are sent as small references | QPACK (RFC 9204): same idea, redesigned so table updates do not block independent streams |
| Connection reuse and keep-alive | Persistent by default; the connection is reused for the next request until someone closes it or it times out (Connection: close ends it) | One long-lived connection per origin; idle time and PING frames keep it alive | One QUIC connection, identified by a connection ID rather than the IP address and port |
| Setup round trips (see example) | TCP 1 plus TLS 1.3 1 = 2 | Same 2 | 1 (transport and TLS combined) |
| Effect of one lost packet | Stalls only that connection | Stalls every stream on the connection (TCP delivers bytes in order) | Stalls only the stream(s) whose data was in that packet |
| Network change (Wi-Fi to cellular) | Connections break; new handshakes | Connection breaks; new handshake, all streams restart | Connection can migrate to the new address without a new handshake |
| Middlebox compatibility | Works almost everywhere | Needs TLS in browsers (negotiated with ALPN, a TLS extension that picks the protocol); falls back to 1.1 if a device does not support it | UDP on port 443 is blocked or throttled on some networks, so a TCP fallback is needed |
Terms used in the table and below. A middlebox is any device between client and server that inspects or alters traffic (firewall, address translator, proxy, corporate gateway), and a TLS-inspecting middlebox decrypts and re-encrypts https to scan it. HPACK and QPACK are the header compression schemes of HTTP/2 and HTTP/3. A connection ID is a number carried in QUIC packets that names the connection independently of IP address and port, which is what lets it migrate. PING frames are small HTTP/2 messages that check a connection is still alive. Alt-Svc (alternative service) is a response header saying that this origin is also reachable over another protocol and port. DNS HTTPS records are DNS entries that publish a host's supported protocols, so a client can try HTTP/3 on its first visit. Domain sharding means spreading resources over several host names to get more parallel connections. In an interview the multiplexing, lost-packet and setup-round-trip rows are the ones that explain the latency result; header compression, Alt-Svc and DNS records are supporting mechanisms.
How a client reaches HTTP/3. The first contact normally uses TCP. The server advertises HTTP/3 in an Alt-Svc response header (RFC 7838), for example Alt-Svc: h3=":443"; ma=86400, and the client tries QUIC on later connections, falling back to TCP if UDP fails. DNS HTTPS records (RFC 9460) can also advertise it.
CPU and battery. The radio is usually the larger cost: every time it wakes from idle it stays in a high-power state for some time. Fewer connections means fewer handshakes and fewer wake-ups, and a single multiplexed connection lets the app batch requests into one burst and let the radio sleep. HTTP/2 helps here. Header compression trims bytes and so radio time. HTTP/3 saves a round trip per new connection, but QUIC implementations often run in user space rather than in the kernel's TCP stack, so CPU per byte can be higher; measure on the real devices rather than assuming. Aggressive keep-alive pings keep the radio awake and cost battery, so keep them infrequent. As an illustration, assume (real values depend on the network and the device) that the radio stays in its high-power state for a 5 second tail after each burst of traffic. A ping every 10 s then keeps it awake 5 / 10 = 50 percent of the time, every 30 s 5 / 30 = 16.7 percent, and every 60 s 5 / 60 = 8.3 percent:
tail = 5
for gap in (10, 30, 60):
print("ping every", gap, "s, radio tail", tail, "s: awake", round(100 * tail / gap, 1), "percent of the time")
Output:
ping every 10 s, radio tail 5 s: awake 50.0 percent of the time
ping every 30 s, radio tail 5 s: awake 16.7 percent of the time
ping every 60 s, radio tail 5 s: awake 8.3 percent of the time
Worked example (assumptions stated)
Assumptions: round-trip time (RTT) 200 ms; TLS 1.3; the screen needs 30 small API calls to one host, all ready at the same moment; each response needs one RTT and bandwidth is not the limit; no packet loss; HTTP/1.1 uses 6 parallel connections; for HTTP/3 the client already knows the server offers it (learned on an earlier visit through Alt-Svc or a DNS HTTPS record), because on a first-ever visit it starts on TCP and matches the HTTP/2 figures.
- Setup: TCP handshake 1 RTT plus TLS 1.3 handshake 1 RTT = 2 x 200 = 400 ms. QUIC combines both in 1 RTT = 200 ms. (The six HTTP/1.1 connections open in parallel, so their setup also takes 400 ms.)
- HTTP/1.1: 30 requests over 6 connections is 30 / 6 = 5 rounds of 200 ms. Total 400 + 5 x 200 = 1,400 ms.
- HTTP/2: all 30 in flight at once, 1 round. Total 400 + 200 = 600 ms.
- HTTP/3: 200 + 200 = 400 ms.
Header size: assuming 500 bytes of request headers, HTTP/1.1 sends 30 x 500 = 15,000 bytes; HTTP/2 and HTTP/3 send the first set in full and then mostly small references to table entries. The exact compressed size depends on which headers repeat, so I do not quote one.
A case where HTTP/2 helps: the screen above. Many small calls to one host go from 1,400 ms to 600 ms in this model because the six-connection limit disappears, and the radio sees one connection instead of six.
A case where HTTP/2 causes problems: the same screen on a cellular link that drops a packet now and then. All 30 streams share one TCP connection, and TCP delivers bytes in order, so when one packet is lost, data behind it waits for the retransmission, at least about one RTT (200 ms here), for every stream. With HTTP/1.1 on 6 connections the loss stalls only one connection, 1 of 6 = 16.7 percent of the in-flight requests. Under HTTP/3 only the stream whose data was in the lost packet waits. A second problem case: the user moves from Wi-Fi to cellular. The single HTTP/2 connection breaks and every stream restarts after a fresh 400 ms setup, whereas QUIC can migrate. Also, a TLS-inspecting middlebox or old proxy that mishandles HTTP/2 forces fallback to HTTP/1.1.
The loss case in numbers. Take the same 30-call screen, one packet lost in the first round, and a retransmission that adds one RTT (200 ms; real retransmission timers can be longer). On HTTP/1.1 the loss delays the 5 calls queued on the one connection that lost the packet, on HTTP/2 every in-flight stream waits, and on HTTP/3 only the stream whose data was in the packet waits (assumed to be one):
RTT, SETUP_TCP_TLS, SETUP_QUIC, LOSS_DELAY = 200, 400, 200, 200
CALLS, PARALLEL = 30, 6
rounds = CALLS // PARALLEL
h1 = SETUP_TCP_TLS + rounds * RTT
h2 = SETUP_TCP_TLS + RTT
h3 = SETUP_QUIC + RTT
print("no loss, screen done at ms: h1.1", h1, "h2", h2, "h3", h3)
print("one packet lost in the first round (retransmission adds", LOSS_DELAY, "ms):")
print(" h1.1 requests delayed:", rounds, "of", CALLS, "screen done at", h1 + LOSS_DELAY)
print(" h2 requests delayed:", CALLS, "of", CALLS, "screen done at", h2 + LOSS_DELAY)
print(" h3 requests delayed:", 1, "of", CALLS, "screen done at", h3 + LOSS_DELAY)
Output:
no loss, screen done at ms: h1.1 1400 h2 600 h3 400
one packet lost in the first round (retransmission adds 200 ms):
h1.1 requests delayed: 5 of 30 screen done at 1600
h2 requests delayed: 30 of 30 screen done at 800
h3 requests delayed: 1 of 30 screen done at 600
HTTP/2 still finishes before HTTP/1.1 in this model (800 ms against 1,600 ms) because HTTP/1.1 pays five rounds anyway; what changes is who waits. All 30 requests wait on HTTP/2, 5 on HTTP/1.1 and 1 on HTTP/3, and each further loss stalls every HTTP/2 stream again, so the penalty grows as the link gets worse.
My recommendation
- Enable HTTP/2 and HTTP/3 on the server with HTTP/1.1 as the fallback, and let the client negotiate. Do not write client logic around a specific version.
- Use one hostname for the API (domain sharding to get more connections helps HTTP/1.1 and hurts HTTP/2 and 3), batch or prefetch requests together, and set conservative idle and keep-alive timeouts.
- HTTP/3 allows 0-RTT resumption (sending request data in the first flight on a repeat connection); that data can be replayed by an attacker or a duplicating network, so by default only safe requests (ones that only read, such as GET; RFC 8470) belong there. Idempotent is not enough: a replayed PUT arriving late can overwrite a newer update, and a GET handler that has side effects is still replayable harm.
- What would flip it: if measurements on target devices show higher CPU or battery draw under HTTP/3 for large steady downloads, or a large share of users sit behind UDP-blocking networks, keep HTTP/2 as the primary path and treat HTTP/3 as an opportunistic upgrade.
Common mistakes
- Saying HTTP/2 removes head-of-line blocking. It removes it at the HTTP layer but TCP still has it.
- Saying HTTP/3 is always faster. On a clean, low-loss link the gain is mostly the saved round trip.
- Forgetting the fallback: UDP can be blocked.
- Keeping HTTP/1.1 habits (sharding, many small connections, concatenated bundles) on HTTP/2.
Running the code
Each program above is self-contained: copy it into a file and run it with python. The output shown is the complete printed result.
A client app should show recently fetched data when the device is offline and avoid re-downloading unchanged data on a poor connection. Explain how Cache-Control, ETag and Last-Modified let it do that, how a conditional request and its 'not modified' reply work, and how you would apply this with a client-side HTTP cache or an intermediary cache.
Sample Answer
The idea in plain words
HTTP caching lets a client keep a copy of a response and reuse it instead of asking the server again. Three response headers do the work. Cache-Control says how long the copy may be reused without asking (its freshness) and who may store it. ETag (an opaque version label the server puts on a response, such as "v17") and Last-Modified (the time the resource last changed) are validators: small tokens the client can send back later to ask "is my copy still current?". If it is, the server answers 304 Not Modified with no body, so the client pays for a few hundred bytes of headers instead of the whole payload. Offline display is a related but separate job: when there is no network at all, no header can fetch anything, so the app must keep its own last good copy and decide when to show it.
How each header works
| Header | Sent by | What it does |
|---|---|---|
Cache-Control: max-age=300 | server (response) | The copy is fresh for 300 seconds after it was generated. While fresh, the cache answers without contacting the server. |
Cache-Control: private / public | server | private: only the end client's own cache may store it (use for per-user data). public: shared caches (a proxy or other intermediary between many clients and the server) may store it too. |
Cache-Control: no-cache | server | Storing is allowed, but the copy must be revalidated with the server before every reuse. It does not mean "do not cache". |
Cache-Control: no-store | server | Do not keep the response at all. Use for secrets. |
ETag: "v17" | server | Version label of this representation. A strong ETag changes whenever the bytes change; a W/ prefix marks a weak one (semantically the same, not byte-identical). |
Last-Modified: <HTTP-date> | server | When the resource last changed. Weaker evidence than an ETag because it has one-second resolution. |
If-None-Match: "v17" | client (request) | "Send the body only if the current ETag is not "v17"." |
If-Modified-Since: <HTTP-date> | client (request) | "Send the body only if it changed after this time." |
If a response has no Cache-Control or Expires (an older header that gives an absolute date after which the copy is stale) but does have Last-Modified, RFC 9111 lets a cache guess a freshness lifetime (a common rule of thumb is 10 percent of the time since the last change). I would never rely on that guess: set max-age explicitly.
The conditional request and the 304, step by step
Freshness rule: a stored copy may be reused without asking while
age<freshness lifetime (max-age)After that it is stale, and the client revalidates instead of re-downloading. Everything below is an illustrative exchange (an invented API at api.example.test, not a capture from a real server).
Step 1, first fetch at 10:00:00 GMT. The body is 40,000 bytes (an assumption for this example):
GET /v1/feed HTTP/1.1
Host: api.example.test
Accept: application/json
HTTP/1.1 200 OK
Date: Sat, 07 Nov 2026 10:00:00 GMT
Cache-Control: private, max-age=300
ETag: "v17"
Last-Modified: Sat, 07 Nov 2026 09:00:00 GMT
Content-Type: application/json
Content-Length: 40000
(40,000-byte JSON body omitted)
The client stores body, ETag, Last-Modified and the time it received the response.
Step 2, 10:03:00. Age is 180 s, below 300 s, so the copy is fresh. The client uses it with no network request at all.
Step 3, 10:07:00. Age is 420 s, above 300 s, so the copy is stale. The client sends a conditional request carrying both validators:
GET /v1/feed HTTP/1.1
Host: api.example.test
Accept: application/json
If-None-Match: "v17"
If-Modified-Since: Sat, 07 Nov 2026 09:00:00 GMT
When both headers are present the server evaluates If-None-Match and ignores If-Modified-Since (RFC 9110). The data has not changed, so:
HTTP/1.1 304 Not Modified
Date: Sat, 07 Nov 2026 10:07:00 GMT
Cache-Control: private, max-age=300
ETag: "v17"
A 304 carries no body. The client keeps its stored body, updates the stored headers from the 304 (so the copy is fresh for another 300 s) and displays the data it already has. If the data had changed, the server would have replied 200 OK with the new body and a new ETag, such as "v18", and the client would replace its copy.
Bytes saved (arithmetic, with stated assumptions)
Assume a full exchange costs 700 bytes of headers plus the 40,000-byte body, and a conditional exchange that returns 304 costs only the 700 bytes of headers. Ten refreshes of unchanged data, every one needing the network:
- Without validators: 10 x (40,000 + 700) = 10 x 40,700 = 407,000 bytes.
- With validators: first fetch 40,700, then nine 304 exchanges at 700 each is 9 x 700 = 6,300, total 40,700 + 6,300 = 47,000 bytes.
- Ratio: 407,000 / 47,000 = 8.66, about 8.7 times fewer bytes. The saving grows with body size and shrinks if the data changes often. On a poor connection the saved bytes matter, and the round trip is still paid, which is why
max-age(no round trip at all) is the first lever and validators the second.
Applying it: client-side cache and intermediary cache
Client-side HTTP cache. Browsers, and native HTTP stacks that ship an on-disk cache, store responses and send the conditional request for you when a stale entry is found. Two cautions. First, the HTTP cache is a performance cache, not a storage guarantee: entries can be evicted (deleted by the browser or operating system when storage runs short), and a stale entry whose revalidation fails offline typically surfaces as a network error unless the code explicitly asks for stale data (in the browser Fetch API, the cache: "force-cache" option returns any stored entry regardless of age). Second, the Fetch Standard says that when a fetch request already carries a conditional header (If-None-Match, If-Modified-Since, If-Match, If-Unmodified-Since or If-Range) and uses the default cache mode, the browser sets the cache mode to no-store: its own cache is bypassed and your code receives the raw 304. So choose one approach: let the HTTP cache manage it, or manage validators yourself.
Offline display, my recommendation. Keep an application-level copy of the last good response (for example in IndexedDB, the browser's built-in database that persists across sessions; SQLite, a small embedded database used in native apps; or the Cache API, browser storage for request and response pairs that your own code manages) together with its ETag and the time it was fetched. On open: render the stored copy immediately, then send a conditional request in the background. Outcomes:
| Result | What the app does |
|---|---|
304 | Keep the copy, mark it "up to date". |
200 | Replace the copy and ETag, re-render. |
| Network failure or timeout | Keep showing the stored copy with a "last updated 10:07" label; retry later. |
401 or 403 | Do not show the stored copy to a different or signed-out user; clear it on logout. |
The same flow as code, with a stand-in server for the origin and STORE for the app's saved copy:
STORE = {}
def server(headers, version):
"""Fake origin: current ETag and body depend on `version`."""
etag = f'"v{version}"'
if headers.get("If-None-Match") == etag:
return 304, {"ETag": etag}, b""
return 200, {"ETag": etag}, f"feed-body-v{version}".encode()
def open_screen(version, online):
stored = STORE.get("feed")
request = {}
if stored:
request["If-None-Match"] = stored["etag"]
print("render stored copy:", stored["body"].decode())
if not online:
print("offline: no request sent, stored copy stays on screen")
return
status, headers, body = server(request, version)
if status == 304:
print("304: stored copy is current")
else:
STORE["feed"] = {"etag": headers["ETag"], "body": body}
print(status, ": replaced copy with", body.decode())
print("first open"); open_screen(17, True)
print("second open, unchanged"); open_screen(17, True)
print("third open, offline"); open_screen(17, False)
print("fourth open, data changed"); open_screen(18, True)
Output:
first open
200 : replaced copy with feed-body-v17
second open, unchanged
render stored copy: feed-body-v17
304: stored copy is current
third open, offline
render stored copy: feed-body-v17
offline: no request sent, stored copy stays on screen
fourth open, data changed
render stored copy: feed-body-v17
200 : replaced copy with feed-body-v18
Read-out: on the first open nothing is stored, so no conditional header is sent and the 200 is saved with its ETag. On the second open the app renders the stored copy at once, then asks If-None-Match: "v17" and gets 304, so it keeps the copy. On the third open the device is offline, so no request is sent and the stored copy stays on screen (a real app adds the "last updated" label from the table). On the fourth open the server's data is at "v18", the tag no longer matches, and the 200 replaces the copy. In a browser the request in the middle is a fetch with If-None-Match set by hand, which, as described above, hands the code the raw 304.
Intermediary cache (a reverse proxy or content delivery network between clients and your server). It can answer many clients from one stored copy, but only if the response allows it: public, or an s-maxage (the shared-cache version of max-age), and a Vary header listing request headers that change the response (for example Vary: Accept-Language). Per-user responses must be private so a shared cache never serves one person's data to another. An intermediary sits in the network, so it cannot help a device that is offline; offline support is always a copy on the device.
Common mistakes
- Thinking
no-cacheforbids storing. It means "revalidate before reuse";no-storeforbids storing. - Shipping an ETag but no
Cache-Control: the client then revalidates on every use (or guesses a lifetime), so you save bytes but not round trips. - Generating an ETag that changes per request (a timestamp or random value), so every conditional request gets a full
200. - Caching personal data in a shared cache without
private, or leaving it on a shared device after logout. - Assuming the HTTP cache alone gives offline reads.
Running the code
Each program above is self-contained: copy it into a file and run it with python. The output shown is the complete printed result.
Your API currently returns JSON and you want to offer a more compact binary format to some clients without breaking existing ones. How does the client and server agree on the format, and what does that agreement do to HTTP caches and intermediaries in front of the API?
Sample Answer
The idea in plain words
Content negotiation is the part of HTTP where a client and server agree on which representation (which format, language or compression) of one resource is sent. In proactive negotiation the client states preferences in request headers and the server chooses. For this API the client says which media type it can read in the Accept request header, and the server labels what it actually sent in the Content-Type response header. Because one URL can now return different bytes depending on a request header, every cache between the server and the client must be told which header made the difference. That is the job of the Vary response header. Forgetting it is the classic way a binary response gets served to a client that wanted JSON.
Method
Step 1. Pick a real media type for the binary format. Examples are application/cbor (CBOR, a compact binary encoding of JSON-like data, RFC 8949) or application/vnd.example.listing+cbor. A vendor-specific type is useful if the schema is yours: the vnd. prefix marks the vendor tree of media types, where an organisation names its own formats, and the +cbor suffix says the bytes are CBOR underneath.
Step 2. Make JSON the default. Existing clients send Accept: application/json or nothing or */*; all of those must keep getting JSON. Only a client that asks for the binary type gets it:
GET /v1/listings/42 HTTP/1.1
Host: api.example.test
Accept: application/cbor;q=1.0, application/json;q=0.5
q is a quality value from 0 to 1 giving the client's preference; the server picks the highest-ranked type it can produce. If the client lists only types the server cannot produce, the server may answer 406 Not Acceptable, though RFC 9110 also allows it to ignore the header and send a default. For an API that must not break old clients I would send the default (JSON) when Accept is absent or contains */*, and 406 only when the client explicitly lists nothing acceptable.
Step 3. Label the response and tell caches what varied.
HTTP/1.1 200 OK
Content-Type: application/cbor
Vary: Accept
Cache-Control: public, max-age=60
ETag: "v7-cbor"
Content-Typestates what is in the body.Vary: Acceptsays: the response depends on the request'sAcceptvalue; a cache may reuse it only for a later request whoseAcceptmatches the stored request's. (The JSON variant of the same URL carriesVary: Accepttoo and its own ETag,"v7-json", because the bytes differ.)- If compression also varies, add it:
Vary: Accept, Accept-Encoding.
Step 4. For requests that carry a body, the matching pair is Content-Type on the request (what the client is sending) and 415 Unsupported Media Type if the server cannot read it. Do not confuse the two: 406 is about what the client can accept in the response, 415 is about the format the client sent.
What the agreement does to caches and intermediaries
A cache's key is the URL plus the request header values named in Vary. With Vary: Accept, the cache stores one entry per distinct Accept string, not per format.
Worked count, with assumed numbers: 3 hot URLs, and the clients in front of the cache send 4 distinct Accept strings (a browser's long one, a bare application/json, */*, and the binary client's application/cbor).
- Entries the cache may need: 3 URLs x 4 strings = 12.
- Entries it needs if the edge first normalises
Acceptto two canonical values (application/cbororapplication/json): 3 x 2 = 6.
The cache-hit rate rises as entries are shared, so I would normalise Accept at the edge and keep Vary: Accept on the response. The edge is the first server a request reaches, such as a CDN node or an API gateway (a front-door server that applies shared rules), and it rewrites the browser's long Accept string to one of the two supported values before the cache lookup. The program below does exactly that rewrite and reproduces the 12 and 6 entry counts.
import json
def head(major, n):
if n < 24:
return bytes([major << 5 | n])
if n < 256:
return bytes([major << 5 | 24, n])
return bytes([major << 5 | 25]) + n.to_bytes(2, "big")
def cbor(v):
if isinstance(v, int):
return head(0, v)
if isinstance(v, str):
b = v.encode("utf-8")
return head(3, len(b)) + b
if isinstance(v, dict):
return head(5, len(v)) + b"".join(cbor(k) + cbor(x) for k, x in v.items())
raise TypeError(v)
record = {"id": 42, "name": "Desk lamp", "price_cents": 2499}
as_json = json.dumps(record, separators=(",", ":")).encode()
as_cbor = cbor(record)
print("JSON bytes:", len(as_json))
print("CBOR bytes:", len(as_cbor))
print("CBOR hex:", as_cbor.hex())
def canonical(accept):
"""Reduce any Accept header to one of two canonical values."""
q = {}
for part in accept.split(","):
fields = part.strip().split(";")
value = 1.0
for f in fields[1:]:
name, _, v = f.strip().partition("=")
if name == "q":
value = float(v)
q[fields[0].strip()] = value
cbor_q, json_q = q.get("application/cbor", 0), q.get("application/json", 0)
return "application/cbor" if cbor_q > 0 and cbor_q >= json_q else "application/json"
seen = [
"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
"application/json",
"*/*",
"application/cbor;q=1.0, application/json;q=0.5",
]
for a in seen:
print(canonical(a), "<-", a)
print(canonical("application/cbor;q=0.2, application/json;q=1.0"), "<- cbor;q=0.2, json;q=1.0")
urls, raw, canon = 3, len(set(seen)), len({canonical(a) for a in seen})
print("cache entries without normalising:", urls, "x", raw, "=", urls * raw)
print("cache entries after normalising:", urls, "x", canon, "=", urls * canon)
Output:
JSON bytes: 47
CBOR bytes: 36
CBOR hex: a3626964182a646e616d65694465736b206c616d706b70726963655f63656e74731909c3
application/json <- text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8
application/json <- application/json
application/json <- */*
application/cbor <- application/cbor;q=1.0, application/json;q=0.5
application/json <- cbor;q=0.2, json;q=1.0
cache entries without normalising: 3 x 4 = 12
cache entries after normalising: 3 x 2 = 6
Read-out: canonical splits the header on commas, reads each q value, and returns application/cbor only when the client lists it with a positive q at least as high as its q for JSON (the line ending json;q=1.0 shows a client that prefers JSON getting JSON); every other header, including the browser's long one and */*, becomes application/json. Four distinct strings collapse to two cache keys, so 3 URLs need 6 entries instead of 12. The same record is 47 bytes as compact JSON and 36 bytes as CBOR (hex shown: a3 opens a map of 3 entries, then each key and value follows), a saving of 11 bytes, about 23 percent, for this small record. Savings differ for other shapes of data, which is why the size comparison belongs in the decision. A cache that does not support Vary properly is the dangerous case: it could hand the CBOR bytes to a JSON client (this is cache poisoning: a cache storing a response that is wrong for the callers who get it later). If you cannot rule that out, publish the binary format on its own URL (a different path or a .cbor suffix) and avoid relying on Vary. The trade-off is a second URL to document and to link, and the two URLs have separate cache entries and separate ETags.
Judgment
I would use header negotiation with JSON as the default, Vary: Accept on every variant, and edge normalisation of Accept, because it keeps one URL per resource and does not change anything for existing clients. I would switch to a separate URL if a proxy in the path is known to mishandle Vary, or if the binary format is semantically a different product with its own lifecycle. I would add a response-size comparison for the two formats before committing, since a compact format that saves little bandwidth does not justify a second cache variant.
Common mistakes
- Omitting
Vary: Accept(cache poisoning of one format with the other, as defined above). - Using
Vary: *or varying onUser-AgentorCookie, which makes caching ineffective. - Returning
406to old clients that sent*/*. - Sharing one ETag between the two formats, so a 304 validates the wrong bytes.
- Using
Content-Typeon a GET request to express the wanted format; that header describes a request body.
Running the code
Each program above is self-contained: copy it into a file and run it with python. The output shown is the complete printed result.
A browser app on one origin calls your API on another and the request fails in the browser although the same call works from curl. Explain why the browser behaves this way, what exchange happens before the real request when it is not a simple one, and how you would configure the API for a public API that serves browsers versus a strictly internal one.
Sample Answer
The idea in plain words
Browsers enforce the same-origin policy: a script loaded from one origin (the triple of scheme, host and port, for example https://app.example.test) may not read responses from a different origin (https://api.example.test is a different origin because the host differs). CORS (cross-origin resource sharing) is the opt-in mechanism: the API states in response headers which origins may read its responses. The key fact is that the browser enforces this, not the server and not the network. curl is not a browser, so it ignores CORS entirely, which is exactly why the call works there and fails in the page. In many cases the request does reach the API; the browser then refuses to hand the response to the script.
What happens before the real request
Browsers classify a cross-origin request as simple (a GET, HEAD or POST using only the safelisted request headers (the short list browsers allow without asking: Accept, Accept-Language, Content-Language and Content-Type with restricted values) and, for POST, a content type of application/x-www-form-urlencoded, multipart/form-data or text/plain) or not. A JSON POST with Content-Type: application/json, a custom header such as X-Request-Id, an Authorization header, or a method like PUT or DELETE makes it non-simple. For a non-simple request the browser first sends a preflight: an automatic OPTIONS request asking permission.
Illustrative preflight and the real request:
OPTIONS /v1/orders HTTP/1.1
Host: api.example.test
Origin: https://app.example.test
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: authorization, content-type
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://app.example.test
Access-Control-Allow-Methods: GET, PUT, DELETE
Access-Control-Allow-Headers: authorization, content-type
Access-Control-Max-Age: 600
Vary: Origin
Originis added by the browser and cannot be forged by page script.Access-Control-Request-MethodandAccess-Control-Request-Headersdescribe the real request that is waiting.- The browser compares the answer to what it is about to send. If the origin is not allowed, or the method or a header is missing from the lists, the real request is never sent and the console shows a CORS error.
Access-Control-Max-Age: 600lets the browser reuse this permission for 600 seconds (browsers cap this value at their own maximum).Vary: Origintells every cache on the path that theAccess-Control-Allow-Originvalue depends on the request'sOrigin. Without it a shared cache could store the reply meant forhttps://app.example.testand send that same header to a page from another origin.
If the preflight passes, the real request goes out and its response must carry Access-Control-Allow-Origin again, or the script still cannot read it:
PUT /v1/orders/9 HTTP/1.1
Origin: https://app.example.test
Authorization: Bearer <token>
Content-Type: application/json
HTTP/1.1 200 OK
Access-Control-Allow-Origin: https://app.example.test
Access-Control-Expose-Headers: X-Request-Id
Vary: Origin
Content-Type: application/json
By default a script can read only the safelisted response headers: Cache-Control, Content-Language, Content-Length, Content-Type, Expires, Last-Modified and Pragma. X-Request-Id is not on that list, so it must be named in Access-Control-Expose-Headers before the script can read it.
Debugging order when "curl works, browser fails"
- Read the console message: it names the missing header or the failed check.
- In the network panel, find the
OPTIONSrequest. Is there one? What status? A gateway that answers 401, 404 or 405 toOPTIONSfails the preflight (the preflight carries no credentials, so authentication must not run on it). - Check the actual response for
Access-Control-Allow-Origin. Error responses (401, 500 from a proxy) often lack it, so a server error looks like a CORS error. - Check for a redirect on the preflight; browsers do not follow redirects for preflights.
- Replay with curl including
-H "Origin: ..."and-X OPTIONSto see exactly what the server sends back.
Configuring public versus internal
| Public API for browsers | Strictly internal API | |
|---|---|---|
| Allowed origins | Access-Control-Allow-Origin: * is acceptable when no cookies are used and credentials travel in an Authorization header or API key | An allowlist of exact origins; the server copies the request's Origin value into Access-Control-Allow-Origin (it echoes it) only when it matches an entry, and sends Vary: Origin |
| Credentials | Not allowed with * (the browser rejects the combination) | Access-Control-Allow-Credentials: true only if cookies are really needed |
| Methods and headers | Only what the API uses | Only what the internal apps use |
Access-Control-Max-Age | Moderate to cut preflight traffic | Moderate |
| Real protection | Authentication and authorisation on every request | The same. Network placement as well |
For the public case I would answer * on documented read endpoints and keep authentication in headers. For the internal case I would use an exact-match allowlist from configuration; never reflect (copy back) an arbitrary Origin, and never trust a suffix match (endswith("example.test") also matches evilexample.test).
CORS is a browser-side read restriction, not access control. A server that relies on it to keep data private is unprotected against any non-browser client, so the authentication check always runs on the server.
Friction for the people using the API
A frequent complaint is a cryptic console error. Cheap mitigations: document the allowed origins and the exact headers the API accepts, return CORS headers on error responses too, and offer a server-side proxy or an SDK for clients that cannot be listed in an allowlist. A server-side proxy is a small server on the app's own origin that forwards the browser's calls to the API, so the browser only makes same-origin requests. An SDK is a client library you publish that wraps the API calls. A gateway is a front-door server in front of the API that applies shared rules such as authentication and CORS headers in one place.
Common mistakes
- Adding the CORS headers only on the success path, so errors look like CORS failures.
- Answering the preflight with a 3xx or 401.
- Echoing
OriginwithoutVary: Origin, so a cache serves one origin's header to another. - Using
*together with cookies. - Believing CORS stops attackers calling the API.
Unlock Full Question Bank
Get access to all 7 HTTP Protocol and Web Fundamentals interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.