Load balancing and CDNs
Spread traffic, survive failures and bring content close to users.
A load balancer sits in front of several servers and distributes requests among them. It also removes servers that fail their health checks, so users do not notice a failure.
| Layer | Looks at | Good for |
|---|---|---|
| L4 (TCP/UDP) | Addresses and ports only. Very fast | Databases, TLS passthrough, non-HTTP protocols |
| L7 (HTTP) | Hostnames, paths, headers and cookies | Routing /api and /static differently, TLS termination, caching, rate limiting |
- Algorithms: round robin, least connections, hash of the client address (for stickiness).
- Health checks: the balancer calls an endpoint and stops sending traffic to a server that fails.
- Session affinity ("sticky sessions") sends a user to the same server. It is simple but makes scaling and failures harder. Prefer stateless servers with shared sessions.
- TLS termination: the balancer decrypts HTTPS and speaks plain HTTP (or re-encrypts) to the backends.
CDN
A content delivery network has servers in many cities. Users are routed to the nearest one (by DNS or anycast), which serves cached copies of your files. It reduces latency, cuts the load on your origin and absorbs traffic spikes and some attacks.
Cache-Control: public, max-age=31536000, immutable # static files with hashed names
Cache-Control: no-store # private or sensitive responsesCarefulNever let a CDN cache a response that contains personal data. Mark private pages Cache-Control: private or no-store, and be careful with caching rules based on the URL only.
NoteA balancer is itself a single point of failure unless it is redundant. Cloud balancers handle that for you. DNS TTL also matters: a short TTL makes failover faster.
Test yourself
Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.