Sub topic 4
Choosing a balancing algorithm
A balancing algorithm is the rule a load balancer uses to pick a backend for each new connection or request. This chapter assumes you know how HTTP and TCP connections work, what a backend pool is, and how to edit a configuration file. It also assumes you have read the earlier chapters on what a load balancer does and on Layer 4 versus Layer 7.
The algorithm decides how evenly work is spread, how well the pool copes with uneven servers, and whether the same client tends to reach the same server. No algorithm is best everywhere. You choose by looking at your traffic and your servers.
What the algorithm actually sees
Before comparing algorithms, note what information each one has:
- Static information: the list of servers and their configured weights.
- Dynamic information: how many connections or requests each server is handling now, and sometimes how fast it has responded.
- Request information: the client IP address, a header, a cookie, or the URL. Only a Layer 7 balancer can read headers, cookies and URLs. A Layer 4 balancer sees addresses and ports.
Simple algorithms use only static information. They are cheap and predictable. Smarter algorithms use dynamic information and adapt to load, but they depend on the balancer's counts being accurate.
Round robin
Round robin sends each new request to the next server in the list, then wraps around at the end. With servers a, b and c, the order is a, b, c, a, b, c.
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}))Running this prints ['a', 'b', 'c', 'a', 'b'] and then b. The first line shows the cycle. The second shows least connections choosing the idle server.
Round robin works well when:
- Requests cost about the same amount of work.
- Servers have the same capacity.
- Connections are short.
It fails quietly when those assumptions break. If one request in twenty takes ten seconds and the rest take ten milliseconds, round robin can still hand several slow requests to the same server by chance. That server queues work while others sit idle. Round robin never looks at load, so it cannot notice.
Weighted round robin
Weighted round robin gives each server a weight, which is a number proportional to its share of traffic. A server with weight 3 receives about three requests for every one that a weight 1 server receives.
Use weights when:
- Servers differ in size, such as a mix of 4-core and 16-core machines.
- You want to send a small share of traffic to a new version (a rough canary release).
- You are slowly warming up a server that has just been added.
Weights are static. You set them by hand, so they reflect your guess about capacity and not the real load. If a heavy server slows down because of a noisy neighbour on shared hardware, its weight stays the same.
Implementations differ in how they interleave picks. A naive version sends three requests to the heavy server in a row, then one to the light server. This creates bursts. NGINX uses a smooth weighted round robin that spreads the heavy server's turns through the cycle, so a weight of 3 against 1 gives a pattern like heavy, heavy, light, heavy and not three in a row.
Least connections
Least connections sends each new request to the server with the fewest active connections. The balancer keeps a counter per server. It adds one when a connection opens and subtracts one when it closes.
This adapts to uneven work. A server stuck on slow requests holds its connections open, its counter stays high, and new requests go elsewhere. Least connections is a good default when:
- Request durations vary a lot.
- Connections are long-lived, such as WebSockets, file uploads or database sessions.
- Servers are the same size but get uneven work.
There are limits you should know about:
- The counter counts connections, not work. One connection that streams a large file counts the same as one idle keep-alive connection.
- With HTTP keep-alive or HTTP/2, a client may reuse one connection for many requests. A Layer 4 balancer counts the connection once, so it cannot see that this connection is busy.
- A freshly added server starts at zero and receives every new connection until its count catches up. A cold server with an empty cache can be overloaded by this rush. Slow-start settings exist for this reason.
- If you run several balancer instances, each one counts only its own connections. Together they may not agree on which server is least loaded.
Weighted least connections divides each server's connection count by its weight before comparing. A weight 3 server with 6 connections ranks equal to a weight 1 server with 2 connections.
Least response time
Some balancers also measure how long servers take to answer. HAProxy and commercial products can combine the connection count with the average response time and prefer the fastest server. This reacts to slowness that connection counts miss, such as a server with a slow disk. It needs a Layer 7 view or timing data, and a short burst of slow replies can cause the balancer to shift traffic in swings. Treat it as a tuning option for mature setups, not a starting point.
Hash-based balancing
Hash-based algorithms compute a hash, which is a fixed-size number derived from some input, and use it to choose a server. The same input always gives the same server, as long as the pool does not change. Common inputs are:
- The client IP address (often called IP hash or source hash).
- A request header, a cookie value, or the URL.
The result is a kind of stickiness without storing any state. This helps in these cases:
- Backends keep a local cache, and the same URL should reach the same cache.
- A client should keep reaching the same server, and you do not want cookies.
The drawback is that a simple hash modulo the pool size reshuffles most clients when a server is added or removed. With 3 servers, a key maps to hash % 3. With 4 servers, it maps to hash % 4, and most keys change servers. Caches go cold all at once. A later chapter covers consistent hashing, which limits this movement.
IP hash has two other problems. Many users behind one company or mobile carrier share one public IP, so one server can receive a disproportionate share. And if the balancer itself sits behind another proxy, every request may appear to come from the same address.
Other options
- Random picks a server at random. With a large number of requests it evens out, and it needs no shared state, which suits many balancer instances.
- Power of two choices picks two servers at random and sends the request to the one with fewer connections. It captures most of the benefit of least connections with far less coordination, and it avoids the herd effect where every balancer sends traffic to the same momentarily idle server.
- First available or primary/backup always uses the first healthy server and moves on only when it is full or down. It suits cases like a warm standby.
Comparing the algorithms
| Algorithm | Uses | Best for | Main weakness |
|---|---|---|---|
| Round robin | Order only | Equal servers, similar short requests | Ignores load |
| Weighted round robin | Order and weights | Mixed server sizes | Weights are static guesses |
| Least connections | Live connection counts | Variable or long requests | Counts connections, not work |
| Hash (IP, URL, header) | Request data | Caches, stateless stickiness | Reshuffles when the pool changes |
| Random / two choices | Randomness, optional counts | Many balancer instances | Less predictable short-term |
A decision path
If you are unsure, start with least connections for HTTP services with varied requests, and round robin for simple stateless services with uniform requests. Measure before you tune further.
Configuring algorithms in NGINX
NGINX selects the algorithm inside the upstream block. With no directive, it uses round robin. This example uses least connections, a weight, passive failure detection and 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;
}
}Here the first server has weight 3, so it counts as three times as able as the second when NGINX compares load. After three failed attempts within the timeout window, NGINX stops using a server for 30 seconds. The backup server only receives traffic when the others are unavailable. Replace least_conn; with ip_hash; or hash $request_uri consistent; to use hashing.
Configuring algorithms in HAProxy
HAProxy sets the algorithm with the balance keyword in a backend.
frontend web
mode http
bind *:443 ssl crt /etc/haproxy/certs/site.pem
default_backend app
backend app
mode http
balance roundrobin
option httpchk GET /healthz
http-check expect status 200
cookie SRV insert indirect nocache
server app1 10.0.0.11:8080 check cookie app1
server app2 10.0.0.12:8080 check cookie app2Other values include leastconn, source (hash of client IP) and uri (hash of the URL). A weight setting on a server line gives weighted behaviour. The check keyword turns on active health checks, covered in the next chapter.
Common errors
- Using round robin with long-lived connections. Connections pile up unevenly after restarts, because old servers keep their connections and new ones get few. Use least connections.
- Forgetting that the algorithm only chooses among healthy servers. A good algorithm cannot help if failed servers stay in the pool. Pair it with health checks.
- Hashing on the client IP behind a proxy. Every request may carry the proxy's address. Hash on a forwarded header instead, and only if you trust it.
- Setting weights once and never revisiting them. Re-check them when hardware or instance sizes change.
- Judging an algorithm from a short test. Random and round robin look uneven over a few dozen requests. Test with realistic volume and request mix.
- Using stickiness to hide a state problem. If a server must hold user state, losing that server loses the state. Hashing makes this worse when the pool changes.
Exercise
Your pool has three identical servers. Most requests take 20 ms, but a report endpoint takes up to 30 seconds. Users see occasional slow responses even though average CPU use is low. Which algorithm would you switch to from round robin, and why?
Show answer
Switch to least connections. Round robin ignores load, so by chance several 30-second report requests can land on one server, which then queues the fast requests behind them. Least connections sees that this server holds many open connections and sends new requests to less busy servers. Because the servers are identical, no weights are needed.
Exercise
You use hash $request_uri over a pool of 4 caching servers (a plain hash, not consistent hashing). You add a fifth server. Roughly what happens to the caches, and what would you use to reduce the effect?
Show answer
Most keys map to a different server because the modulus changes from 4 to 5, so many cached objects are no longer found where requests now go. Cache hit rates drop until the new mapping warms up. Use consistent hashing, which moves only about one in five keys (the share the new server takes over), and not most of them.