Load balancing
medium 25 minA load balancer gives many servers one address, sends each request to a healthy one and hides failures and upgrades.
See it run
Watch four algorithms choose a server, then health checks and draining keep requests away from the wrong one.
Operations
Round robin
Servers take turns. Nothing else is considered.
Step 1 of 5
Request 1
Turn 1: A
The first request goes to server A.
Step 1: Request 1
def round_robin(): pool = healthy(servers) server = pool[turn % len(pool)] turn += 1 return server- Looks at
- The turn
- Keeps
- A counter
- Least connections
- looks at open work
Equal turns are not equal work.
In the real world
The same introduction to load balancing doing real jobs. Pick one and step through it.
Least connections, and a server that returns errors in 2 ms.
Step 1 of 4
Normal
Even
Three servers share the load.
Step 1: Normal
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Only one balancer
criticalTen servers behind one balancer still go down together.
Wrongclients -> balancer -> 10 serversRightclients -> balancer 1 or 2 -> 10 serversA health check that queries the database
criticalA slow database then makes every server look dead.
Wrongdef health(): db.query("SELECT COUNT(*) ...")Rightdef health(): return 200 # this process can serveCounting an ended request twice
majorDecrementing on error and again on close makes the count negative, and the server a magnet.
Wrongon_error: open -= 1on_close: open -= 1Righton_close: open -= 1 # always, onceStopping a server without draining
majorUploads, calls and sockets are cut in the middle.
Wrongstop(server)Rightdrain(server)stop(server)
Interview tips
How to explain it
- One address in front, many servers behind.
- Choose, forward, watch health.
- Two balancers, never one.
Memory trick: LRWI
- Least connections, Round robin.
- Weighted, IP hash.
- Load Routing With Intelligence.
Choose by
- Similar requests: round robin.
- Unequal servers: weights.
- Unequal work: least connections.
Watch out for
- Fast-failing servers.
- Shared addresses with IP hash.
- No room to lose one server.