Sub topic 4
Choosing a balancing algorithm
This chapter assumes you know how HTTP requests and TCP connections work, and that you can read a configuration file. It also assumes you know what a load balancer does: it receives client traffic and forwards each request or connection to one server in a pool. The balancing algorithm is the rule that picks that server.
The working model
For every new request (Layer 7) or connection (Layer 4), the load balancer builds a list of healthy backends and applies its algorithm to choose one. Most algorithms use one of three inputs:
- A position in a fixed order (round robin).
- A live measurement such as the number of active connections (least connections).
- A key taken from the request, such as the client IP address (hash-based).
The right choice depends on how uniform your requests are and how uniform your servers are.
Round robin
Round robin sends requests to servers in a repeating order: a, b, c, a, b, and so on. It needs no state about the servers, so it is cheap and predictable. It works well when requests cost about the same and the servers have equal capacity.
It fails when requests vary a lot. A server that receives several slow requests in a row keeps receiving new ones on schedule, because round robin never looks at load.
Weighted variants
A weight tells the balancer that one server should receive a larger share. A server with weight 3 gets three requests for every one sent to a server with weight 1. Use weights when servers differ in size, or to send a small share of traffic to a new version during a gradual rollout.
Weights are static. If you set them by hand, you must update them when the hardware changes.
Least connections
Least connections chooses the server with the fewest active connections. It adapts to uneven request cost: a server stuck on slow requests holds more open connections, so it receives fewer new ones. It suits long-lived connections such as WebSockets, file uploads, and database proxies.
The two ideas combine. Weighted least connections divides each server's connection count by its weight before comparing.
The following Python snippet shows the difference between the two simplest rules.
import itertools
servers = ["a", "b", "c"]
round_robin = itertools.cycle(servers)
def pick_round_robin():
return next(round_robin)
def pick_least_connections(active):
return min(active, key=active.get)
print([pick_round_robin() for _ in range(5)])
print(pick_least_connections({"a": 2, "b": 0, "c": 5}))The first line prints ['a', 'b', 'c', 'a', 'b']. The second prints b, because server b has no active connections.
Hash-based balancing
A hash-based algorithm computes a hash of a key, such as the client IP address, and maps the result to a server. The same key always reaches the same server while the pool stays the same. This gives a form of stickiness without cookies, and it improves cache hit rates when each server caches the data for its own keys. The weakness is that adding or removing a server changes the mapping for many keys. A later chapter covers consistent hashing, which limits that disruption.
Comparing the options
| Algorithm | Decides using | Good fit | Main weakness |
|---|---|---|---|
| Round robin | Fixed order | Uniform requests, equal servers | Ignores load |
| Weighted | Configured weights | Unequal servers, gradual rollouts | Weights are manual |
| Least connections | Live connection counts | Long or uneven requests | Needs connection tracking |
| Hash | Request key | Caching, simple stickiness | Remapping when the pool changes |
Configuring an algorithm in NGINX
The upstream block selects the algorithm. This example uses least connections, gives the first server a higher weight, and keeps a backup server.
upstream app {
least_conn;
server 10.0.0.11:8080 weight=3 max_fails=3 fail_timeout=30s;
server 10.0.0.12:8080 max_fails=3 fail_timeout=30s;
server 10.0.0.13:8080 backup;
}
server {
listen 80;
location / {
proxy_pass http://app;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}The max_fails and fail_timeout settings mark a server as failed after three failed attempts. That is passive health checking, covered in the next chapter. The backup server receives traffic only when the others are unavailable.
In HAProxy, the same choice is the balance line in a backend, for example balance roundrobin or balance leastconn.
Common errors
- Using round robin for requests with very different costs, then wondering why one server runs hot.
- Using least connections for very short requests. The counts change so quickly that they add little over round robin.
- Hashing on the client IP when many users sit behind one proxy or NAT. They all map to one server.
- Forgetting that weights are relative. Weights of 3 and 1 and weights of 30 and 10 behave the same.
Exercise
Your pool serves file uploads that take between one second and ten minutes. Which algorithm fits better, round robin or least connections, and why?
Show answer
Least connections. Upload duration varies widely, so connection counts show which servers are busy. Round robin would keep assigning new uploads to a server that already holds several long ones.