Module 2 · Backend architectureLesson 14 of 887 minBeginner
Load balancers
A load balancer spreads requests across many servers so no single one gets overwhelmed, and routes around servers that fail.
One server is slow. Watch round robin keep feeding it, then switch to "Least busy". Then crash a server with health checks off, and again with them on.
Once you have more than one server, something has to decide which server gets each request. That's the load balancer.
Common algorithms
- Round robin: 1, 2, 3, 1, 2, 3... Simple and fair when servers are identical.
- Least connections (least busy): pick the server with the fewest requests in progress. Adapts when some requests or servers are slower.
- Random: surprisingly decent at large scale. "Pick two at random, use the less busy" is even better.
- Hash-based: the same user (or key) always goes to the same server. Useful when a server keeps something in memory for that user.
Health checks
A load balancer pings each server every few seconds: GET /health. If a server fails a couple of checks in a row, it's taken out of rotation. When it recovers, it's put back.
Without health checks, the balancer keeps sending requests to a crashed server, and users see errors. Try it in the demo.
Layer 4 vs layer 7
- Layer 4 balancers look only at IP addresses and ports. Very fast, can't read URLs.
- Layer 7 balancers read HTTP. They can route by path or header, retry failed requests, and keep users on one server with cookies.
Don't create a new weak point
If all traffic goes through one load balancer, that box is now a single point of failure. Real setups run at least two, sharing one address (failover), or use the cloud provider's managed balancer, which is redundant behind the scenes.
Sticky sessions: avoid if you can
"Stickiness" pins a user to one server, usually because their session is stored in that server's memory. It makes balancing uneven and breaks when that server dies. Better: keep servers stateless and store sessions in a shared cache or database.