Skip to main content

Chapter 6 — Networking II: TLS, HTTP/1.1–3, Proxies, Load Balancers, CDNs

Part I · Foundations | Prerequisites: Ch 5 | Builds: the edge of the system — TLS, HTTP versions, proxies, LBs, CDNs

By now you've earned the byte stream. You can picture a packet finding its way across the internet, a TCP handshake building an ordered reliable pipe between two IPs, and DNS turning a name into one of them. You've also met HTTP as semantics: methods, status codes, headers, idempotency, safety. That was the wire from one socket to one socket. This chapter is about everything that lives between that raw socket and your handler — the part beginners wave at as "the cloud" or "the edge" and treat as magic.

It is not magic. It is three separable machines stacked on top of TCP: a machine that makes the pipe private and authenticated (TLS), a machine that frames and multiplexes many logical messages over the pipe (HTTP/1.1, /2, /3), and a machine that terminates, routes, balances, and caches those messages across a fleet (proxies, load balancers, CDNs). Get these three apart in your head and the entire edge stops being scary. Conflate them — as nearly every tutorial does — and you will spend years confused about why "enabling HTTP/2" didn't, why your cache leaked one patient's chart to the wrong clinician, and why a single expired certificate took the whole company offline at 3 a.m. This is the last chapter of Part I. After it, the spine you've been drawing across Part I is complete from the user's thumb to your handler's front door, and Part II walks inside that door.


1. The problem: why an entire tier exists between the socket and your code​

Let me give you three failures, because this chapter is born from three distinct pains and they don't share a fix.

Pain one: the pipe is naked. Early Pulsely ships on plain http://. A clinician logs in from a hospital cafeteria. Sitting two tables away is someone running tcpdump on the shared Wi-Fi. The clinician's login request crosses the air in cleartext; the attacker reads the Set-Cookie in the response, copies the session token, and now opens patient charts in Pulsely as that clinician from their own laptop. Nothing was "hacked" in the cinematic sense — the bytes were simply readable by anyone on the path, and the path includes the cafeteria's router, the ISP, and every hop in between. Notice that "encryption" alone is not the whole problem. You need three things at once: confidentiality (the sniffer learns no PHI), integrity (a man-in-the-middle can't silently flip a med order from dose: 10 to dose: 100), and authenticity (you're sure you're talking to the real pulsely.health and not an impostor who hijacked DNS). Plain HTTP gives you zero of the three. That gap is what TLS fills.

Pain two: one process is the entire front door. Earlier "the server" was one Node process bound to a port. That single process is now doing everything: terminating the public connection, paying the CPU cost of encryption, parsing HTTP, and running your business logic — all on the same event loop, on the same core. One deploy means restarting it, which means downtime. One malicious client uploading a 30 MB imaging study at one byte per second ties up resources your real clinicians need (you've already felt this exact stall). And the CPU cost of a TLS handshake — which is real and asymmetric, expensive for the server, cheap for the client — competes directly with JSON.stringify and your database calls for the same single thread. A serious system does not let its crown-jewel application logic share a core with connection grunt-work. It pushes the grunt-work outward, to a tier built for it.

Pain three: the protocol itself is fighting you. A patient's chart timeline loads twelve scanned documents. Over HTTP/1.1 a browser opens at most six connections per origin, so your twelve documents queue two-deep behind six pipes. Worse, a clinician on lossy hospital LTE drops a single TCP segment, and because TCP delivers bytes strictly in order, every in-flight response on that connection freezes until the lost segment is retransmitted — even responses whose bytes already arrived. The chart stalls though bandwidth is fine. This is head-of-line blocking, and it is a property of the framing and transport, not of your code. Newer HTTP versions exist precisely to attack it.

Strip the three pains to their shape and you get the reason this tier exists. The gap between "a reliable byte stream to one IP" (everything the previous chapter gave you) and "a global fleet of stateless app instances serving authenticated, multiplexed, cacheable requests to users on every network condition imaginable" is enormous. Something has to bridge it. That something is the TLS + HTTP-version + proxy/LB/CDN stack. It is not optional ceremony; each layer pays off a specific pain you'd otherwise feel in production.

🧭 A useful distinction. The "edge" is not one thing — it's a role (the outermost boundary that faces untrusted clients) that may be filled by a CDN, a cloud load balancer, a reverse proxy, or all three in sequence. Just as "backend" is a role independent of deployment, "the edge" is a role independent of which box fills it. This chapter teaches the roles; the boxes are interchangeable.


2. The mental model: three orthogonal axes and a boundary​

Here is the single idea that organizes this whole chapter. The edge varies along three axes that people constantly conflate, and your job is to keep them apart:

  1. Encryption — is the pipe private? This is TLS. It concerns the session: keys, certificates, identity. It says nothing about what messages flow inside.
  2. Framing — how are messages packed onto the pipe? This is the HTTP version: 1.1, 2, or 3. It concerns how bytes are cut into requests and responses and whether many can share one connection. It says nothing about whether they're encrypted.
  3. Topology — who terminates, routes, balances, and caches? This is the proxy/LB/CDN tier. It concerns where the hops are and what each hop is allowed to do.

In principle these are independent: you could run HTTP/2 with or without TLS, terminate TLS at any hop, balance load under any HTTP version. In practice they interact — browsers only speak HTTP/2 over TLS, and the protocol is chosen inside the TLS handshake via something called ALPN (§4). But the interactions are specific and learnable. The disaster is treating "HTTPS," "HTTP/2," and "the load balancer" as one undifferentiated blob.

🧭 Mental model. Encryption, framing, and topology are three dials, not one. When something at the edge misbehaves, your first move is to ask which dial: Is the pipe failing to go private (TLS)? Are messages framed/multiplexed wrong (HTTP version)? Or is a hop terminating/routing/caching incorrectly (topology)? Most edge confusion is a category error — debugging a framing problem as if it were an encryption problem.

The boundary​

Now the spatial picture, which is just Chapter 1's membrane drawn at network scale. There is a line — the trust + traffic boundary — and the world looks completely different on each side:

OUTSIDE the edge │ INSIDE the edge
untrusted · encrypted · slow · far │ trusted · plaintext · fast · near
│
┌──────────┐ TLS/HTTPS ┌──────────────┴───────┐ plain HTTP ┌─────────────┐
│ browsers │ ─────────────▶│ EDGE (terminates) │ ─────────────▶│ app instance│
│ mobile │ multiplexed │ decrypt · route · │ keep-alive │ app instance│
│ partners │ ◀─────────────│ balance · cache │ ◀─────────────│ app instance│
└──────────┘ └──────────────┬───────┘ └─────────────┘
the EDGE BOUNDARY
(where encrypted/untrusted becomes plaintext/trusted)

Outside the boundary: every byte must be encrypted, you assume hostility, latency is high, distance is real. Inside: a trusted network you operate, where plaintext is acceptable and hops are cheap and near. Everything in this chapter is a decision about where you draw that boundary and what is allowed to cross it. TLS termination is "where does encrypted become plaintext?" L7 routing is "what is allowed to read the HTTP and decide where it goes?" Caching is "what is allowed to answer without asking the origin?"

The hop chain​

The third picture refines the spine. A request no longer takes one TCP connection to one server. It takes a chain of independent hops, and — this is the load-bearing insight — each arrow is its own connection with its own TLS state, its own keep-alive, its own timeouts, and its own failure mode:

client ──TLS/h2──▶ CDN edge ──TLS/h2──▶ load balancer ──TLS/h1──▶ reverse proxy ──h1──▶ app
conn A conn B conn C conn D

There is no single connection from browser to app. There are four (or more), each terminated and re-originated at a hop. The browser's TLS session ends at the CDN; the CDN opens a fresh connection onward; and so on. This is the durable concept that unifies TLS termination, L7 routing, and caching: a hop terminates a connection when it decrypts, understands, and re-originates the request. Once you see "termination" as the common verb, the whole tier collapses into one idea applied at different layers.

📎 Borrowed on credit: statelessness. This hop chain only works because — as you've already glimpsed and as built fully in Ch 29 — the app instances are interchangeable. Any instance can answer any request because no instance holds per-user truth in memory; identity travels inside the request. That's the precondition that lets a load balancer fan a single clinician's requests across N instances without anyone noticing. We lean on it constantly below; Ch 29 owns the full treatment.


3. Theory & invariants​

A mental model tells you how to picture the edge. Invariants tell you what must stay true or the edge is wrong — leaking PHI, dropping security, or corrupting requests. These are the load-bearing rules.

TLS: three guarantees, two separable halves​

🔑 The TLS guarantee invariant. TLS provides exactly three things, and you should be able to name which one each design choice protects:

  • confidentiality — an eavesdropper learns nothing (encryption with a negotiated symmetric key).
  • integrity — any tampering in flight is detected. Here's the mechanism, because it's easy to hand-wave: the cipher attaches a small cryptographic checksum — the auth tag — computed over the real contents, so if an attacker flips even one bit the checksum no longer matches and the receiver rejects the message. (It's the same idea as a signed webhook payload, where a changed body fails signature verification.) Ciphers that encrypt and run this tamper-check together are called AEAD — authenticated encryption.
  • authentication — you are talking to whoever the certificate proves, anchored in a trust store.

Critically, authentication is one-directional by default: the server proves its identity to the client; the client proves nothing back until you add mutual TLS (mTLS, §8). Most "is this secure?" questions resolve to "which of the three am I actually getting, and in which direction?"

🔑 The handshake-separation invariant. Inside the handshake, key agreement is separate from identity proof. Take key agreement first, in plain terms: the two sides each throw in a random ingredient, mix them together in public, and independently arrive at the same secret number — and an eavesdropper who watched the entire exchange still can't reproduce it. That's Diffie–Hellman; ECDHE is the elliptic-curve, throwaway-per-connection variant. The result is a shared symmetric key that neither side ever transmitted. Separately, the certificate signature proves the server is who it claims.

Keeping these two apart buys you forward secrecy. Because that shared secret is ephemeral — derived fresh for this one connection and thrown away when it closes — an attacker who records today's encrypted traffic and later steals the server's long-term private key still cannot decrypt what they recorded. The private key proves identity; it does not unlock past sessions. This is why "they'll just steal the key eventually" is not the catastrophe it sounds like — past traffic stays sealed.

The cost of the handshake is measured in round trips, and the version matters: TLS 1.3 completes in 1 RTT (and 0 RTT for resumed connections, with a sharp caveat below); TLS 1.2 took 2 RTT. On top of the TCP handshake you've already met (1 RTT) and DNS, this is why a cold HTTPS connection feels sluggish and why connection reuse is everything.

🔑 The chain-of-trust invariant. A certificate is trusted not because it asserts a hostname but because it is signed by a key your client already trusts — transitively. The leaf cert (for pulsely.health) is signed by one or more intermediate CAs, which are signed by a root CA whose public key is pre-installed in the client's trust store (the OS/browser shipped it; you decided to trust whoever ships your OS). Validity requires all of: the signature chain links unbroken to a trusted root, and the cert is not expired, and the hostname matches a Subject Alternative Name (SAN — not the legacy Common Name), and it isn't revoked. Break any one and the connection must fail. Most production TLS incidents are a broken link in exactly this chain.

🔑 The SNI invariant. There's a chicken-and-egg problem: one IP often serves many hostnames (many certs), so the server must know which hostname before it can send the right cert — but the cert comes during the handshake. The fix is SNI (Server Name Indication): the client names the host in the ClientHello, before encryption is established, so the server can pick the cert. Consequence: the hostname you're visiting travels in cleartext even on HTTPS (an eavesdropper can't read your request, but can see which site you hit). Encrypted ClientHello (ECH) is the in-progress fix; for now, just know SNI leaks the hostname.

HTTP across versions: semantics are invariant, framing changes​

🔑 The version-invariance invariant. This is the most freeing idea in the chapter. HTTP semantics — methods (GET/POST/PUT/DELETE), status codes, headers, and the safety/idempotency rules you've already met — are identical across HTTP/1.1, /2, and /3. What changes between versions is only the wire framing and multiplexing: how bytes are cut into messages and whether many messages share one connection. You do not relearn HTTP per version. A GET /patients/:id/chart means the same thing and a 409 Conflict means the same thing whether it rides 1.1, 2, or 3. Version is a transport detail; semantics are stable.

🔑 The multiplexing invariant (HTTP/2+). HTTP/2 and /3 carry many independent streams over one connection, each separately flow-controlled. Ordering is guaranteed within a stream but not across streams. So response B can complete before response A even though A's request came first — perfectly fine, because each stream is its own ordered conversation. This is what kills HTTP/1.1's six-connections-per-origin limit: one connection now carries unlimited concurrent requests.

🔑 The head-of-line-blocking invariant, precisely scoped. HoL blocking exists at different layers in each version, and conflating them is the classic mistake:

  • HTTP/1.1 — HoL at the request layer: one connection carries one response at a time, so a slow response blocks everything queued behind it.
  • HTTP/2 — solves request-layer HoL via multiplexing, but reintroduces it at the TCP layer: because TCP delivers bytes strictly in order, a single lost segment stalls all streams until retransmission, even streams whose data already arrived.
  • HTTP/3 / QUIC — solves it at the transport, because QUIC owns its own ordering per stream over UDP, so a lost packet stalls only the one stream it belonged to. The senior answer to "does HTTP/2 fix HoL?" is "at the HTTP layer yes, at the TCP layer no — and that's exactly what QUIC was built to fix."

Load balancing and caching invariants​

🔑 The idempotency-retry invariant. A load balancer that retries a failed request must respect HTTP method semantics. Safe/idempotent requests (GET, PUT, DELETE) can be retried across instances with no harm. Non-idempotent requests (a bare POST that submits a claim) cannot be blindly retried — a retry after an ambiguous timeout may submit the same claim twice, so the payer sees a duplicate. The LB's retry policy is not a free knob; it's bounded by method semantics, and POSTs need idempotency keys to be safely retryable.

🔑 The cache-correctness invariant. A response may be cached and reused only if it is safe to serve the right response to the right set of users for the right duration. Three things together define correctness: the cache key (what makes two requests "the same" — usually URL plus selected headers), freshness (Cache-Control max-age / s-maxage, how long it's valid), and Vary (which request headers change the response and must therefore be part of the key). Violate the key and you leak one patient's chart to the wrong clinician — a reportable HIPAA breach, not a mild bug. Violate freshness and you serve staleness. Both are correctness bugs, not performance bugs.

📎 Borrowed on credit: caching theory. This chapter covers only HTTP and CDN caching — the wire-level mechanics of Cache-Control, ETag, cache keys, and edge revalidation. The general theory of caching — cache-aside vs write-through patterns, invalidation strategy, staleness reasoning, stampede control as a data-layer concern — is owned by Ch 21. When you need to reason about caching beyond the HTTP edge, that's the chapter. Here, cache = "what a hop may answer without asking the origin."


4. Under the hood: how each machine actually works​

Let's open the three machines, just enough to kill the magic. Each gets deeper treatment in later parts; here we learn what it is and how it behaves.

The TLS 1.3 handshake, step by step​

Picture the handshake as a four-message dance riding on the TCP pipe you already established:

CLIENT SERVER
│ ── ClientHello ──────────────────────────────────────────▶ │ "here are my ciphers,
│ (cipher suites, key share, SNI: pulsely.health, ALPN: h2)│ a key share, the host
│ │ I want, and which HTTP
│ │ versions I speak"
│ ◀────────────────────────────── ServerHello + {cert} + Fin │ "chosen cipher, my key
│ (chosen cipher, key share, then ENCRYPTED: cert, ALPN=h2)│ share — and from here on
│ │ everything's encrypted,
│ ── Finished ──────────────────────────────────────────────▶ │ here's my cert + done"
│ ══════════════ application data (your HTTP/2) ══════════════ │

After ClientHello and ServerHello, both sides can derive the shared key (each had a key share; ECDHE combines them). So in TLS 1.3 the server's certificate is itself sent encrypted, and application data flows after just 1 round trip. TLS 1.2 needed an extra round trip and an explicit ChangeCipherSpec ceremony before encryption began, and sent the cert in the clear — that extra RTT is precisely what you'd measure if you forced 1.2 in the handshake-archaeology exercise (§9).

🏭 ALPN is how the HTTP version gets chosen. Tucked inside that ClientHello is ALPN (Application-Layer Protocol Negotiation): the client lists the protocols it speaks (h2, http/1.1), and the server picks one — inside the TLS handshake, before any HTTP flows. This is the answer to a question that confuses everyone: HTTP/2 is effectively TLS-only in the wild because browsers negotiate it via ALPN, which only happens during a TLS handshake. So "enable HTTP/2" really means "negotiate h2 via ALPN at whatever hop terminates TLS." If TLS terminates at the CDN and the CDN doesn't offer h2 in ALPN, you don't have HTTP/2 to clients no matter what your app config says.

Session resumption is how you avoid paying the full handshake every time. TLS 1.2 used session tickets; TLS 1.3 uses a pre-shared key (PSK) from a prior session. The elegant trick is statelessness: the server hands the client an encrypted ticket and keeps no per-session memory — the client presents it next time to resume. The tradeoff is ticket-key rotation: the key that encrypts those tickets must be rotated, or a stolen ticket key retroactively breaks forward secrecy for resumed sessions. TLS 1.3 also offers 0-RTT early data — sending application data in the first flight, before the handshake completes — which is a latency win but carries a sharp hazard:

🔑 The 0-RTT replay invariant. 0-RTT early data is replayable by a network attacker — there's no round trip yet to prove freshness. So 0-RTT must be restricted to safe, idempotent requests only. A POST /claims sent as 0-RTT early data can be captured and replayed to submit a duplicate claim. Same idempotency reasoning as LB retries, different layer.

Why you don't terminate TLS in Node​

In Node, you can terminate TLS — https.createServer({ cert, key }, app), with tls.createSecureContext and an SNICallback to pick certs per hostname:

import https from 'node:https';
const server = https.createServer({
SNICallback: (servername, cb) => cb(null, contextFor(servername)), // pick cert per host
}, app);

And in production you almost never do. Three reasons, each a real operational wound: Node's crypto runs on the single event loop thread, so every handshake's asymmetric CPU cost competes with your handlers; Node has no graceful certificate reload (rotating a cert means restarting the process, i.e., dropping connections); and it lacks the connection-draining and slow-start machinery a real terminator has. The conclusion writes itself, and it's the chapter's ADR: put a purpose-built proxy in front and let it terminate TLS. The same logic applies to the JVM:

🏭 The proxy contract is language-agnostic. (Skippable if you don't run the JVM — the payoff is the last sentence.) A Spring Boot app behind Nginx looks identical from the edge to a Node app behind the same Nginx — same TLS termination, same X-Forwarded-*, same health checks. The thread-per-connection JVM (Tomcat/Netty) feels slow-client backpressure and TLS CPU cost differently internally than Node's event loop, but the edge doesn't care. This is why the proxy tier is where polyglot fleets converge: the contract is HTTP, not your runtime.

HTTP/2 internals​

HTTP/2 replaces HTTP/1.1's plaintext, line-based framing with a binary framing layer. Requests and responses become sequences of typed frames carrying a stream ID (clients use odd IDs, the server even), and frames from many streams interleave on one connection — that's the multiplexing. Three details matter:

  • HPACK header compression. HTTP headers are repetitive (the same cookies, user-agent, accept headers on every request). HPACK compresses them with a static table of common headers plus a dynamic table of ones seen this connection. It saves real bytes — but here's the danger: compression shrinks repeated bytes, so if an attacker can plant guessed text right next to your secret session token in the same request and watch the compressed size shrink whenever the guess matches, they can recover the token one character at a time. That leak is exactly the recipe behind CRIME/BREACH-style attacks (§8). Separately, a malicious peer can try an HPACK bomb (a tiny compressed payload that expands hugely) to blow up memory. Compression is never free of security implications.
  • Flow control exists at two levels: per-stream and connection-level windows, so one greedy stream can't starve the rest.
  • Server push — the server proactively sending resources the client didn't ask for — was the marquee feature and has been largely deprecated and abandoned; browsers dropped it because it rarely beat smart caching and often wasted bandwidth. Mention it only so you recognize it as a dead end.

HTTP/3 and QUIC​

HTTP/3 runs over QUIC, which runs over UDP instead of TCP. The radical move: QUIC integrates TLS 1.3 into the transport itself (encryption isn't a layer on top — it's built in) and owns its own ordering per stream, which is what finally kills TCP-layer head-of-line blocking. Two more wins: connection IDs that survive an IP change, so a phone moving from Wi-Fi to LTE (NAT rebinding) keeps its connection alive instead of reconnecting; and QPACK, HPACK's successor, redesigned so header compression itself doesn't reintroduce HoL blocking. The catch is operational: because QUIC is UDP, and decades of firewalls and middleboxes were built assuming UDP is for DNS and games (and TCP is for "real" traffic), UDP deployment is harder than TCP — some networks throttle or block it, and tooling is younger.

Proxies, load balancers, and CDNs​

A forward proxy is configured by the client and hides the client from the server — corporate egress filtering, for instance ("all our staff appear to come from this one IP"). A reverse proxy is server-side and hides the backend from the client; it terminates the public connection, routes, and re-originates to upstreams. They're mirror images: forward proxies serve the client's interests, reverse proxies serve the server's. The reverse proxy is what this chapter cares about, and its mechanics are: rewrite the Host header for the upstream, inject X-Forwarded-For / X-Forwarded-Proto / X-Forwarded-Host so the app can recover the real client IP and original scheme it can no longer see directly, and pool keep-alive connections to upstreams so the short internal hop doesn't repay setup per request.

forward proxy: client ─▶ [proxy] ─▶ ANY server (hides the client; client configures it)
reverse proxy: client ─▶ [proxy] ─▶ your servers (hides the backend; server operates it)

Load balancers come in two layers, and the difference is exactly how much of the request they understand:

  • L4 (transport) forwards TCP/UDP by the 5-tuple you've already met. It's fast and protocol-agnostic but opaque — it cannot read HTTP, so it cannot route by path, read a cookie, or terminate TLS for routing. It just shovels connections to backends.
  • L7 (application) parses the HTTP. It can route by host/path/header, do sticky sessions, apply retry policies, terminate TLS, and emit rich observability — all at higher CPU cost because it actually understands every request. Pulsely wants L7 at its edge: routing /api versus /imaging differently, reading the auth context to enforce minimum-necessary access, and caching public reference data by URL all require understanding HTTP.

A CDN is a reverse proxy distributed geographically. Anycast routing sends each user to the nearest PoP (point of presence — a data center close to them). On each request the PoP does a cache lookup: hit → serve from the edge (no origin round trip, huge latency win); miss → fetch from origin, store per Cache-Control, serve. The cache key composes the URL plus selected headers/query, ETag/Age drive revalidation (the PoP asks origin "still fresh?" with If-None-Match, gets a cheap 304 Not Modified if so), and Vary multiplies cache entries — Vary: Accept-Encoding means gzip and brotli versions are cached separately. We map the full decision flow in §9's diagram.


5. In production: the path that actually runs​

The teaching chain in §2 is close to real, but production adds the operational details that tutorials skip and that page you at 3 a.m.

Certificate lifecycle is automation, not a task. Modern certs (Let's Encrypt) are valid for 90 days by design — short enough to force you to automate renewal via ACME (certbot, Caddy, or your LB's built-in client). The classic outage is a human-renewed cert that expired because the human left, was on vacation, or forgot; "the whole site is down and curl says certificate expired" is a rite of passage you should never have. Know the knobs: ACME has staging vs production endpoints (test against staging or you'll hit rate limits), HTTP-01 (prove control by serving a token over HTTP) vs DNS-01 (prove control via a DNS record — the only way to get wildcard certs), and wildcard vs SAN certs (one *.pulsely.health vs an explicit list of names).

Where TLS actually terminates is a real architectural choice, usually the CDN, the LB, or a reverse proxy — not the app. The follow-on decision is plaintext-internal vs re-encrypt-to-upstream: after terminating at the edge, do you forward plaintext HTTP across your internal network (simple, fast) or re-encrypt to each upstream (defense-in-depth)? Compliance regimes and zero-trust networking force re-encryption; most low-stakes teams on a trusted VPC run plaintext internally. For a PHI platform this is not a coin flip — it's the chapter's ADR, taken up in §7.

Health checks separate liveness from readiness, and this distinction prevents outages. The LB actively probes each instance (GET /healthz) and routes only to healthy ones; it may also passively eject an instance that returns connection errors. The trap is probe depth:

🏭 Liveness must be shallow; readiness may be deep. A liveness probe answers "is this process alive?" — it must check only the process itself, never a dependency. A readiness probe answers "should this instance receive traffic right now?" and may check dependencies. The catastrophe is a liveness probe that hits Postgres: one database hiccup makes every instance fail liveness simultaneously, so the orchestrator restarts the entire fleet at once, turning a 5-second DB blip into a total outage — every clinician locked out of every chart at the same moment. Liveness gates restarts; readiness gates traffic. Never let a shared dependency flip a liveness check. Also: slow-start (ramp traffic to a freshly-healthy instance gradually, don't slam it cold) and connection draining (stop sending new requests to an instance being deployed, let in-flight ones finish).

LB algorithm choice is workload-dependent. Round-robin (rotate evenly) is the default and fine for uniform requests. Least-connections (send to the instance with the fewest in-flight) wins when request cost is heterogeneous — which is exactly Pulsely's mix of cheap chart reads and heavy imaging/document uploads, where round-robin would unluckily pile three large uploads on one instance. EWMA/least-latency routes by recent response time; consistent hashing routes the same key to the same instance for cache affinity. Match the algorithm to the cost distribution.

Reverse-proxy config tutorials skip is where production lives: upstream keep-alive pools (reuse internal connections), deliberate timeouts (connect/read/send — never "wait forever"), buffer sizes for large uploads, gzip/brotli at the edge (compress once, near the user), and the one that bites everyone:

🏭 Trust X-Forwarded-For only from known proxy IPs. Any client can send an X-Forwarded-For header claiming to be any IP. If your app blindly trusts it, an attacker spoofs their IP to defeat rate-limiting, poison the audit log (attributing their access to someone else's IP — a real problem when "who touched this chart, from where" is a compliance question), and bypass IP allowlists. The rule: configure exactly how many proxy hops you trust and read the client IP from the correct position — in Express, app.set('trust proxy', <n>) set to your known proxy count, never true blindly. The forwarded headers are trustworthy only when injected by a proxy you control and received from an IP you recognize.

HTTP version rollout in the field is usually HTTP/2 to clients at the edge, HTTP/1.1 to upstreams — the internal hops are short and fast on a reliable network, so multiplexing buys little there, and HTTP/1.1 is simpler to debug. HTTP/3 is advertised to clients via an Alt-Svc response header ("you can also reach me over h3 at this UDP port") with graceful fallback to h2 if UDP is blocked. Watch the protocol field in your access logs to confirm what clients actually negotiated — "we enabled h2" is a claim until the logs show h2.

CDN/cache operations hinge on getting freshness and scope right: fingerprinted asset URLs (app.4f3a.js) let you cache forever and bust by changing the URL, far better than racing a purge API whose propagation across PoPs lags. Use Cache-Control: private or no-store for authenticated Pulsely pages (a chart, a worklist, a claim) so they're never shared; distinguish s-maxage (how long shared caches like the CDN may keep it) from max-age (how long the browser may); and reach for stale-while-revalidate to serve a slightly-stale public page instantly while refreshing in the background — resilience and speed at once. (PHI, of course, is never a candidate for shared staleness.)

🏭 The edge is your best measurement point. TLS handshake latency, p99 by HTTP version, per-upstream error rates at the LB, and cache hit ratio all live at the edge — and the edge sees real user latency including the network legs your app can't observe from inside. When you instrument later (Ch 34), the edge is where the truest user-experienced numbers are.


6. Common pitfalls​

Each is signature → fix: the symptom you'll see, then the principle that resolves it.

Expired or incomplete certificate chain. Signature: curl from your laptop works fine, but mobile browsers and Java clients fail with trust errors — because your laptop happened to have the intermediate cached and they don't. Fix: serve the full chain (fullchain.pem: leaf + intermediates), not just the leaf. The chain invariant requires every link present. Verify with SSL Labs or openssl s_client -showcerts. And automate renewal so "expired" never happens.

Hostname mismatch. Signature: the cert is valid but the browser shows ERR_CERT_COMMON_NAME_INVALID. Fix: modern clients validate the SAN, not the legacy CN. List every served hostname as a SAN; remember a wildcard *.pulsely.health covers one label only, not a.b.pulsely.health.

X-Forwarded-For spoofing / trust proxy misconfiguration. Signature: your rate limiter keys on an attacker-controlled header and is trivially bypassed; or Express logs the proxy's IP for every request because it's reading the wrong hop. Fix: set app.set('trust proxy', <exact hops>) to your known proxy topology; never true blindly. Trust forwarded headers only from proxy IPs you operate.

Mixed content and redirect loops after edge TLS termination. Signature: TLS terminated upstream, so the app thinks it's serving plain HTTP — it emits http:// redirects and sets cookies without the Secure flag; or both proxy and app force HTTPS and you get an infinite redirect. Fix: honor X-Forwarded-Proto so the app knows the original scheme was HTTPS. Force the redirect in exactly one place, not both.

"We enabled HTTP/2" but it never negotiated. Signature: config says h2, but every request is still HTTP/1.1. Fix: HTTP/2 is negotiated via ALPN at the TLS terminator (§4). If TLS terminates at the CDN, the CDN must offer h2 — your app config is irrelevant to client-facing protocol. Verify with curl --http2 -I and check the access-log protocol field.

Idempotent retry storms. Signature: the LB retries a POST that timed out, and Pulsely submits the same claim twice — the payer sees a duplicate. Fix: retry only idempotent methods automatically; for POSTs, use idempotency keys so a retried request is recognized and de-duplicated server-side. Same reasoning as the 0-RTT replay hazard.

Caching authenticated responses. Signature: the CDN serves one patient's chart to another clinician — a PHI leak and a reportable breach, not a perf bug. Fix: never cache without an explicit policy. Authenticated pages need Cache-Control: private (or no-store), and any shared cache must key on the auth dimension via the cache key and Vary. Default to not-cacheable and opt in deliberately.

Health check too deep. Signature: a brief Postgres hiccup marks all instances unhealthy at once; the orchestrator restarts the whole fleet; a 5-second blip becomes a full outage. Fix: liveness checks the process only; readiness checks dependencies and gates traffic, not restarts. Never let a shared dependency flip liveness.

0-RTT replay. Signature: an attacker captures a 0-RTT early-data POST and replays it, duplicating a side effect. Fix: restrict 0-RTT to safe/idempotent methods; reject non-idempotent requests from early data.


7. Tradeoffs​

Senior engineering is naming the spectrum and saying why you stand where you stand.

Where to terminate TLS — the chapter's ADR. Three positions, sliding from convenience to assurance:

  • Terminate at the edge/LB. Central cert management, plaintext (fast) internally, full L7 routing and caching. The default for low-stakes apps.
  • Re-encrypt to upstream. Terminate at the edge for L7 and re-encrypt each internal hop for defense-in-depth. Higher CPU and latency; you choose it when regulated data crosses a shared or untrusted internal network, or zero-trust policy demands no plaintext anywhere.
  • Full passthrough. The edge does not decrypt — TLS rides end-to-end to the app, which terminates it (mTLS-ready). Maximum assurance, but you lose L7 routing and caching because no hop can read the HTTP.

For Pulsely the call is terminate at a reverse proxy at the edge and re-encrypt to upstream. You still want the edge to decrypt so you get L7 routing and caching for public reference data — but because every internal hop can carry PHI, running plaintext across the internal network is the wrong default here. This is where the healthcare threat model strengthens the argument rather than softening it: a chart in flight on an internal link is still a HIPAA exposure, and "it's behind the firewall" is not a control an auditor accepts. You'd relax toward plaintext-internal only on a genuinely isolated, attested network segment; you'd tighten all the way to full passthrough/mTLS the day a single service handles the most sensitive flows on a shared substrate and can afford to give up edge caching for them.

L4 vs L7 load balancing. L4 gives raw throughput and protocol-agnosticism but can't route smartly or terminate TLS for routing. L7 gives routing, retries, caching, and observability at CPU and latency cost. Reverse toward L4 only when you need extreme throughput or are balancing non-HTTP protocols; Pulsely's edge wants L7.

HTTP/1.1 vs 2 vs 3. 1.1 is universal, simple, and debuggable but connection-limited. 2 multiplexes but suffers TCP-layer HoL under loss. 3 is best on lossy/mobile networks but adds UDP operational complexity and younger tooling. The field's answer: h2 (or h3) to clients, h1.1 to upstreams — short fast internal hops on a reliable network gain little from multiplexing and cost debuggability.

Stickiness vs statelessness. Sticky sessions (consistent-hash a user to one instance) let you keep per-user state in instance memory — but they break clean rebalancing and amplify a dead instance's blast radius (everyone stuck to it loses their state). The senior preference: stateless app + external session store, sticky sessions only as a temporary crutch, never a foundation. (This is the statelessness thread cashing out again — Ch 29 owns it.)

Cache aggressiveness. Longer TTL means a better hit ratio and a cheaper origin, but more staleness and harder invalidation. stale-while-revalidate buys much of both — instant stale serve, background refresh. Reverse to short/no-cache for anything user-specific or fast-changing, like Pulsely's live vitals stream or a patient's claim status.

🚫 A framing this book rejects. "Just run Nginx on one box and you have an edge." It reintroduces the exact single-front-door SPOF this chapter set out to kill — one box terminating all TLS, balancing all load, with no redundancy is the problem in pain two, dressed up. A real edge is itself redundant (multiple terminators, the LB failed over, the CDN distributed). Self-managed proxies trade control for ops burden against managed cloud LB/CDN; that's a legitimate spectrum. "One Nginx box" is not a point on it — it's the failure mode.


8. Security & scale notes​

The edge adds threat surface, not just protection. TLS protects the pipe, but the edge introduces its own exposures: SNI leaks which hostnames a user visits (cleartext in the handshake); TLS downgrade/stripping attacks try to force a victim onto plain HTTP — mitigate with HSTS (a header telling browsers "only ever reach me over HTTPS"), HTTP→HTTPS redirects, and HSTS preload (baked into browsers so even the first visit is HTTPS); weak ciphers/protocols (disable TLS 1.0/1.1 and broken ciphers); and compression-based leaks — CRIME/BREACH exploit the fact that compressing a secret next to attacker-controlled data leaks the secret's length one guess at a time, which is why you're careful about what you compress alongside sensitive tokens.

🔑 mTLS preview. Mutual TLS adds the missing direction from the TLS guarantee invariant: the client also presents a certificate, so both sides are authenticated. It's the backbone of service-to-service auth inside a mesh and of high-assurance PHI APIs, with the LB/proxy as the enforcement point (it validates client certs so your app doesn't have to). You only need to recognize it here as "TLS, but both directions prove identity." The deep dive — issuing, rotating, and validating client certs — is deferred to Ch 32.

Trust-boundary discipline at the edge. Everything inside the boundary is implicitly trusted, which means a compromised internal hop — or a spoofed X-Forwarded-* header accepted from an untrusted source — is high-impact. Least-privilege the proxy, and pin exactly which hops you trust for forwarded headers. The boundary is only as strong as your discipline about what's allowed to cross it.

TLS handshake CPU is asymmetric — a DoS lever. The handshake costs the server far more than the client (the server does the expensive asymmetric crypto). An attacker can flood handshakes cheaply and burn your CPU — a handshake flood. A distinct HTTP/2-specific vector is Rapid Reset (CVE-2023-44487). Here's the mechanism, one step at a time. First, the rule it abuses: a server caps how many streams a connection may have open at once, to bound the work any single connection can create. Now the attack: the client opens a stream and instantly cancels it with an RST_STREAM frame, before the server has responded. Because a cancelled stream no longer counts against that cap, the attacker can open-and-cancel forever — a single connection churns through a near-unbounded flood of requests, each one forcing the server to start real work. The two levers are different — one burns crypto CPU, the other abuses multiplexing — and they need different defenses: connection and stream rate limits at the edge, handshake throttling, and crucially a cap on the rate of stream resets, not just the count of concurrent streams.

Saturation and the edge as the choke point. Follow the chain reasoning: the LB is both your scale lever and a concentration of risk — it's the choke point and the failover unit, which is why it's itself redundant in production. The CDN, meanwhile, absorbs spikes the app fleet couldn't — but it has its own failure mode:

🔑 Cache stampede (thundering herd). When a popular CDN object expires, every user requesting it simultaneously misses the cache and hammers the origin at once — a self-inflicted DDoS the instant a hot key goes stale (imagine every clinic hitting the same public formulary or code-set reference the moment it expires). Mitigate with request coalescing (the edge collapses concurrent misses for the same key into one origin fetch) and stale-while-revalidate (serve stale to everyone while one request refreshes). This is the HTTP-layer face of a general problem; the data-layer treatment lives in 📎 Ch 21.

Failure isolation is engineered, not hoped for. Health checks plus draining plus slow-start mean one bad instance or a botched deploy doesn't cascade. Anycast and CDN distribution give geographic failover — if one PoP or region dies, users route to the next. The edge is where you design for the independent-failure-per-hop invariant.


9. Interview lens & exercises​

Interview questions​

The same question separates levels by the quality of the narration.

"Walk me through what happens, byte by byte, from typing https://pulsely.health to the first rendered byte."

  • Junior answer: "DNS, then it connects, then HTTPS, then the page loads." A list that stops at "it loads."
  • Senior answer: the full chain as a reasoning tool — "DNS resolves the name (often cached); TCP handshake (1 RTT); TLS 1.3 handshake (1 RTT) carrying SNI to pick the cert and ALPN to negotiate h2; the request hits a CDN edge which checks its cache — a hit serves from the PoP with no origin trip, a miss forwards through the L7 LB to a reverse proxy that terminates TLS and re-encrypts to one of N stateless app instances; the response retraces the hops." Every hop annotated with cost and what it decides.

"Why does HTTP/2 not fully solve head-of-line blocking, and what does?"

  • Junior: "HTTP/2 fixed HoL with multiplexing."
  • Senior: "It fixed it at the HTTP layer via multiplexed streams, but reintroduced it at the TCP layer — because TCP delivers in order, one lost segment stalls all streams. QUIC/HTTP/3 fixes it because QUIC owns ordering per stream over UDP, so a lost packet stalls only its own stream." Names the layer, not just the version.

"Where would you terminate TLS for Pulsely and why?"

  • Junior: "at the load balancer."
  • Senior: weighs edge-terminate vs re-encrypt-to-upstream vs full passthrough against the threat model, internal-network trust, and the need for L7 routing/caching — concluding edge-terminate with re-encryption to upstream for Pulsely, because PHI travels on the internal links and "behind the firewall" isn't a HIPAA control, and naming the conditions (an isolated attested segment, or a single service needing full mTLS passthrough) that would move the call either way. That's the chapter's ADR reasoned aloud.

"Your LB retried a request and a claim got submitted twice — what happened and how do you prevent it?"

  • Junior: blames the app code.
  • Senior: "the LB retried a non-idempotent POST after an ambiguous timeout. Auto-retry only idempotent methods; make POSTs safely retryable with idempotency keys so a duplicate is recognized server-side." Invokes the idempotency-retry invariant.

"How do you safely cache an authenticated page on a CDN?"

  • Junior: "just don't cache it."
  • Senior: "if you cache it at all, the cache key and Vary must include the auth dimension so users never share an entry; Cache-Control: private/no-store keeps it out of shared caches; s-maxage vs max-age separates CDN from browser. The failure mode is serving one patient's chart to another clinician — a reportable breach, not slowness." Reasons about the cache-correctness invariant.

Exercises & the Pulsely increment​

  1. Pulsely increment — stand up the edge. Put Pulsely behind an Nginx (or Envoy) TLS-terminating reverse proxy fronted by a load balancer. Use a real cert path (Let's Encrypt in prod, a self-signed local CA for dev), an HTTP→HTTPS redirect, HTTP/2 to clients and HTTP/1.1 (re-encrypted) to upstreams, two app instances behind L7 round-robin with active /healthz checks, and X-Forwarded-* plumbed through with trust proxy set to the proxy only. Confirm a deploy of one instance doesn't drop traffic (draining works).

  2. Handshake archaeology. Capture a TLS 1.3 handshake with openssl s_client (or Wireshark). Identify the ClientHello's cipher list, the ALPN offer, the SNI value, and the cert chain the server returns. Then force TLS 1.2 and count the extra round trip — see the §4 difference with your own eyes.

  3. Head-of-line-blocking demo. Use tc/netem to add ~2% packet loss. Load a patient's document-heavy chart timeline three ways and compare load time: HTTP/1.1 (capped at six connections), HTTP/2 (multiplexed — watch all streams stall together on a single lost segment), and HTTP/3 if available (only the affected stream stalls). You'll feel the invariant from §3.

  4. Cache + safety drill. Put a CDN/Varnish layer in front. Cache public reference pages (a formulary or code-set lookup) aggressively. Then prove an authenticated /patients/:id/chart page is never shared across users by crafting the cache key plus Cache-Control: private — and finally break it on purpose (drop the private, key without the auth cookie) and observe the leak: one clinician's session pulling back another patient's chart. If you can make that leak happen and then close it deliberately, you understand the cache-correctness invariant cold — and you've felt why it's a breach, not a bug.


Key takeaways​

  • The edge varies along three orthogonal axes — encryption (TLS), framing (HTTP version), topology (proxy/LB/CDN). Most edge confusion is conflating them; debug each separately.
  • TLS gives three guarantees — confidentiality, integrity, authentication (server-only by default) — and separates key agreement (ECDHE, forward secrecy) from identity proof (the cert chain to a trusted root). TLS 1.3 is 1-RTT; 0-RTT resumption is replayable, so safe-methods-only.
  • HTTP semantics are version-invariant; only framing and multiplexing change. HoL blocking is request-layer in 1.1, TCP-layer in 2, and solved per-stream by QUIC in 3. HTTP/2 is negotiated via ALPN inside the TLS handshake.
  • A request is a chain of independent hops, each terminating and re-originating a connection. "Termination" is the one verb behind TLS termination, L7 routing, and caching alike.
  • L4 balances by 5-tuple (fast, opaque); L7 understands HTTP (routing, retries, caching, TLS termination) at CPU cost. Retries must respect idempotency; POSTs need idempotency keys.
  • Liveness shallow, readiness deep — never let a shared dependency flip liveness or one blip restarts the fleet. Trust X-Forwarded-* only from known proxies.
  • Cache correctness = cache key + freshness + Vary; violating the key leaks PHI (a reportable breach), violating freshness serves staleness. HTTP/CDN caching here; general caching theory is 📎 Ch 21.
  • This chapter completes Part I's spine from the user's thumb to your handler's door. Part II walks inside that door.

← Previous: Ch 5 — Networking I · Up: Part I overview · Master TOC · Next: Ch 7 — The Node Event Loop, libuv & the Async Model →