Volume 2 Companion: The Web FrontendPractice for Volume 2
0 / 0

Workbench / Volume 2 Companion: The Web Frontend

V2·19

Frontend Networking

Companion to Volume 2, chapter 19: how HTTP itself, caching and state, and cross-origin access connect; new angles (idempotency as a lift button, ETags as a library's date stamp, CORS as a club's guest list, retries as a crowd at a closed door); what the chapter simplifies, measured in Chromium and Node: four ways a cancelled `fetch` rejects (and only one is an `AbortError`), a 64 KiB budget that two analytics beacons share, and an `If-None-Match` written by hand that turns the browser's invisible 304 into a failed request; the theory behind it; how `ky` decides what to retry (and why five clients come back within 4 ms of each other); four debugging drills; interview questions with how to approach each.

6 sections · ~15 min to read
Updated Suggest a correction

Understanding it better

Concept map

Chapter 19 has three strands. HTTP itself: methods and status codes, idempotency, HTTP/1.1, HTTP/2 and HTTP/3 with QUIC, and compression. Caching and state: the HTTP cache and freshness, ETags and conditional requests, Vary, cookies, SameSite and third-party contexts. Cross-origin access and real time: the same-origin policy, CORS, preflights and credentials, and the real-time transports.

HTTP itself caching and state cross-origin and real time methods, status codes what a request means idempotency safe to repeat HTTP/1.1 one at a time per connection HTTP/2 streams on one connection HTTP/3, QUIC no head-of-line blocking compression gzip · Brotli · zstd the HTTP cache fresh or stale ETags, conditionals 304 · 412 Vary one URL, many answers cookies state on every request SameSite which contexts send them third-party contexts partitioned, blocked same-origin policy reads are blocked CORS the server opts in preflights ask before sending credentials cookies across origins polling, SSE, WebSocket updates without asking WebTransport streams over QUIC defines carried by then then plus revalidates with keyed by beside limited by applies in relaxed by may need plus then newest goes deeper: ch12 the browser · ch17 browser APIs · ch28 security · ch31 deploys and CDNs · Vol 1 ch9 HTTP by hand exercises: P1–P9 status codes, heuristic caching, ETags, Vary, compression, SameSite, HTTP/2, CORS, real time
Concept map of chapter 19, frontend networking: HTTP itself (methods and status codes, idempotency, HTTP/1.1, HTTP/2, HTTP/3 and QUIC, compression), caching and state (the HTTP cache and freshness, ETags and conditional requests, Vary, cookies, SameSite and third-party contexts) and cross-origin access and real time (the same-origin policy, CORS, preflights, credentials, polling, SSE and WebSocket, WebTransport), with links such as idempotent methods being safe to retry and ETags turning a re-download into a 304.

The links worth remembering:

  • Idempotency is what makes retries safe. GET, PUT and DELETE are defined so that repeating them has the same effect as doing them once; POST isn't, unless the server makes it so with a key (Volume 1, stage 5). Every retry policy is a statement about idempotency.
  • Caching is a contract written in headers. The server says how long a response is fresh and how to check it afterwards (ETag); the browser keeps its side of the contract invisibly (Gaps 3).
  • The browser enforces rules for the user, not for you. CORS, SameSite and the same-origin policy protect the person using the browser from other sites; they say nothing about whether your server is safe from scripts, curl or attackers.

Explain it differently

1. Idempotency is a lift button. Pressing "3" once or five times sends the lift to floor 3 once. A POST /orders is a vending machine: press twice, get two drinks, pay twice. An idempotency key turns the vending machine into a lift button: "this is the same press as before".

2. An ETag is the date stamp on a library book. The library (server) stamps each edition. You (the browser) bring your copy and ask "is this still the current edition?" (If-None-Match). "Yes" (304) costs a sentence; "no" (200) means carrying home the new book.

3. CORS is a club's guest list, checked by the doorman, for the club's protection of your bag. The browser (doorman) won't let a page from one site read responses from another unless that other site lists it. The list is the server's (Access-Control-Allow-Origin), the enforcement is the browser's, and anyone not using a browser walks straight past.

4. A preflight is calling ahead. For an unusual request (a PUT, a JSON body, a custom header), the browser phones the server first: "a page from this origin wants to send this; will you accept it?" Only on "yes" does it send the real request.

5. HTTP/2 is one wide road instead of six narrow lanes. HTTP/1.1 gives each origin six single-file lanes; a slow lorry blocks its lane (Companion to chapter 17, Gaps 1). HTTP/2 is one road where everyone interleaves. HTTP/3 removes the last bottleneck: on HTTP/2, a lost packet still stops the whole road (TCP's head-of-line blocking); QUIC lets other streams keep moving.

6. Retries are a crowd at a closed door. If everyone who finds the door shut comes back exactly one minute later, the door opens to a stampede. Spreading the return (jitter) and having fewer people try at all (retry budgets) is what keeps the door usable (Code walkthrough).

7. Cookies are a wristband the browser shows on every visit. The server puts it on; the browser shows it automatically on every request to that site, from any page that makes one. SameSite is the rule about when the wristband is shown (only for visits you started on the site itself, or also for links from elsewhere).

8. A timeout is a promise to stop waiting, not to stop the work. When the client gives up after 5 seconds, the server may still finish the order a second later. The client then doesn't know what happened, which is exactly when an idempotency key matters (stage 19 measures it).

Gaps and misconceptions

What the chapter oversimplifies

All outputs are real, from Chromium (Playwright) and Node 22 against small local servers (exp/19).

1. "Abort a fetch with AbortController": and then check what you caught. The chapter cancels requests and catches AbortError. A fetch waiting on a slow endpoint, cancelled four ways:

Terminal
how a fetch rejects when it's cancelled:
  controller.abort()                                         -> DOMException name=AbortError message="signal is aborted without reason"
  controller.abort(new Error('superseded'))                  -> Error name=Error message="superseded"
  AbortSignal.timeout(500)                                   -> DOMException name=TimeoutError message="signal timed out"
  AbortSignal.any([c.signal, timeout(500)]), timeout first   -> DOMException name=TimeoutError message="signal timed out"

fetch rejects with the signal's reason: whatever was passed to abort(reason), a TimeoutError for timeouts, and an AbortError only when no reason was given. Code that treats e.name === 'AbortError' as "cancelled, ignore it" will report a user's own cancellation as an error if someone later adds a reason, and will treat timeouts as errors (which is usually right: a timeout is a failure, a cancellation isn't). Decide explicitly: compare e === signal.reason, or check signal.aborted before treating an error as a failure (drill D1). Stage 15's latest() checks both the sequence number and the name, so a superseded request is stale whatever its error.

2. Analytics as the page goes away: 64 KiB, shared. The chapter leaves out request lifecycle tools; real-user monitoring (stage 32) sends data with navigator.sendBeacon or fetch(…, { keepalive: true }) so it survives the page closing. Both have a budget:

Terminal
sending analytics as the page goes away (64 KiB limit):
  60 KiB: fetch keepalive -> sent | sendBeacon -> true
  70 KiB: fetch keepalive -> TypeError: Failed to fetch | sendBeacon -> false
  40 KiB: fetch keepalive -> sent | sendBeacon -> true, then false (two at once)

The limit is 64 KiB of in-flight keepalive data per page, shared by every beacon and keepalive request. Over it, sendBeacon returns false (silently, unless you check) and fetch rejects with an uninformative TypeError. Two 40 KiB beacons sent together: the first is accepted, the second refused. A page that sends its error log and its performance data at the same moment on pagehide loses one of them. Keep payloads small (aggregate on the client), check the return value, and send periodically instead of only at the end (drill D2).

3. Revalidation is invisible to your code, until you try to do it yourself. With Cache-Control: no-cache and an ETag, the browser revalidates every time and turns a 304 into the cached 200 for your code. Add the validator by hand and the browser steps aside:

Terminal
revalidation: the browser's cache against a hand-written If-None-Match:
  first fetch: 200
  second fetch (browser revalidates): status 200, body 52 bytes
  with If-None-Match set by hand: status 304, ok false, body 0 bytes
  requests the server saw: [('/menu', None), ('/menu', '"ff79c3d4ce47293c"'), ('/menu', '"ff79c3d4ce47293c"')]

The server saw two identical conditional requests and answered 304 to both, but the page got a 200 with the full body the first time (the browser's cache answered) and an empty 304 with ok: false the second (a conditional header added by script bypasses the cache). A client that adds If-None-Match "to save bandwidth" turns every unchanged response into an error, unless it keeps its own copy of the body. Leave revalidation to the browser for GETs; set If-Match yourself only for writes (Chapter Exercises P3) (drill D3).

Common misconceptions

Misconception What's actually true Where it's shown
"A cancelled fetch rejects with AbortError." It rejects with the signal's reason: TimeoutError, your own error, or AbortError only without a reason. Gaps 1; drill D1
"sendBeacon always sends." It returns false past 64 KiB of in-flight keepalive data, shared across the page. Gaps 2; drill D2
"My code sees 304s." The browser hides them unless you set the conditional header yourself, and then the body is empty. Gaps 3; drill D3
"Retry libraries make requests safe to repeat." They only retry methods assumed idempotent; POST needs a key. Code walkthrough
"Exponential back-off spreads retries out." Without jitter, everyone backs off by the same amounts and returns together. Code walkthrough; drill D4
"CORS protects my API." It protects users' browsers; any non-browser client ignores it. Explain it differently 3

Theoretical gaps: the ideas behind the chapter

1. The two generals problem: a client can't know. When a request times out, the client can't tell whether the server never got it, got it and failed, or succeeded and the response was lost. No protocol fixes this; it's a theorem about unreliable channels. The practical answer is to make retries harmless (idempotency) so that "I don't know" can always be followed by "do it again" (Explain it differently 8).

2. Exactly-once is at-least-once plus deduplication. Networks deliver messages zero or more times. "Exactly once" in practice means the sender retries until acknowledged (at least once) and the receiver remembers what it has done (an idempotency key, an event id). Stage 5's keys, stage 17's event ids and stage 19's retries are all the same idea.

3. Caching is consistency traded for speed, with explicit rules. A cached response may be stale; max-age, no-cache, stale-while-revalidate and ETags let the server choose how stale is acceptable per resource. It's the same trade-off as database replicas and CDNs: the question is never "cache or not" but "how wrong, for how long, and who decides".

4. Retries multiply. If each of three layers (browser, gateway, service) retries three times, one failing call becomes up to 27 calls at the bottom. Retry budgets (retry at most 10% of requests), retrying only at one layer, and circuit breakers (stop calling a failing dependency for a while) keep a partial outage from becoming a total one; the AWS Builders' Library article "Timeouts, retries, and backoff with jitter" is the standard reference.

5. The browser is a policy enforcement point, not a security boundary for servers. Same-origin, CORS, SameSite, CSP and Fetch Metadata are rules the browser applies on behalf of its user. The server can use the signals browsers send (stage 12's Sec-Fetch-Site), but must assume requests can come from anywhere, with anything in them.

6. HTTP semantics are a shared language for intermediaries. Methods, status codes and caching headers let proxies, CDNs, browsers and libraries act correctly without knowing your application: retrying GETs, caching 200s, not caching POSTs. Using them correctly (a 409 for a conflict, a 503 with Retry-After for overload) is what lets the whole chain help instead of guess.

Applying it

Code walkthrough

ky is a small fetch wrapper with retries, used widely in frontends. Its retry logic is a compact example of the decisions every client makes. Excerpts from version 1.7.5 (distribution/utils/normalize.js and core/Ky.js, installed from npm).

What gets retried, by default

JavaScript
const retryMethods = ['get', 'put', 'head', 'delete', 'options', 'trace'];
const retryStatusCodes = [408, 413, 429, 500, 502, 503, 504];
const retryAfterStatusCodes = [413, 429, 503];
const defaultRetryOptions = {
    limit: 2,
    methods: retryMethods,
    statusCodes: retryStatusCodes,
    afterStatusCodes: retryAfterStatusCodes,
    maxRetryAfter: Number.POSITIVE_INFINITY,
    backoffLimit: Number.POSITIVE_INFINITY,
    delay: attemptCount => 0.3 * (2 ** (attemptCount - 1)) * 1000,
};

The method list is HTTP's idempotent methods: POST and PATCH aren't retried, because the library can't know whether repeating them is safe. The status codes are the ones that mean "try again later" (timeout, too many requests, server errors, gateway errors); a 400 or 404 won't change on retry. The delay doubles from 300 ms. Note what's missing: randomness.

Deciding the delay

JavaScript
    _calculateRetryDelay(error) {
        this._retryCount++;
        if (this._retryCount > this._options.retry.limit || error instanceof TimeoutError) {
            throw error;
        }
        if (error instanceof HTTPError) {
            if (!this._options.retry.statusCodes.includes(error.response.status)) {
                throw error;
            }
            const retryAfter = error.response.headers.get('Retry-After')
                ?? error.response.headers.get('RateLimit-Reset')
                ?? error.response.headers.get('X-RateLimit-Reset') // GitHub
                ?? error.response.headers.get('X-Rate-Limit-Reset'); // Twitter
            if (retryAfter && this._options.retry.afterStatusCodes.includes(error.response.status)) {
                let after = Number(retryAfter) * 1000;
                if (Number.isNaN(after)) {
                    after = Date.parse(retryAfter) - Date.now();
                }
                else if (after >= Date.parse('2024-01-01')) {
                    // A large number is treated as a timestamp (fixed threshold protects against clock skew)
                    after -= Date.now();
                }
                const max = this._options.retry.maxRetryAfter ?? after;
                return after < max ? after : max;
            }
            if (error.response.status === 413) {
                throw error;
            }
        }
        const retryDelay = this._options.retry.delay(this._retryCount);
        return Math.min(this._options.retry.backoffLimit, retryDelay);
    }

Three details worth noticing. A timeout isn't retried (error instanceof TimeoutError): ky assumes a request that took too long once will take too long again, and avoids piling more load on a slow server. Retry-After wins over back-off when the server sends it, in any of its forms (seconds, an HTTP date, and non-standard rate-limit headers from GitHub and Twitter), with a heuristic for "seconds or a timestamp?" that names its own reason: clock skew (the Companion to chapter 17, Gaps 4). And network errors (a TypeError from fetch) aren't HTTPErrors, so they go straight to the back-off: retried.

Read it yourself

  1. Five clients hit a server that answers 503 (without Retry-After) twice and then succeeds. When do their retries arrive?
  2. The same server, with ky.post. What happens, and what would you need to make retrying it safe?

Debugging drills

D1. "Something went wrong" when users type fast

After a refactor of the search client, users who type quickly see a red "Something went wrong" banner flash, though results appear correctly a moment later. The refactor replaced controller.abort() with controller.abort(new Error('superseded by a newer search')) "for clearer logs". The error handler: if (e.name === 'AbortError') return; showBanner();.

D2. Error reports go missing when the page is closed

The frontend collects console errors and performance measures in an array and sends both on pagehide: navigator.sendBeacon('/rum/errors', errors) and navigator.sendBeacon('/rum/perf', perf). On busy kitchen displays, error reports are often missing; performance data usually arrives.

D3. The menu loads fine once, then "Failed to load menu" on every visit

A developer added ETag support to the menu client "to save bandwidth": it stores the ETag from the first response in localStorage and sends If-None-Match on later requests. From the second visit on, the menu fails to load until localStorage is cleared.

D4. Every deploy is followed by a two-minute error spike

Each deploy restarts instances one at a time. The API client retries GETs on 502/503 with exponential back-off (300 ms, 600 ms, 1.2 s, 2.4 s, up to 5 attempts). Monitoring shows request rates to the remaining instances jumping to five times normal in waves a few hundred milliseconds apart, and some of those instances failing too.

Career-oriented

Interview prep

Mid level

Q1. Which of these requests may a client retry automatically after a network error: GET /menu, PUT /dishes/7, POST /orders, DELETE /orders/o9/items/3, POST /orders/o9/events ("ready")?

How to get there. Start from HTTP's definition of idempotent methods, then check whether each request is actually idempotent in this API, since the definition is a promise the server has to keep.

Q2. A user reports that after changing their address, the app still shows the old one until they reload. The API returns Cache-Control: max-age=300 on GET /me. Explain and fix.

How to get there. Trace the requests: the update goes to the server, then the app fetches /me again. What does the browser do with a fresh cached response?

Senior level

Q3. Design TiffinBox's API client retry policy, for browsers and for the kitchen tablets.

How to get there. Decide which requests can be retried and how (methods and keys), which failures (network, status codes, timeouts), how long (attempts and a deadline), how to spread retries, and how to avoid amplification. Write it as a policy a team can implement.

Q4. You need to put a CDN in front of TiffinBox. What do you cache, for how long, and what do you never cache?

How to get there. Chapter Exercises leaves CDNs out. Classify responses by audience (everyone, a kitchen, a user) and by change rate, then give Cache-Control per class, and handle invalidation.

Staff level

Q5. Your company runs dozens of services with clients that each implemented retries differently. An outage of one dependency took down everything. What do you standardise?

How to get there. Look at the failure as a system: retries amplifying, timeouts too long, no isolation. Decide what to standardise (libraries, defaults, budgets, circuit breakers), at which layer, and how to roll it out and verify.

Q6. Product wants "instant" order status for customers on 2G and patchy 4G in smaller Indian cities. What's your networking strategy?

How to get there. Bound the problem by physics (latency, packet loss), then choose protocols, payload sizes, caching and real-time transport to match. Chapter Exercises S3 covers HTTP/3 and CDNs for Indian mobile users; focus here on the order-status experience end to end.