Load balancers, proxies & CDNs
Between a browser and your app there are usually several middlemen: a CDN edge, a cloud load balancer, a reverse proxy. The Security & infrastructure chapter introduced them in a paragraph; here you'll see how each works, configure Nginx as a load balancer, and learn how caching headers decide what a CDN keeps.
Forward vs reverse proxy
- A forward proxy works for clients: outgoing traffic from a company network goes through it, and websites see the proxy's IP. Used for filtering and controlling outbound access; tools that read
HTTPS_PROXYuse one. - A reverse proxy works for servers: it sits in front of your apps, and clients never see the backends. Nginx, HAProxy, Traefik, Caddy and Envoy are common ones.
The reverse proxy handles jobs you don't want in every app: TLS termination, routing by hostname or path, compression, caching, rate limiting. Since the app now sees the proxy as the client, the proxy passes the original details in headers: X-Forwarded-For (client IP plus each proxy on the way), X-Forwarded-Proto (http or https) and often X-Real-IP.
Layer 4 vs layer 7
| Layer 4 | Layer 7 | |
|---|---|---|
| Sees | IPs and ports of TCP/UDP connections | The HTTP request: host, path, headers, cookies |
| TLS | Usually passes encrypted bytes through | Terminates TLS to read the request |
| Good for | Any protocol (databases, raw TCP), huge throughput | Websites and APIs, path routing, retries, headers |
| Examples | AWS NLB, HAProxy TCP mode, Nginx stream | AWS ALB, Nginx http, Kubernetes Ingress |
Algorithms, health checks, sticky sessions
- Round robin (the usual default): 1, 2, 3, 1, 2, 3… Fair when requests cost about the same. Weighted:
weight=3gets three times the share. - Least connections: next request to the server with the fewest active connections. Better when some requests are slow.
- IP hash / consistent hashing: the same client (or key) always lands on the same server.
Active health checks call an endpoint like /healthz every few seconds and remove a server after several failures in a row; passive checks watch real traffic for errors. AWS ALB, HAProxy and Kubernetes probes do active checks; open-source Nginx does passive only (active checks are an NGINX Plus feature). A good health endpoint returns 200 only when the app can really serve, e.g. it can reach its database.
Sticky sessions pin each user to one backend (by cookie or IP hash), a workaround for apps that keep sessions in memory. The cost: uneven load, and users are logged out when their server dies. The real fix is a stateless app with sessions in Redis or a database.
Nginx as a load balancer
# /etc/nginx/conf.d/app.conf
upstream app_backend {
least_conn; # default would be round robin
server 10.0.2.11:3000 max_fails=3 fail_timeout=30s;
server 10.0.2.12:3000 max_fails=3 fail_timeout=30s;
server 10.0.2.13:3000 backup; # only used if the others are down
}
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://app_backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_next_upstream error timeout http_502 http_503; # retry on another server
}
}
max_fails=3 fail_timeout=30s is the passive check: 3 failures within 30 seconds and that server is skipped for 30 seconds. ip_hash; instead of least_conn; gives IP stickiness, but can't be combined with backup.
$ sudo nginx -t # syntax check first
$ sudo systemctl reload nginx # apply without dropping connections
CDNs and Cache-Control
A CDN is a worldwide network of reverse proxies (edge servers). Users hit the nearest one; on a hit it answers from cache, on a miss it fetches from your origin and keeps a copy. Faster pages far away, less load on the origin, and a big front door that absorbs DDoS attacks. The origin controls caching with Cache-Control:
| Header value | Meaning / use |
|---|---|
public, max-age=31536000, immutable | Cache for a year, never changes. For fingerprinted files like app.3f9a1c.js. |
public, max-age=60, s-maxage=600 | Browsers 1 minute, shared caches (CDNs) 10 minutes. |
no-cache | May be stored, but must be revalidated before each use. HTML that must be current. |
no-store | Never store anywhere. Sensitive pages. |
private | Browser only, never a CDN. Logged-in, personalised pages. |
Despite the name, no-cache doesn't mean "don't cache"; no-store does. Revalidation uses ETag: the server answers 304 Not Modified with no body if nothing changed. Age shows how long a response has sat in a cache.
Cloudflare as an example
Mark a DNS record proxied (orange cloud) and DNS returns Cloudflare's IPs, so every request passes their edge: TLS terminated, cache and firewall rules applied, then forwarded to your origin. By default it caches static files by extension, but not HTML unless you add a Cache Rule. Purge the cache after a deploy if needed.
$ curl -sI https://example.com/logo.png | grep -iE 'server|cf-cache-status|cache-control|age'
server: cloudflare
cf-cache-status: HIT # or MISS, EXPIRED, BYPASS, DYNAMIC (not cacheable)
cache-control: public, max-age=14400
age: 812
The SSL/TLS mode sets how Cloudflare reaches your origin: Flexible uses plain HTTP (the second half of the trip is unencrypted), Full uses HTTPS with any certificate, Full (strict) requires a valid one. Aim for Full (strict).
How one request travels
Browser ── DNS: example.com → Cloudflare edge IP
▼
CDN edge TLS #1 ends here; cache HIT answers immediately
▼ (miss) adds CF-Connecting-IP / X-Forwarded-For
Load balancer TLS #2 ends here; picks a healthy target
▼
Reverse proxy routes /api to the API, / to the frontend
▼
App reads the real client IP from forwarded headers
Errors and what they point to
- 502 Bad Gateway: the proxy got no valid response from the backend: app down, crashed, wrong port, or listening only on
127.0.0.1. Nginx's error log will show "connect() failed (111: Connection refused)". - 504 Gateway Timeout: the backend answered too slowly. Find the slow query, or raise
proxy_read_timeoutif it's expected. - AWS targets "unhealthy": the health check isn't getting a 200: wrong path, a redirect, or a security group blocking the load balancer.
- Cloudflare 521 origin refused the connection, 522 timed out (often a firewall), 525 TLS handshake with origin failed, 526 invalid origin certificate in Full (strict).
- ERR_TOO_MANY_REDIRECTS behind Cloudflare: Flexible mode sends HTTP, the origin redirects to HTTPS, repeat forever. Use Full (strict).
- Every log line shows the same client IP: the app sees the proxy. Use
X-Forwarded-For, trusting it only from your own proxies. - Old version still showing after a deploy: a stale cache. Purge the CDN, and use fingerprinted file names.