Topic B8
Load balancers
Spreading requests over several servers: round robin, least connections and health checks.
Watch: heavy work piles up on one server if it's just shared in turn. Sending it to the least busy server evens things out.
- moving now
- being checked
- passed / marked
Like supermarket checkouts
A staff member at the front directs shoppers to tills. If they just take turns (till 1, 2, 3, 1, 2, 3), shoppers with full trolleys can keep landing on the same till, and its queue snakes back while others sit empty. A smarter director looks at which queue is shortest. That's the difference between round robin and least connections.
Common choosing rules
- Round robin: take turns. Simple, good when every request is roughly equally heavy.
- Least connections: to the server with the fewest active requests. Better when request weight varies (uploads, reports, websockets).
- Weighted: bigger servers get a bigger share.
- Hash (sticky): a hash of the user id or IP always goes to the same server. Useful when servers keep per-user state, but the split can be lopsided. The next topic covers a better version.
- Power of two choices: pick two servers at random, send to the less busy one. Nearly as good as least connections without knowing every server's load; Envoy and NGINX use it.
Code, for programmersNGINX configuration
upstream api {
least_conn; # default is round robin
server 10.0.0.11:3000;
server 10.0.0.12:3000;
server 10.0.0.13:3000 weight=2; # a bigger machine
}
server {
listen 80;
location / { proxy_pass http://api; }
}Health checks
The load balancer calls an endpoint like /healthz every few seconds. A server that fails to answer is taken out of rotation until it recovers. Make sure the health check tests the right thing: a server that's up but can't reach its database shouldn't get traffic. But don't let one slow minor dependency mark every server dead at once.
Quiz
When does round robin work badly?
Users suddenly get logged out on the next request after adding a load balancer. Most likely cause?
What does a health check do?
0 of 3 answered.
Built on
Used in
No follow-up topics yet.