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

Workbench / Volume 2 Companion: The Web Frontend

V2·31

Frontend Deployment

Companion to Volume 2, chapter 31: how hosting, the edge and releases connect; new angles (a hashed asset as a book's ISBN, a release switch as a railway points lever, a rollback as a train reversing into a station that was rebuilt); what the chapter simplifies, measured on the build's stage 31: a rollback that 404'd because the older release had never heard of the newer one's files, nginx's default buffering holding every event of a live stream back for over 10 seconds, and two of eight kitchen displays unable even to load over HTTP/1.1; the theory behind atomic switches and validators; how serve-static decides headers and why an ETag made from a file's time breaks on redeploy; four debugging drills; interview questions with how to approach each.

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

Understanding it better

Concept map

Chapter 31 has three parts: static frontends (static hosting, object storage, CDNs, the SPA fallback), server-rendered frontends (SSR hosting and Node runtimes, serverless, edge runtimes, Docker, reverse proxies, TLS) and releases and configuration (immutable assets, cache invalidation, environment configuration, rollout and rollback).

static frontends server-rendered frontends releases static hosting files on a server object storage buckets, no server CDN copies near users SPA fallback index.html for routes cache headers per kind of file SSR hosting Node runtimes serverless, edge cold starts, limits containers one image everywhere reverse proxies buffering, headers TLS, HTTP/2 HSTS, multiplexing immutable assets hash in the name cache invalidation only the documents configuration build once, deploy anywhere atomic switch all old or all new rollout, rollback the same operation or behind with and or or behind ends leaves only and then and goes deeper: ch19 networking (caching) · ch24 SSR · ch29 service workers · ch30 build · Volume 6 infrastructure · Volume 16 production deployment exercises: P1–P9 nginx headers, streaming SSR, TLS, cold starts, graceful shutdown, canaries, containers, object storage, runtime config; C1–C3 deploy, previews, incident review
Concept map of chapter 31, frontend deployment: static frontends (static hosting, object storage, CDN, SPA fallback), server-rendered frontends (SSR hosting and Node runtimes, serverless, edge runtimes, Docker, reverse proxies, TLS) and releases and configuration (immutable assets, cache invalidation, environment configuration, rollout and rollback), with links such as content-hashed names making long caching safe and an atomic switch keeping old tabs working.

The links worth remembering:

  • Separate what can be cached forever from what can't. Content-hashed files can be cached for a year; the few documents that name them (HTML, an asset map, the service worker) can't be cached at all. Every caching layer (browser, CDN, service worker) then follows from that one split.
  • A deploy is "make available", then "make current". Uploading never changes what users get; switching a pointer does. Atomic switches, instant rollbacks and safe old tabs all come from keeping the two apart.
  • Everything between the server and the browser can change the response. Proxies buffer, compress, add and drop headers; CDNs cache; protocols multiplex or don't. Deployment is checking what actually arrives.

Explain it differently

1. A hashed asset name is a book's ISBN. A library can keep a book with a given ISBN on the shelf forever: a new edition gets a new ISBN. The catalogue (the HTML) is what changes, and the catalogue is what you check for updates.

2. A release switch is a railway points lever. The new track (the release) is laid completely beside the old one while trains keep running; one throw of the lever sends the next train down the new track. No train ever runs on a half-laid track.

3. A rollback is reversing into a station that was rebuilt. Trains that left from the new platform still expect to come back to it. If the old station doesn't have that platform (the newer release's files), they can't stop (Gaps 1).

4. Proxy buffering is a postman who waits for the whole letter. For a normal response that's efficient: one delivery. For a live stream, the letter never ends, so nothing is delivered (Gaps 2).

5. HTTP/1.1's six connections are six checkout lanes. Each open kitchen display stands in a lane forever, waiting for news. The seventh customer, even one with a single item (a page load), has no lane (Gaps 3). HTTP/2 is one lane with a conveyor that carries everyone's items at once.

6. Build once, deploy anywhere is a sealed parcel with a label. The parcel (the build) is the same everywhere; only the label (configuration read at start or from the page) differs by environment. Rebuilding per environment is repacking the parcel, and then you're not shipping what you tested.

7. HSTS is a promise the browser remembers. Once told, the browser refuses plain HTTP for that site for the stated time, even if the user types http://. That's why it's both strong and hard to undo.

Gaps and misconceptions

What the chapter oversimplifies

All outputs are real, from Chromium 153 headless, nginx 1.24 and the build's stage 31 (exp/31), unless stated.

1. Keeping old assets makes deploys safe, but not rollbacks. The chapter recommends additive deploys: new files are added, old ones kept for a while, so open tabs keep working. Stage 31 did that: each release carried the files of the releases before it. Under load, with four threads loading pages and all their files while the release switched back and forth:

Terminal
622 pages and their assets loaded during 10 switches, 11 failures

All eleven were 404s, all after a rollback. The older release was built before the newer one existed, so it couldn't carry the newer one's files, and a page rendered by the newer release a moment before the rollback asked for them afterwards. Carrying is now done at every switch (deploy or rollback), into the target, from every kept release: 664 pages and their assets loaded during 10 switches, 0 failures. "Additive" has to hold in both directions.

2. Reverse proxies buffer by default, and a stream never completes. The chapter's reverse-proxy section covers headers and TLS; P2 covers streaming SSR. A kitchen's event stream through nginx, three ways:

Terminal
direct (Java, HTTP/1.1)        snapshot after 5 ms; each new order seen after (ms): [0, 0, 0, 0, 0]
nginx, proxy_buffering off     snapshot after 1 ms; each new order seen after (ms): [0, 0, 0, 0, 0]
nginx, proxy_buffering on      snapshot after 10019 ms; each new order seen after (ms): ['>10000', '>10000', '>10000', '>10000', '>10000']

With nginx's default (proxy_buffering on), not even the first event arrived within 10 s: the response has no length and never ends, so nginx keeps filling its buffer. The browser would show the display as connected and silent. The configuration fix is per location; the robust fix is the upstream saying so on the response (X-Accel-Buffering: no), which nginx honours even where someone forgot the location: with it, the on case delivered the snapshot in 4 ms. Compression and other proxies (some CDNs, corporate proxies) can do the same, which is one reason the stream has a heartbeat (stage 17) that a client can watch.

3. HTTP/1.1's connection limit stops pages, not just streams. The chapter mentions that HTTP/2 multiplexes. Eight kitchen displays in one browser:

Terminal
  tab 7: Page.goto: Timeout 5000ms exceeded.
  tab 8: Page.goto: Timeout 5000ms exceeded.
HTTP/1.1, Java directly    (http/1.1): 6 of 8 displays live after 10 s
HTTP/2, through nginx      (h2): 8 of 8 displays live after 10 s

The seventh and eighth tabs didn't show a stale display: their HTML never loaded, because six open streams held all six connections the browser allows per host, and the page request queued behind them. Any tab of the site would have hung, the menu included. Over HTTP/2 all eight share one connection (h2). Long-lived connections and HTTP/1.1 don't mix beyond a handful of tabs; that limit is per browser profile and host, so kitchens with several stations on one device meet it.

Common misconceptions

Misconception What's actually true Where it's shown
"Keep old files and deploys are safe." Also in the rollback direction, or rollbacks 404. Gaps 1
"A proxy passes a stream through." nginx's default held it back entirely. Gaps 2
"The six-connection limit only slows things down." The seventh tab couldn't load at all. Gaps 3
"An ETag tells the browser whether a file changed." serve-static's ETag changes when the file's time does, even with the same bytes. Code walkthrough
"Cache-busting query strings are as good as hashed names." Some caches ignore query strings, and the file itself can't be kept for old tabs. Drill D3
"Content hashes depend only on content." esbuild's names changed with the build directory until the paths were made relative. Drill D1
"immutable is what makes assets long-lived." The year-long max-age does that; immutable only stops revalidation on reload (Firefox and Safari honour it; Chrome changed its reload behaviour instead). Explain it differently 1

Theoretical gaps: the ideas behind the chapter

1. Atomicity by indirection. Replacing a pointer is atomic where replacing content isn't: rename(2) of a symlink, a database row naming the current version, a CDN's origin setting, a load balancer's target group. The same idea appears in copy-on-write file systems and in persistent data structures.

2. Validators and freshness (RFC 9111). A cache serves a stored response while it's fresh (max-age); after that it revalidates with a validator (ETag, Last-Modified) and gets a 304 if nothing changed. Immutable assets skip revalidation; documents with no-cache always revalidate. A validator derived from metadata (time, size) can disagree with content; a content hash can't.

3. Version skew. During any deploy, old and new versions coexist: old tabs, cached workers, half-updated servers, mobile apps months behind. Systems that tolerate skew are designed for "N and N−1 at once": backwards-compatible APIs (stage 30), kept assets (stage 31), feature flags.

4. Head-of-line blocking. HTTP/1.1 sends one response per connection at a time, so a slow or endless response blocks that connection; HTTP/2 removes it at the HTTP layer but not at TCP (a lost packet stalls all streams), which HTTP/3 over QUIC addresses.

5. Trust on first use, made durable. HSTS turns one successful HTTPS visit into a remembered rule; preload lists remove even the first visit's exposure. The cost is irreversibility within max-age.

Applying it

Code walkthrough

Stage 31's server sets Cache-Control by hand. Most Node servers use serve-static, built on send. Excerpts from send 1.2.0 (used by serve-static 2.2.0), index.js, installed from npm.

The headers it sets

JavaScript
SendStream.prototype.setHeader = function setHeader (path, stat) {
  var res = this.res

  this.emit('headers', res, path, stat)

  if (this._acceptRanges && !res.getHeader('Accept-Ranges')) {
    debug('accept ranges')
    res.setHeader('Accept-Ranges', 'bytes')
  }

  if (this._cacheControl && !res.getHeader('Cache-Control')) {
    var cacheControl = 'public, max-age=' + Math.floor(this._maxage / 1000)

    if (this._immutable) {
      cacheControl += ', immutable'
    }

    debug('cache-control %s', cacheControl)
    res.setHeader('Cache-Control', cacheControl)
  }

  if (this._lastModified && !res.getHeader('Last-Modified')) {
    var modified = stat.mtime.toUTCString()
    debug('modified %s', modified)
    res.setHeader('Last-Modified', modified)
  }

  if (this._etag && !res.getHeader('ETag')) {
    var val = etag(stat)
    debug('etag %s', val)
    res.setHeader('ETag', val)
  }
}

The default is public, max-age=0 with an ETag and Last-Modified: always revalidate, and get a 304 when unchanged. immutable is opt-in and only meaningful with a long maxAge, which you must only set for hashed files (one configuration per kind of file, as stage 31 does). Every header is skipped if something already set it, so an on('headers') hook or earlier middleware wins.

What the ETag is made of

From the etag package that send calls with the file's stat:

JavaScript
function stattag (stat) {
  var mtime = stat.mtime.getTime().toString(16)
  var size = stat.size.toString(16)

  return '"' + size + '-' + mtime + '"'
}

The validator is the file's size and modification time, not its content: cheap (no reading the file), but it changes whenever the file is copied or touched, and two servers behind a load balancer with different file times give different ETags for identical files.

The conditional GET

JavaScript
  // conditional GET support
  if (this.isConditionalGET()) {
    if (this.isPreconditionFailure()) {
      this.error(412)
      return
    }

    if (this.isCachable() && this.isFresh()) {
      this.notModified()
      return
    }
  }

isFresh compares the request's If-None-Match and If-Modified-Since with the headers just set; a match is a 304 with no body.

Debugging drills

D1. Every release changes every file name

After moving the release job to a new CI runner, every deploy renames every script, even when only CSS changed, and users download everything again.

D2. Displays connected but silent after moving behind nginx

After putting the site behind nginx, kitchen displays say "Live" (the request succeeded) but no orders appear until someone reloads, and then they appear all at once.

D3. An old tab breaks after every deploy

A team uses app.js?v=123 and overwrites app.js on each deploy. Tabs opened before a deploy start failing when they load a lazily imported chunk.

D4. HTTPS works, but the theme setting is lost on the HTTPS site

After enabling HTTPS and HSTS, the theme preference set earlier on the plain-HTTP site seems to be ignored for some users, and there are now two tb-theme cookies in their browsers.

Career-oriented

Interview prep

Mid-level 1: cache headers

Question. "What cache headers would you set for index.html, main.3f2a.js, and /api/menu?"

How to get there. Classify each: does its URL change when its content does? Who else may cache it?

Mid-level 2: what happens to an open tab during a deploy?

Question. "A user has your SPA open when you deploy. What can go wrong, and how do you prevent it?"

How to get there. List what the open page will still request, then what can be missing or incompatible.

Senior 1: design the release process

Question. "Design how a frontend release goes from a merged commit to production, including rollback."

How to get there. Build, store, switch, observe, undo; and what makes each step safe.

Senior 2: why is our real-time feature flaky behind the load balancer?

Question. "A live dashboard using Server-Sent Events works locally but in production updates arrive late or in bursts, and connections drop every minute. Where do you look?"

How to get there. Every hop between server and browser, and what each does to long, unending responses.

Staff 1: CDN or not

Question. "We serve everything from our own servers in one region. Should we put a CDN in front, and what changes?"

How to get there. What it improves, what it risks, and what has to be true of the application first.

Staff 2: making rollbacks boring

Question. "Our last two incidents got worse during rollback. What would you change?"

How to get there. Why rollbacks fail, what to standardise, and how to keep it working.