The front door, layer by layer
L4 vs L7
| Layer 4 (transport) | Layer 7 (application) | |
|---|---|---|
| Sees | IPs, ports, TCP/UDP | HTTP: paths, headers, cookies, bodies |
| Can route by | Connection | URL path, host, header, user, version |
| Speed | Very fast, cheap | More CPU per request |
| TLS | Usually passes through | Terminates (decrypts) |
| Examples | AWS NLB, IPVS, Maglev | Nginx, Envoy, HAProxy, AWS ALB |
Balancing algorithms
| Algorithm | How | Best for |
|---|---|---|
| Round robin | Next server in turn | Identical servers, similar requests |
| Weighted round robin | Bigger servers get more | Mixed hardware, canaries (5% weight) |
| Least connections | Fewest open connections | Long or variable requests, WebSockets |
| Least response time / EWMA | Fastest recent latency | Mixed latency backends |
| Power of two choices | Pick 2 random, choose less loaded | Huge fleets; near-optimal with little state |
| Consistent hash | Hash(key) → server | Cache affinity, sticky routing (Sharding and Consistent Hashing Explained) |
Tip
Power of two random choices is a lovely interview detail. Picking the better of just two random servers avoids the herd effect of everyone choosing the single "least loaded" server, while getting most of the benefit.
Health checks, draining and stickiness
- Health checks: the LB pings
/healthzevery few seconds. Liveness ("process is up") differs from readiness ("can serve traffic now: DB reachable, caches warm"). Route only to ready instances. - Connection draining: before removing an instance (deploy, scale-in), stop sending new requests and let in-flight ones finish within a timeout.
- Sticky sessions: pin a user to one server via a cookie. Useful for legacy stateful apps, but it ruins even balancing and makes failures lose sessions. Prefer stateless servers with shared session storage.
Common trap
A health check that calls the database. If the DB has a hiccup, every instance reports unhealthy and the LB removes the whole fleet — turning a small blip into a total outage. Keep liveness checks shallow and readiness checks tolerant.