Sub topic 16
Proxies, Load Balancers, and CDNs
This chapter assumes you can read HTTP requests and responses, know what common headers do, and understand the basics of caching (Cache-Control, ETag, conditional requests) and HTTPS/TLS. It covers the servers that often sit between a browser and the application that answers it.
Why requests rarely go straight to the app
In the earlier chapters, a browser talked to "the server". In production, that is rarely one machine running your code. A request usually passes through one or more intermediaries. Each one receives an HTTP request, then forwards it, answers it, or rejects it.
Intermediaries exist for a few reasons:
- Scale: one machine cannot handle all the traffic, so work is spread over many machines.
- Speed: content can be served from a location close to the user.
- Safety: the application can be hidden from direct internet access.
- Operations: TLS, compression, logging, and rate limiting can be handled in one place.
Forward proxies and reverse proxies
A proxy is a server that forwards HTTP traffic on behalf of someone else. The direction matters.
- A forward proxy acts for the client. A company network might require all employee traffic to go through one, to filter sites or log usage. The destination server sees the proxy's address, not the employee's.
- A reverse proxy acts for the server. Clients think they are talking to the real site. The reverse proxy decides which backend handles the request. Nginx, HAProxy, Envoy, and Caddy are commonly used this way.
| Property | Forward proxy | Reverse proxy |
|---|---|---|
| Configured by | The client or its network | The site operator |
| Hides | The client's identity | The backend servers |
| Typical use | Filtering, corporate access control | Load balancing, TLS, caching |
| Client aware of it? | Usually yes | Usually no |
Load balancers and CDNs are both specialized reverse proxies. The rest of the chapter covers them.
Load balancers
A load balancer distributes incoming requests across several backend servers. If one backend fails, it stops sending traffic there. This gives you more capacity and better availability.
Layer 4 and layer 7
- A layer 4 balancer works at the TCP level. It picks a backend per connection and does not read HTTP. It is fast and simple, but it cannot route by path or header.
- A layer 7 balancer parses HTTP. It can send
/api/to one group of servers and/static/to another, add headers, or retry a failed request.
Choosing a backend
Common algorithms:
- Round robin: take backends in turn. Simple, and fine when requests cost about the same.
- Least connections: send to the backend with the fewest active connections. Better when request times vary.
- Hash-based: hash the client IP or a header so the same client tends to reach the same backend.
Health checks
The balancer periodically requests a URL such as /healthz from each backend. A backend that returns errors or times out is removed from rotation until it passes again. Keep the health endpoint cheap. If it queries a slow database, a database hiccup can make every backend look unhealthy at once, and the balancer then has nowhere to send traffic.
Sessions and sticky routing
Chapter material on cookies showed that a session ID points to state stored on the server. If that state lives in one backend's memory, a request sent to a different backend will not find it, and the user appears logged out.
There are two fixes:
- Sticky sessions: the balancer pins a client to one backend, often with a cookie. This is easy, but uneven load results, and the user loses the session if that backend dies.
- Shared session storage: backends keep sessions in a shared store such as Redis, or use signed tokens. Any backend can then handle any request. This is the more robust design.
TLS termination
Many deployments terminate TLS at the proxy. The browser's encrypted connection ends at the load balancer or CDN, which holds the certificate. It then forwards the request to the backend over a private network, sometimes as plain HTTP.
Benefits are centralized certificate management and less CPU work on the backends. The cost is that traffic between proxy and backend is only as safe as that network. For sensitive systems, re-encrypt to the backend with a second TLS connection.
What the backend loses, and how headers restore it
When a proxy forwards a request, the backend sees a connection from the proxy. The client's IP address and the original scheme (https) are lost unless the proxy passes them on. The convention is to add headers:
X-Forwarded-For: the client IP, with each proxy appending the address it received the request from.X-Forwarded-Proto: the original scheme,httporhttps.X-Forwarded-Host: the originalHostvalue.Forwarded: the standardized form that carries the same information.
Here is a small Node.js server that reports what it sees. It reads the headers a proxy would add.
import { createServer } from "node:http";
const server = createServer((req, res) => {
const forwardedFor = req.headers["x-forwarded-for"] ?? "(none)";
const proto = req.headers["x-forwarded-proto"] ?? "(none)";
res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8" });
res.end(
`Socket peer: ${req.socket.remoteAddress}\n` +
`X-Forwarded-For: ${forwardedFor}\n` +
`X-Forwarded-Proto: ${proto}\n`
);
});
server.listen(3000);You can simulate a proxy with curl by sending the headers yourself:
curl -H "X-Forwarded-For: 203.0.113.9" -H "X-Forwarded-Proto: https" http://localhost:3000/CDNs
A content delivery network (CDN) is a global group of reverse proxy servers, called edge servers or points of presence. Your origin is the server that holds the real content. A user's request is routed to a nearby edge, usually through DNS or anycast routing. The edge answers from its cache if it can. Otherwise it fetches from the origin, stores the response, and returns it.
Benefits:
- Lower latency: the round trips are to a nearby machine.
- Lower origin load: a cache hit never reaches your servers.
- Absorbing spikes: traffic surges and some attacks are spread across the edge network.
How the CDN decides what to cache
A CDN uses the caching headers you learned earlier, with a few additions:
Cache-Control: max-age=Napplies to any cache.s-maxage=Napplies only to shared caches such as CDNs and overridesmax-agethere.privateforbids shared caches from storing the response. Use it for per-user content.no-storeforbids storing it anywhere.Varylists request headers that change the response.Vary: Accept-Encodingtells the cache to keep separate copies for gzip and Brotli.Vary: Cookieeffectively fragments the cache per user, so avoid it on content you want shared.- The
Ageheader reports how many seconds a response has sat in a cache.
A typical response for a fingerprinted asset:
HTTP/1.1 200 OK
Content-Type: text/css
Cache-Control: public, max-age=31536000, immutable
Vary: Accept-Encoding
Age: 120Because the filename contains a content hash (for example app.3f9c2a.css), you can cache it for a year and change the name when the content changes.
Invalidation
Cached content can become stale before it expires. Options are:
- Purge a URL or tag through the CDN's API.
- Versioned URLs, as above, so old entries are simply never requested again.
- Short TTLs for content that changes often, with
stale-while-revalidateto serve the old copy while a refresh happens in the background.
Purges are not always instant across all edges, and versioned URLs avoid the problem entirely.
Common errors
| Symptom | Likely cause |
|---|---|
| Users randomly logged out | Sessions stored in one backend's memory behind a load balancer |
| Logs show the proxy's IP for every client | Backend reads the socket address, not the forwarded header |
| Redirect loop to HTTPS | Backend sees plain HTTP from the proxy and keeps redirecting, because it ignores `X-Forwarded-Proto` |
| One user sees another user's page | A personalized response was cached by a shared cache without `private` or a suitable `Vary` |
| `502 Bad Gateway` | The proxy got an invalid response or no response from the backend |
| `504 Gateway Timeout` | The backend took longer than the proxy's timeout |
| Old content after a deploy | Stale CDN entry, with no purge or versioned filename |
Exercise
A site runs three app servers behind a layer 7 load balancer with round robin routing. Users report being logged out every few clicks. Sessions are stored in each server's memory. Give two fixes and one downside of each.
Show answer
Fix 1: enable sticky sessions so the balancer sends each client to the same backend. Downside: load can become uneven, and users lose their session if their backend fails. Fix 2: move sessions to a shared store such as Redis, or use signed tokens, so any backend can serve any request. Downside: it adds a dependency that must be run and kept available, plus a small network delay on each session lookup.
Exercise
A CDN is caching an account page, and a user sees another person's name. Which header changes would prevent this, and why?
Show answer
Add Cache-Control: private (or no-store) to the personalized response so shared caches do not store it. If the response must be cached and varies by a request header, list that header in Vary. Without these, the CDN treats the response as shareable and serves the first user's copy to later users of the same URL.