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

Workbench / Volume 2 Exercises: The Web Frontend

V2·19

Frontend Networking

Exercises for Volume 2, chapter 19: HTTP semantics (methods, status codes, headers, idempotency), HTTP/1.1, HTTP/2 and HTTP/3 with QUIC, the browser HTTP cache (freshness, heuristic caching, Cache-Control directives, stale-while-revalidate, Vary), ETags and conditional requests, compression, cookies (SameSite and third-party cookies), cross-origin access (the same-origin policy for reads, CORS, preflights and credentials), and real-time transports (polling, long polling, SSE, WebSocket, WebTransport). 9 theory questions, 9 programming exercises, 3 cumulative projects, the concepts the chapter leaves out, and 5 senior-level exercises.

32 exercises · ~13 min to read
Updated Suggest a correction

Start here: how this chapter's exercises work

Same four sets and the same locking. Frontend networking is Volume 1, chapter 09 seen from the browser: the exercises use a tiny Python server that logs every request (so you can see what the browser actually sends), Playwright, Resource Timing (performance.getEntriesByType('resource')) and the Network panel. All outputs in the solutions are real (Chromium 153); two of them correct common beliefs (P2's heuristic caching and P4's Vary behaviour).

The chapter's lab measured HTTP/1.1 vs HTTP/2 concurrency, cache directives on repeat visits, gzip vs Brotli, preflights and SameSite cookies; the exercises build on those. Chapter 17 already covered SSE and WebSocket client code, so this chapter's real-time exercises focus on choosing and operating transports.

Coverage map.

Chapter component Exercises
HTTP semantics: methods, status codes, idempotency, headers T1, P1
HTTP/1.1, HTTP/2, HTTP/3 and QUIC T2, P7
the HTTP cache: freshness, heuristics, directives, stale-while-revalidate T3, P2, P3
ETags, conditional requests, 304s T4, P3
Vary and cache keys T4, P4
compression T5, P5
cookies, SameSite, third-party cookies T6, P6
same-origin reads, CORS, preflights, credentials T7, P8
polling, long polling, SSE, WebSocket, WebTransport; choosing T8, P9
how it all shows up in performance (round trips, priorities, reuse) T9, P7

Theory

T1. HTTP semantics for frontend developers

  1. Classify GET, HEAD, POST, PUT, PATCH, DELETE and OPTIONS as safe and/or idempotent, and say why it matters for browser retries, prefetching (chapter 18's gaps), caches and links.
  2. What should the frontend do for 200, 201, 204, 301/302/303/307/308, 304, 400, 401, 403, 404, 409, 412, 422, 429 (with Retry-After), 500, 502, 503 and 504? Which are worth retrying automatically?
  3. Why is "everything returns 200 with {"error": …} in the body" harmful for caches, monitoring and clients?

T2. HTTP versions

  1. The chapter's lab sent 24 requests that each take 500 ms on the server: HTTP/1.1 finished in 2,044 ms (four waves of six connections) and HTTP/2 in 560 ms. Explain the six-connections limit, head-of-line blocking in HTTP/1.1 vs HTTP/2, and why HTTP/2 made domain sharding and sprite sheets obsolete.
  2. What does HTTP/3 change (QUIC over UDP, per-stream loss recovery, 1-RTT/0-RTT handshakes, connection migration: Volume 1, chapter 09's T6), and how does the browser discover and fall back (Alt-Svc, HTTPS DNS records)?
  3. HTTP/2 server push was removed from Chrome. Why did it fail, and what replaced it (103 Early Hints, preload)?

T3. The HTTP cache

  1. Explain freshness (max-age, Expires, Age), staleness and revalidation, and each directive: no-cache, no-store, private, public, must-revalidate, immutable, stale-while-revalidate, stale-if-error, s-maxage.
  2. P2 served /heuristic.js with only a Last-Modified date 10 days old and no Cache-Control: the browser served it from cache on later visits without asking the server at all. Explain heuristic freshness (10% of the age), and why every response should have an explicit Cache-Control.
  3. P2's /swr.js had max-age=1, stale-while-revalidate=60: on a visit 2 s later, it was served instantly from cache (0 bytes) and fetched again in the background (470 bytes). When is stale-while-revalidate right, and when is it wrong?
  4. Write the Cache-Control headers for: the HTML document, hashed JS/CSS, dish images, the menu API, a user's order history API, and the logout response.

T4. Conditional requests, ETags and Vary

  1. P3 served /etag.js with Cache-Control: no-cache and an ETag: each later visit sent If-None-Match and got a 304 with ~300 bytes of headers instead of the 470-byte response. Explain strong vs weak ETags, If-None-Match/If-Modified-Since, and what a 304 saves (and doesn't).
  2. How do ETags support optimistic concurrency for writes (If-Match with PUT/PATCH and 412 Precondition Failed)? Design the "two kitchen staff editing the same dish" flow.
  3. P4 fetched /vary.json (with Vary: Accept-Language, max-age=60) with Accept-Language: hi, then te, then hi again: the server saw three requests, so the third wasn't served from cache. Explain what Vary does, why browsers typically keep one cached variant per URL, and why Vary: User-Agent or Vary: Cookie is a CDN performance problem.

T5. Compression

  1. The chapter's lab compressed a 625 KB JavaScript file: gzip-6 → 111 KB (12 ms), gzip-9 → 110 KB (62 ms), Brotli-5 → 105 KB (13 ms), Brotli-11 → 90 KB (954 ms). Which settings do you use for static assets (pre-compressed at build time) versus dynamic API responses (compressed per request), and why?
  2. What doesn't compress (images, video, already-compressed files), and why is compressing responses that mix secrets with attacker-controlled input risky (BREACH: Volume 1, chapter 06's gaps)?
  3. What are Zstandard and compression dictionaries (shared dictionaries), and what problem do they solve for repeat visitors downloading a new version of a bundle?

T6. Cookies in the modern web

  1. The chapter's lab set four cookies (Strict, Lax, None, and an HttpOnly one) and observed which were sent: same-site requests got all; an <img> on another site got only SameSite=None; a top-level link from another site got Lax and None. Explain each, and why SameSite=Lax became the default.
  2. What does the deprecation and restriction of third-party cookies (Safari ITP, Firefox Total Cookie Protection, Chrome's changing plans and user choice) break, and what replaced the legitimate uses (CHIPS partitioned cookies, the Storage Access API, FedCM for federated login)?
  3. Cookies travel with every request to their domain. Estimate the cost of 3 KB of cookies on a page with 80 requests to the same domain, and say how to avoid it.

T7. CORS in depth

  1. The chapter's lab showed: a simple GET with no preflight; a JSON POST preflighted (OPTIONS with Access-Control-Request-Method: POST and -Headers: content-type) the first time and not the second (preflight cached with Access-Control-Max-Age); a form-encoded POST without preflight; a DELETE with a custom header preflighted. Explain the rules, and how to make an API need fewer preflights.
  2. P8: with credentials: 'include', why must the server send Access-Control-Allow-Credentials: true and an exact Access-Control-Allow-Origin, and what does Access-Control-Expose-Headers do (reading X-Request-Id or Location from JavaScript)?
  3. Explain why CORS errors are deliberately vague in JavaScript (TypeError: Failed to fetch) and how to debug them (Network panel, the console message, the preflight response).

T8. Choosing a real-time transport

  1. Compare polling, long polling, SSE, WebSocket and WebTransport on: direction, latency, overhead per message, behaviour through proxies and HTTP/2/3, reconnection, browser support and server complexity.
  2. For TiffinBox, choose a transport for: order status (customer), new-order alerts (kitchen display), live rider location on the customer's map, a support chat, and "how many people are viewing this kitchen" counters. Justify each.
  3. What does WebTransport add (multiple streams and unreliable datagrams over HTTP/3), and when would it beat WebSockets?

T9. Networking costs in page performance

  1. Using Volume 1, chapter 09's round-trip arithmetic, count the round trips before the first byte of the menu page on a cold visit (DNS, TCP, TLS 1.3, HTTP request) and after each optimisation: connection reuse, preconnect to the API and image CDN, HTTP/3, a CDN edge close to the user, 103 Early Hints.
  2. What are request priorities (fetchpriority, the browser's internal priorities for CSS, scripts, images, fetch), and how can a "fast" page still be slow because the hero image lost the priority battle?
  3. Explain how to read a Network panel waterfall: queueing, stalled, DNS, connect, SSL, request sent, waiting (TTFB), content download, and what each long bar usually means.

Programming exercises

P1. Status codes your client handles correctly

Write a small server with endpoints returning 200, 201 with Location, 204, 303 after POST, 400 with a problem+json body, 401, 403, 404, 409, 412, 422, 429 with Retry-After: 2, 500, 503. Extend chapter 15's API client so each is handled as T1 describes (parse problem details, re-auth on 401, honour Retry-After, retry only 429/502/503/504 for idempotent methods), and write tests that drive each case.

P2. Heuristic caching surprises

Serve three files: one with only Last-Modified (10 days ago) and no Cache-Control, one with Cache-Control: no-cache and an ETag, and one with max-age=1, stale-while-revalidate=60. Load a page referencing all three three times (immediately, then after 2 s), recording transferSize from Resource Timing and the server log. Then reload the page (F5) and note which files the browser re-requests.

P3. Conditional requests and optimistic concurrency

Add ETags to a menu API (GET /api/dishes/7 with ETag: "v12"), support If-None-Match (304) and If-Match on PUT (412 on mismatch). In two browser tabs, load the dish, change the price in tab A and save, then save a different change in tab B. Implement the UI for the 412: show both versions and let the user choose. Measure the bytes saved by 304s on repeated menu loads.

P4. What Vary really does in the browser

Serve /vary.json with Cache-Control: max-age=60 and Vary: Accept-Language, echoing the request's Accept-Language. Fetch it with hi, then te, then hi again, and count server requests. Then switch to language-specific URLs (/vary.json?lang=hi) and repeat. Discuss what a CDN would store in each design.

P5. Compression in your own stack

Take your built JavaScript bundle and the menu API's JSON response. Measure sizes and times for gzip 6 and 9, Brotli 5 and 11, and zstd 3 and 19 (with command-line tools or Python/Node libraries). Check your dev server's and production server's actual Content-Encoding for HTML, JS, JSON, SVG and images (with curl -H 'Accept-Encoding: br, gzip' -sI). Fix any missing compression and any compression of already-compressed formats.

P6. SameSite cookies and third-party contexts

Reproduce the chapter's lab setup: a "bank" site setting Strict, Lax, None; Secure and HttpOnly cookies, and a second site that embeds an image, an iframe and a link to the bank. Record which cookies each request carries. Then add a Partitioned (CHIPS) cookie set inside the iframe and check that it's different when the same iframe is embedded on a third site. Test in Chromium, Firefox and WebKit with Playwright.

P7. HTTP/1.1 versus HTTP/2, and connection setup

Set up a local HTTPS server that supports HTTP/2 (Caddy, nginx, or Node's http2 module with a mkcert certificate) and an HTTP/1.1 one. Load a page that makes 24 requests to an endpoint taking 500 ms, and record total time and nextHopProtocol. Then use Resource Timing to compute, for each request, DNS, connect, TLS and TTFB, and count how many connections were opened (requests whose connectStart differs from connectEnd).

P8. CORS with credentials and exposed headers

Serve an API on localhost:8002 for a page on localhost:8001. Make a credentialed fetch (credentials: 'include') that returns a session-dependent response and an X-Request-Id header. Try: no CORS headers; Allow-Origin: * with Allow-Credentials: true; the exact origin with credentials; then read X-Request-Id without and with Access-Control-Expose-Headers. Then make a PUT with Authorization and check the preflight and its caching with Access-Control-Max-Age: 600.

P9. A real-time transport decision, prototyped

Prototype "live rider location on the customer's map" three ways: polling every 3 s, SSE pushing every 3 s, and WebSocket pushing every 3 s, each from a small local server. Over 10 minutes per variant, measure the bytes transferred (Network panel or server counters), the number of requests, and the update latency (server send time to client receipt). Then simulate a network drop (DevTools offline for 20 s) and measure recovery for each. Write a one-paragraph recommendation.

Cumulative projects (chapters so far: Volume 1, and Volume 2's 00, 12–19)

C1. A caching and delivery plan for TiffinBox

Write and implement the caching and delivery configuration for TiffinBox's web app behind a CDN: Cache-Control and ETags for every response type (T3's table), hashed asset names from the build, Brotli/gzip pre-compression, Vary only on Accept-Encoding, language-specific URLs, HTTP/2 and HTTP/3 enabled, preconnect and Early Hints for the API and image origins, cookie scoping, a service worker strategy consistent with the HTTP cache (chapter 17's P7), and a purge strategy for the CDN. Verify each rule with automated checks (a script that requests each URL type and asserts headers) and measure a cold and a warm load before and after.

Combines: HTTP and TLS (Vol 1 ch 09); compression (ch 06); this volume's loading (ch 12), service workers (ch 17), browser internals (ch 18) and all of this chapter.

C2. A network-resilient API client, tested against chaos

Extend chapter 15's and 16's API client with: ETag-based conditional GETs and an in-memory cache honouring max-age; optimistic concurrency with If-Match (P3); Retry-After support; offline detection from failed requests; and request priority hints (priority: 'high' for checkout, 'low' for prefetches). Test it with Playwright's page.route injecting latency, 503s, dropped connections and 412 conflicts, and with chapter 09's latency proxy from Volume 1 (C2) at 300 ms RTT.

Combines: Volume 1's networking, retries and idempotency (ch 09, 11); this volume's JavaScript async (ch 15), types and schemas (ch 16), fetch and storage (ch 17) and this chapter's HTTP semantics and caching.

C3. Debug "the menu doesn't update after a kitchen edits it"

A kitchen owner changes a dish price in the partner portal; customers keep seeing the old price for up to 10 minutes, and some for hours. Investigate every cache between the database and the customer's screen (database read replicas, the API's in-process cache, the CDN, the browser HTTP cache, the service worker, IndexedDB, in-memory state in an open tab), describe how to check each, and design a fix that makes price changes visible within 60 s while keeping the menu fast.

Combines: replication lag and caches (Vol 1 ch 03, 09); service workers and IndexedDB (ch 17); this chapter's HTTP caching, ETags, stale-while-revalidate and CDN behaviour.

What the chapter leaves out

CDNs and the edge

Most production traffic is served by a CDN: edge locations cache responses close to users (Mumbai, Chennai, Hyderabad PoPs cut RTTs to ~10–30 ms), terminate TLS and HTTP/3, compress, and shield the origin. Concepts: cache keys (what parts of the URL and headers identify an object), s-maxage and Surrogate-Control, surrogate keys/tags for targeted purges, origin shielding (one regional cache in front of the origin), request collapsing (many simultaneous misses become one origin request), and edge compute (Cloudflare Workers, Lambda@Edge, Fastly Compute) for personalisation, A/B tests, redirects and auth checks without a round trip to the origin. Chapter 31 covers frontend deployment on them.

HTTP authentication patterns for SPAs

How the browser authenticates API calls shapes networking: session cookies (same-site API, HttpOnly, SameSite: the simplest and most secure for first-party apps), tokens in memory with silent refresh via an HttpOnly refresh cookie, the BFF pattern (a backend-for-frontend holds OAuth tokens server-side and gives the browser a session cookie: recommended by current OAuth guidance for browser apps), and Authorization headers (which trigger CORS preflights cross-origin: T7). Avoid tokens in localStorage (XSS-readable) and in URLs (logged). Volume 3's security chapter covers OAuth 2.1, OIDC and sessions in depth.

Request lifecycle tooling: HAR files, throttling and mocks

The Network panel can export a HAR (HTTP Archive) file of all requests with timings and headers, which is the best artefact for sharing a networking bug with a backend or CDN team (scrub cookies and tokens first: HAR files contain them). DevTools throttling profiles (Fast 4G, Slow 4G, custom latency/bandwidth) and request blocking reproduce slow or failing third parties; Local Overrides let you change response headers or bodies to test cache directives without redeploying. In tests, Playwright's page.route, MSW (Mock Service Worker) and routeFromHAR record and replay network traffic.

GraphQL, gRPC-Web and other API styles over HTTP

Not all frontends call REST: GraphQL sends queries (usually POST to one endpoint) and returns exactly the requested fields, which reduces over-fetching but complicates HTTP caching (POSTs aren't cached; persisted queries with GET restore it) and needs query cost limits; gRPC-Web and Connect carry protobuf over HTTP for typed, compact APIs; tRPC shares TypeScript types between a Node backend and the frontend. Each changes how caching, CORS, error statuses and observability work; the HTTP fundamentals of this chapter still apply underneath.

Privacy, tracking prevention and network-level signals

Browsers increasingly limit what the network reveals: referrer policies (strict-origin-when-cross-origin default), Client Hints replacing the full User-Agent string (Sec-CH-UA, requested with Accept-CH), link decoration stripping (tracking parameters removed from URLs in some browsers), bounce-tracking mitigation, IP protection features in some browsers, and Global Privacy Control (Sec-GPC: 1) as a legal opt-out signal in some jurisdictions. For analytics and personalisation, design first-party, consent-based, privacy-preserving measurement, and expect user-agent sniffing to break.

Senior exercises

S1. Diagnose a CORS failure that only happens in production

The new partner portal at partners.tiffinbox.in calls api.tiffinbox.in. It works on developers' machines and in staging, but in production about 5% of requests fail with CORS errors in the console, randomly. Plan the investigation and list the likely causes and fixes.

S2. Review an API's HTTP behaviour

A backend PR adds GET /api/menu?kitchen=42 returning 200 with {"success": false, "error": "not found"} for unknown kitchens, no Cache-Control, a new random ETag on every response, Set-Cookie with a tracking ID on every response, Access-Control-Allow-Origin reflecting any Origin, and POST /api/menu/refresh triggered by a GET link in the admin page. Write the review from the frontend networking perspective, ranked by severity.

S3. Decide on HTTP/3 and CDN configuration for Indian mobile users

Your users are mostly on Jio and Airtel 4G/5G networks across India, many on budget Android phones, with frequent switches between Wi-Fi and mobile data. Decide whether to enable HTTP/3 on the CDN, how to evaluate it (A/B by region, metrics), what risks to watch (UDP blocking, CPU cost on low-end phones, observability gaps), and what else at the network level would help these users most.

S4. Plan a migration from WebSocket polling hacks to a coherent real-time layer

TiffinBox's frontend has grown five real-time mechanisms: a 2-second poll for order status, a WebSocket for chat, another WebSocket for the kitchen display, long polling for notifications, and a Firebase listener for promotions. Each has its own reconnection logic and bugs. Propose a target architecture, the migration plan, and how to measure success.

S5. Teach caching with one request's journey

Write a 10-minute explanation for the team using one request, GET /api/kitchens/42/menu, traced through every cache it can hit (memory cache, service worker, browser HTTP cache, CDN edge, CDN shield, origin cache, database), with what decides a hit or miss at each layer and which headers control it. End with five rules.