Balancing Algorithms
Who gets the next request.
A load balancer has to pick a server for every single request. There are a few simple rules it can follow, and each one suits different traffic.

- A choice for every request
- A few simple rules
- Each suits different traffic
Round robin vs least connections
Round robin just takes turns, one, two, three, one, two, three. Least connections picks the server with the fewest requests in progress. Here, server A is stuck with slow requests. Run it. Round robin keeps sending A its share, even though it's busy. Least connections notices, and sends new work to B and C instead.
from itertools import cycle
servers = ["A", "B", "C"]
active = {"A": 5, "B": 1, "C": 0} # requests in progress
rr = cycle(servers)
print("round robin:", [next(rr) for _ in range(6)])
picks = []
for _ in range(6):
s = min(active, key=active.get)
active[s] += 1
picks.append(s)
print("least conn: ", picks)round robin: ['A', 'B', 'C', 'A', 'B', 'C'] least conn: ['C', 'B', 'C', 'B', 'C', 'B']
Common algorithms
Here are the common choices. Round robin is simple, and works when requests are similar. Weighted round robin sends more to bigger servers. Least connections handles requests of different lengths. And hashing the user's IP sends the same user to the same server, which helps with caching.
| Algorithm | Good when |
|---|---|
| Round robin | requests are similar |
| Weighted | servers differ in size |
| Least connections | request times vary |
| IP hash | same user, same server |
Summary
Round robin takes turns, least connections avoids busy servers, and hashing keeps a user on one server. Next, two levels a balancer can work at.
Key takeaways- Round robin
- Least connections
- Hash for stickiness