Backend Case Studies

Topic B8

Load balancers

Spreading requests over several servers: round robin, least connections and health checks.

9 min · intermediate

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.

0 active0 active0 activeS1S2S3load balancer
  • moving now
  • being checked
  • passed / marked
Step 1 of 11

Round robin: send requests to S1, S2, S3, S1, S2, … in turn, without looking at how busy each server is. The number on a block = seconds of work left.

Requests aren't equally heavy. Splitting evenly by count doesn't mean splitting evenly by work.

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

  1. When does round robin work badly?

  2. Users suddenly get logged out on the next request after adding a load balancer. Most likely cause?

  3. What does a health check do?

0 of 3 answered.