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

Workbench / Volume 2 Exercises: The Web Frontend

V2·31

Frontend Deployment

Exercises for Volume 2, chapter 31: static hosting, object storage, CDNs and SPA fallbacks; server-rendered frontends on Node runtimes, serverless and edge runtimes, Docker, reverse proxies and TLS; and releases: immutable assets, cache invalidation, environment configuration, rollouts and rollbacks. 9 theory questions, 9 programming exercises, 3 cumulative projects, the concepts the chapter leaves out, and 5 senior-level exercises.

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

Start here: how this chapter's exercises work

Same four sets and the same locking. The measured exercises use nginx 1.24 as a reverse proxy, a self-signed certificate with OpenSSL 3.0, small Node 22 servers, and the Next.js 16.4.6 app from chapter 24. All outputs quoted are real. Docker wasn't available in this environment, so the container exercises give expected results instead. Four outputs are worth knowing before you start:

  • P1: an add_header inside an nginx location silently dropped the CSP and HSTS headers set at server level.
  • P2: nginx's default proxy buffering held a streamed SSR shell back until the whole response was done (811 ms instead of 2 ms).
  • P5: a server that exited on SIGTERM reset 14 of 20 in-flight orders, while graceful shutdown completed all 14 that had been accepted.
  • P6: assigning users to a canary with Math.random() per request would flip a user between versions on 40% of 10-page visits.

The chapter's lab measured a naive SPA fallback (a missing JS file returned 200 HTML), a deploy that deleted old chunks (a permanent "Failed to fetch dynamically imported module" in that tab), and three release-switching methods over 20 deploys. Copying over the live folder broke 229 of 878 loads, switching a pointer broke 141 of 1,926, and switching a pointer while keeping old assets broke 0 of 2,974. The exercises build on those.

Coverage map.

Chapter component Exercises
static hosting, object storage T1, C1
CDN T2, P8
SPA fallback T2
SSR hosting and Node runtimes T3, P4
serverless T4, P4
edge runtimes T4
Docker for frontends T5, P7
reverse proxies T6, P1, P2
TLS T7, P3
immutable assets T8, P8
cache invalidation T8, P8
environment configuration T9, P9
rollout and rollback T9, P5, P6

Theory

T1. Static hosting and object storage

  1. What does "static hosting" provide (files over HTTPS, a CDN, custom domains, redirects, headers, preview deploys, atomic releases), and what doesn't it (server rendering, server-side secrets, per-request logic, unless the host adds functions)? Compare Netlify/Vercel/Cloudflare Pages/GitHub Pages with S3 + CloudFront (or GCS + Cloud CDN) for TiffinBox's marketing site and the SPA partner portal.
  2. When serving from object storage, what must you set per object (Content-Type, Cache-Control, Content-Encoding for pre-compressed files), and why should the bucket be private with the CDN as the only reader (Origin Access Control)?
  3. The lab's experiment 3: copying files over the live folder broke 229 of 878 page loads during 20 deploys; switching a pointer broke 141 of 1,926; switching while keeping old hashed assets broke 0 of 2,974. Explain each failure mode and describe an atomic, additive deploy to S3 + CloudFront.

T2. CDNs and SPA fallbacks

  1. Revisit CDNs for deployment (chapter 19's C1): cache keys, what's cached at the edge (hashed assets forever, HTML briefly or not at all), origin shielding, purges, and how a CDN changes rollout behaviour (old HTML cached at the edge for s-maxage seconds after a deploy).
  2. The lab's naive SPA fallback returned 200 text/html for a missing /assets/missing-123.js; the proper one returned 404. Explain the consequences of the naive version (MIME errors instead of 404s, CDN caching HTML under a JS URL, invisible errors), and write correct fallbacks for nginx, Netlify and CloudFront.
  3. How should the SPA fallback interact with real 404 pages (unknown routes), SEO (soft 404s), and service workers (chapter 29)?

T3. SSR hosting and Node runtimes

  1. What does a server-rendered frontend need in production (a long-running Node process or a platform that runs it, enough CPU for rendering, connection pooling to APIs, streaming support end to end, logs, health checks)? Compare hosting options: a container on a VM/Kubernetes/ECS/Cloud Run, a platform (Vercel, Netlify, Render, Fly.io), and serverless functions.
  2. P4 started the chapter 24 Next.js app with next start: the process took 735–1,431 ms from start to its first response, the first request to the dynamic /orders page took 59–76 ms and the next 11–14 ms, and a never-before-rendered ISR page took ~35–41 ms first and ~5 ms after. Explain cold starts (process start, module loading, JIT warm-up, caches) and how they affect deployments and autoscaling.
  3. How many Node processes per machine, and why (single-threaded rendering, cluster or multiple containers, memory per process, CPU-bound SSR)? What are the signals to scale on (CPU, event-loop delay, response latency) rather than memory or request count alone?

T4. Serverless and edge runtimes

  1. Compare serverless functions (Lambda/Cloud Functions/Vercel Functions on Node) and edge runtimes (Cloudflare Workers, Vercel Edge, Netlify Edge, Deno Deploy) for frontend hosting: cold starts, execution limits, location relative to data, APIs available, pricing, and observability.
  2. What breaks when moving an SSR app to serverless (in-memory caches per instance, WebSockets/SSE, background work after the response, filesystem writes, connection limits to databases), and how do platforms address it (shared cache handlers, waitUntil, connection poolers like PgBouncer/RDS Proxy, streaming responses)?
  3. Chapter 24's T5 said edge rendering often doesn't help pages that query a single-region database. Give three TiffinBox use cases that do belong at the edge (redirects and geolocation, A/B bucketing: P6, auth gating with signed cookies, image transformation) and how to test them.

T5. Docker for frontends

  1. Write a multi-stage Dockerfile for the Next.js app (deps → build → runtime with output: 'standalone') and for the SPA (build → nginx or a static server). Why multi-stage, why a small base image (distroless, Alpine, node:22-slim), and why run as a non-root user?
  2. What makes container builds fast and reproducible (layer caching order: copy lockfile → install → copy source → build; .dockerignore; BuildKit cache mounts for the package store; pinned base image digests)?
  3. What must a frontend container handle at runtime (PID 1 signal handling and graceful shutdown: P5, health checks, read-only filesystem, environment configuration at runtime rather than build time: T9, logs to stdout, memory limits and --max-old-space-size)?

T6. Reverse proxies

  1. What does a reverse proxy do in front of a frontend (TLS termination, HTTP/2 and HTTP/3, compression, static file serving, caching, routing to SSR servers and APIs, headers, rate limiting, request size limits, WebSocket/SSE upgrades)? Compare nginx, Caddy, Envoy and cloud load balancers.
  2. P1: with security headers set at server level in nginx, / returned CSP and HSTS, but /assets/app-abc123.js, whose location added a Cache-Control header, returned only Cache-Control; repeating the security headers in that location restored them. Explain nginx's add_header inheritance rule and how to avoid the bug (includes, always, header tests).
  3. P2 streamed an SSR page (shell, then reviews after 800 ms) through nginx: with default proxy_buffering, the shell arrived at +811 ms together with the rest; with proxy_buffering off, or the upstream sending X-Accel-Buffering: no, at +2–3 ms; with gzip enabled and buffering off, still at +3 ms. Explain proxy buffering, why it breaks streaming SSR and SSE, and how to configure it per location.

T7. TLS

  1. Explain what TLS gives a frontend (confidentiality, integrity, server authentication), the certificate chain, SNI, ACME and Let's Encrypt (90-day certificates, and the CA/Browser Forum's schedule shortening maximum lifetimes towards 47 days by 2029), and automation (cert-manager, Caddy, managed certificates at the CDN).
  2. P3 configured nginx with ssl_protocols TLSv1.2 TLSv1.3: OpenSSL clients negotiated TLSv1.3 (TLS_AES_256_GCM_SHA384) and TLSv1.2 (ECDHE-RSA-AES256-GCM-SHA384); TLS 1.0 and 1.1 attempts got alert protocol version from the server (even with the client's legacy security level enabled). Why disable TLS 1.0/1.1, and what else belongs in a modern TLS config (forward-secret ciphers, OCSP stapling, session resumption, HTTP/2 and HTTP/3)?
  3. HSTS (Strict-Transport-Security: max-age=63072000; includeSubDomains; preload): what it prevents (SSL stripping), the risks of includeSubDomains and preload (every subdomain must have HTTPS; preload removal takes months), and how to roll it out safely.

T8. Immutable assets and cache invalidation

  1. Why are content-hashed file names (orders-c93bc377.js) the foundation of safe frontend deploys (caching forever, no invalidation needed, old versions coexisting)? What isn't hashed (HTML entry points, sw.js, manifest.webmanifest, robots.txt, OG images referenced by URL), and how should each be cached?
  2. The lab's experiment 2: after a deploy that deleted v1's chunks, a v1 tab clicking "Orders" failed with "Failed to fetch dynamically imported module", and the failure persisted in that tab even after the file was restored (the module map remembers failures). Write the client-side handling (catch chunk load errors, prompt or reload once with a loop guard) and the server-side policy (asset retention).
  3. When do you need CDN purges (HTML, mutable URLs, emergencies like a leaked file or legal takedown), and why are purges by tag/surrogate key better than wildcard purges?

T9. Environment configuration, rollouts and rollbacks

  1. "Build once, deploy everywhere": why should one artefact go through staging and production unchanged (chapter 30's C3, P7's cache lesson), and how do you give the client per-environment configuration at runtime (/config.json fetched at start, values injected by the server into HTML, window.__CONFIG__), and what must never be in it (secrets)?
  2. Compare rollout strategies for frontends: all-at-once, blue/green, canary by percentage (P6's hashing), feature flags (decoupling deploy from release), and per-region rollouts. What's different about frontend rollouts (users keep old versions open; CDN caches; mobile users on flaky networks)?
  3. How do you roll back a frontend (move the production alias to the previous deploy; re-point the CDN origin; restore the previous index.html; disable a flag), and what can't be rolled back easily (data migrations, service workers that cached new assets, API contract changes)? Design the rollback runbook.

Programming exercises

P1. nginx headers that don't silently disappear

Configure nginx with CSP and HSTS at server level and a location /assets/ that adds Cache-Control. Request / and an asset and list the headers. Fix it with an include file, add always, and write a CI test that requests one URL of each route type and asserts the security and caching headers.

P2. Keep streaming SSR streaming through the proxy

Put nginx in front of a server that streams a shell immediately and the rest after 800 ms. Measure when headers and each chunk arrive at the client, with default buffering, with proxy_buffering off, with the upstream sending X-Accel-Buffering: no, and with gzip. Then test the full chain including your CDN.

P3. A modern TLS setup

Generate a certificate (self-signed for local testing, ACME for staging), configure nginx with TLS 1.2 and 1.3 only, HTTP/2, OCSP stapling and HSTS, and test which protocol versions and ciphers are accepted with openssl s_client (and testssl.sh if available). Then automate renewal (certbot or cert-manager) and add expiry monitoring.

P4. Measure cold starts and warm-up

Start your SSR app (next start, or the standalone server) several times and measure: process start to first response, first and second request to a dynamic page, and first and second request to a page that hasn't been rendered yet. Then add a warm-up step before readiness (request key routes once), and compare the first user request after a deploy with and without it.

P5. Graceful shutdown during deploys

Write a server with 500 ms requests and a /healthz endpoint. Send 20 requests over 300 ms and send SIGTERM at 200 ms. Compare exiting immediately with graceful shutdown (fail readiness, server.close(), finish in-flight requests, hard deadline). Then explain the remaining refused connections and fix them with a pre-stop delay.

P6. Sticky canary assignment

Write a bucketing function that maps a user or anonymous id to 0–100 with a salted hash, and verify: about 5% of 100,000 users at 5%; everyone in the 5% stays in the 10% when you expand; the same user always gets the same answer; a different experiment salt gives an independent assignment. Compare with Math.random() per request. Then implement it at the edge (a CDN function setting a cookie and rewriting to the canary build).

P7. Containerise the SSR app

Write the multi-stage Dockerfile from T5 for the Next.js app (or Angular SSR), with a .dockerignore, BuildKit cache mounts, a pinned base image digest, a non-root user, SIGTERM handling (P5), health checks and a read-only root filesystem. Measure image size and build time (cold and with cache) and scan the image for vulnerabilities (Trivy or Grype).

P8. An additive deploy to object storage with a CDN

Write a deploy script for a static build to S3-compatible storage (MinIO locally, or a real bucket) behind a CDN: upload hashed assets with immutable caching first, upload HTML last with no-cache, set content types and encodings, never delete recent assets, invalidate only HTML, and keep the previous index.html for rollback. Simulate users with old tabs during the deploy and count broken loads (the lab's experiment 3 harness).

P9. Runtime configuration for a build-once artefact

Refactor an app that bakes VITE_API_URL and VITE_SENTRY_DSN into the bundle so the same build runs in staging and production: serve /config.json (or inject window.__CONFIG__ from the server/edge), load it before the app boots, validate it with Zod, cache it briefly, and fail visibly if it's missing. Verify by deploying one artefact to two environments.

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

C1. Deploy the customer app and partner portal

Deploy TiffinBox's Next.js customer app (SSR/ISR) and Angular partner portal (SPA) to production-like infrastructure: container images for SSR (P7) behind a reverse proxy with correct headers, buffering and TLS (P1–P3), a CDN with immutable assets and HTML policies (P8, chapter 19's C1), the portal on object storage with a proper SPA fallback, runtime configuration (P9), graceful shutdown and warm-up (P4, P5), canary releases by hash (P6), chunk-error handling and asset retention (T8), source maps uploaded per release (chapter 30's P5), and a rollback runbook. Run a release with a deliberate regression and roll it back.

Combines: HTTP, CDN and TLS (ch 19), full-stack frameworks (ch 24), performance (ch 27), security headers (ch 28), service workers (ch 29), build pipelines (ch 30) and this chapter.

C2. Preview environments for every pull request

Give every PR a preview: the frontend built and deployed to a unique URL (static host previews or containers per PR), pointed at a staging API (or an ephemeral backend), with seeded test data, protected from indexing and the public (auth or noindex + basic auth), with Playwright E2E and Lighthouse runs against the preview, a comment on the PR with links and results, and automatic teardown.

Combines: CI and testing (ch 26), performance budgets (ch 27), security headers and secrets (ch 28), build tooling (ch 30) and this chapter.

C3. A deployment incident review

During lunch, a release of the customer app caused blank screens for some users for 40 minutes: the deploy deleted old chunks, the CDN cached HTML for 10 minutes, a service worker served a mix of old and new files, and the rollback was slow because the previous build had been overwritten. Write the incident review: timeline, impact (from RUM and error tracking), root causes, contributing factors, and the corrective actions mapped to this chapter (additive deploys, chunk-error handling, SW update flow, HTML caching, immutable releases, rollback runbook, canaries).

Combines: Volume 1's incident management and post-incident reviews (ch 10), service workers (ch 29), CDN caching (ch 19), observability (ch 32's preview) and this chapter.

What the chapter leaves out

Infrastructure as code for frontend platforms

CDNs, buckets, DNS records, certificates, edge functions, WAF rules and preview environments should be defined in code (Terraform/OpenTofu, Pulumi, AWS CDK, the platform's config files like vercel.json/netlify.toml/wrangler.toml), reviewed in pull requests and applied by CI, so that header rules (P1), fallbacks (T2) and caching behaviours are versioned and reproducible rather than click-configured in a console nobody remembers.

DNS and domains

Deployments depend on DNS: apex domains with ALIAS/ANAME or CNAME flattening to CDNs, TTLs (lower them before migrations), DNSSEC, CAA records restricting which CAs can issue certificates, subdomain takeovers (dangling CNAMEs pointing at deleted CDN or storage resources that an attacker can claim: chapter 28's subdomain risks), and split horizons for internal tools. A DNS mistake can take the whole site down regardless of how good the deploy is.

Multi-region and disaster recovery

For SSR and APIs, multi-region deployment (active-active behind a global load balancer, or active-passive with failover) protects against regional outages, at the cost of data replication and consistency concerns (Volume 1). Static frontends are naturally multi-region via the CDN, but the origin bucket and the build/deploy system are single points of failure: replicate buckets across regions, keep the last good artefacts available outside the CI system, and document how to deploy if CI is down.

Compliance, data residency and cookies

Hosting choices affect compliance: India's DPDP Act and sectoral rules (RBI's payment data localisation), EU data residency expectations, logging of IP addresses and user agents at CDNs and proxies (personal data), cookie consent requirements for analytics set at the edge, and records of where data is processed. Choose CDN and log retention settings deliberately and document them.

Cost management

Frontend hosting costs come from CDN bandwidth and requests, image transformations, serverless invocations and duration, SSR compute, log storage and egress from origins. Caching (hit ratio), image optimisation, avoiding SSR for content that can be static, and log sampling usually matter more than the hosting provider's list price. Track cost per 1,000 page views per app, and watch for surprises like preview environments left running or uncached API routes at the edge.

Senior exercises

S1. Choose the hosting architecture

Decide how to host TiffinBox's frontends: the Next.js customer app (SSR/ISR, high traffic at lunch and dinner), the Angular partner portal (SPA, 2,000 tablets), the marketing site and blog, and Storybook. Options: one platform (Vercel/Netlify), self-hosted containers on Kubernetes behind a CDN, a mix, or serverless on AWS (OpenNext). Consider cost, control, performance in India (PoPs), compliance, team skills, lock-in and operations.

S2. Review a deployment configuration

A PR changes deployment: CloudFront custom error responses map all 403/404 to /index.html with 200; index.html gets Cache-Control: max-age=3600; the deploy uses aws s3 sync --delete; nginx's location /checkout adds add_header X-Frame-Options DENY; proxy_buffering stays at the default for the SSR upstream; the Node container runs npm start as root with no SIGTERM handling; and config.js with the API URL is generated at build time. Write the review.

S3. Design zero-downtime releases for the kitchen tablets

Kitchen tablets keep the portal open for 12+ hours, with a service worker, IndexedDB state and pending outbox operations (chapter 29). Design releases so a new version never breaks a tablet mid-shift: compatibility rules between old clients and new APIs, asset retention, service worker update timing, IndexedDB migrations, feature flags, and how to force an urgent fix (a security issue) onto every tablet within an hour.

S4. Plan a migration from a self-managed server to a CDN-first setup

TiffinBox's SPA is served from two VMs running nginx with no CDN; deploys are rsync to both; there's no TLS automation (a certificate expired last year); and lunchtime traffic overloads the VMs. Plan the migration to a CDN-first setup: what moves where, DNS cutover with low TTLs, header and fallback parity tests, rollback, and how you'll measure success.

S5. Teach safe frontend deploys with four failures

Prepare a 20-minute session using four real outputs: the lab's naive SPA fallback (missing JS → 200 HTML), the lab's deleted-chunk error that persisted in the tab, P1's vanished security headers, and P5's reset in-flight requests. For each: what happened, why, and the fix. End with five rules.