Load Balancing
A load balancer (LB) spreads incoming requests over a pool of servers. It makes a group of machines look like one, lets you add or remove machines without clients noticing, and stops sending traffic to servers that fail their health checks.
+------------------+
clients ------> | load balancer | health checks every few seconds
+------------------+
| | |
web1 web2 web3 (unhealthy: removed from rotation)Layer 4 vs layer 7
| L4 (transport) | L7 (application) | |
|---|---|---|
| Sees | IPs, ports, TCP/UDP | HTTP method, path, headers, cookies |
| Can route by | Connection | URL, header, user, A/B group |
| Speed | Very fast, little CPU | Slower: must parse HTTP, often terminates TLS |
| Examples | AWS NLB, LVS, Maglev | Nginx, HAProxy, Envoy, AWS ALB |
Balancing algorithms
The algorithm decides which server gets the next request. Here are the common ones as small functions over the same pool:
import hashlib
from itertools import cycle
servers = ["web1", "web2", "web3"]
# 1. Round robin: take turns
rr = cycle(servers)
print("round robin: ", [next(rr) for _ in range(7)])
# 2. Weighted round robin: web1 is twice as big as the others
weights = {"web1": 2, "web2": 1, "web3": 1}
wrr = cycle([s for s, w in weights.items() for _ in range(w)])
print("weighted rr: ", [next(wrr) for _ in range(8)])
# 3. Least connections: pick the server with the fewest open connections
open_conns = {"web1": 12, "web2": 4, "web3": 9}
print("least connections:", min(open_conns, key=open_conns.get))
# 4. IP hash: the same client always lands on the same server
def ip_hash(ip):
digest = int(hashlib.md5(ip.encode()).hexdigest(), 16)
return servers[digest % len(servers)]
for ip in ["10.0.0.1", "10.0.0.2", "10.0.0.1"]:
print(f"ip hash {ip}:", ip_hash(ip))round robin: ['web1', 'web2', 'web3', 'web1', 'web2', 'web3', 'web1']
weighted rr: ['web1', 'web1', 'web2', 'web3', 'web1', 'web1', 'web2', 'web3']
least connections: web2
ip hash 10.0.0.1: web1
ip hash 10.0.0.2: web3
ip hash 10.0.0.1: web1
Smooth weighted round robin (used by Nginx) interleaves the heavier server instead of sending it two requests in a row, but the idea is the same: requests in proportion to capacity.
Why least connections wins with uneven requests
Round robin assumes every request costs the same. When some requests are slow (reports, uploads), a server can be stuck with several of them while others sit idle. The simulation sends the same seeded stream of requests to three servers with each strategy and measures how long requests wait:
import random
def simulate(strategy, n=3000, servers=3, seed=42):
rng = random.Random(seed)
busy_until = [[] for _ in range(servers)] # finish times of active requests
t, waits, turn = 0.0, [], 0
for _ in range(n):
t += rng.expovariate(1 / 1.6) # a request every ~1.6 ms
cost = 50 if rng.random() < 0.05 else 5 # 5% slow requests
for active in busy_until: # drop finished requests
active[:] = [f for f in active if f > t]
if strategy == "round robin":
s, turn = turn % servers, turn + 1
elif strategy == "random":
s = rng.randrange(servers)
else: # least connections
s = min(range(servers), key=lambda i: len(busy_until[i]))
# each server processes 2 requests at a time
start = t if len(busy_until[s]) < 2 else sorted(busy_until[s])[-2]
busy_until[s].append(max(start, t) + cost)
waits.append(max(start, t) - t)
waits.sort()
return sum(waits) / n, waits[int(n * 0.99)]
for strategy in ["random", "round robin", "least connections"]:
avg, p99 = simulate(strategy)
print(f"{strategy:<18} avg wait {avg:6.2f} ms p99 wait {p99:6.1f} ms")random avg wait 13.37 ms p99 wait 87.2 ms
round robin avg wait 6.30 ms p99 wait 52.9 ms
least connections avg wait 2.08 ms p99 wait 31.5 ms
Least connections reacts to the actual load on each server, so slow requests don't pile up behind each other: here it cuts the average wait to a third of round robin's and the p99 wait from about 53 ms to 32 ms. Random choice is worst, because it can send several requests in a row to the same busy server. A popular cheap variant, power of two choices, picks two servers at random and sends the request to the less loaded one; it gets most of the benefit without tracking every server globally.
Health checks and failover
The LB probes every server (for example GET /healthz every 5 s). After a few consecutive failures it removes the server; after a few successes it adds it back. Requiring several results in a row avoids "flapping" on a single slow response.
class Pool:
def __init__(self, names, fall=3, rise=2):
self.state = {n: {"healthy": True, "fails": 0, "oks": 0} for n in names}
self.fall, self.rise = fall, rise
def report(self, name, ok):
s = self.state[name]
if ok:
s["oks"], s["fails"] = s["oks"] + 1, 0
if not s["healthy"] and s["oks"] >= self.rise:
s["healthy"] = True
else:
s["fails"], s["oks"] = s["fails"] + 1, 0
if s["healthy"] and s["fails"] >= self.fall:
s["healthy"] = False
def healthy(self):
return [n for n, s in self.state.items() if s["healthy"]]
pool = Pool(["web1", "web2", "web3"])
web2_results = [True, False, False, True, False, False, False, True, True, True]
for check, ok in enumerate(web2_results, start=1):
pool.report("web2", ok)
print(f"check {check:2}: web2 {'ok ' if ok else 'FAIL'} -> in rotation: {pool.healthy()}")check 1: web2 ok -> in rotation: ['web1', 'web2', 'web3']
check 2: web2 FAIL -> in rotation: ['web1', 'web2', 'web3']
check 3: web2 FAIL -> in rotation: ['web1', 'web2', 'web3']
check 4: web2 ok -> in rotation: ['web1', 'web2', 'web3']
check 5: web2 FAIL -> in rotation: ['web1', 'web2', 'web3']
check 6: web2 FAIL -> in rotation: ['web1', 'web2', 'web3']
check 7: web2 FAIL -> in rotation: ['web1', 'web3']
check 8: web2 ok -> in rotation: ['web1', 'web3']
check 9: web2 ok -> in rotation: ['web1', 'web2', 'web3']
check 10: web2 ok -> in rotation: ['web1', 'web2', 'web3']
Session affinity and consistent hashing
Some workloads want the same key on the same server: a cache shard, a WebSocket connection, a user's in-memory session. Simple hash % N (like IP hash above) does that, but adding a server remaps almost every key. Consistent hashing (its own lesson) remaps only about 1/N of the keys, which is why caches and sharded stores use it.
Tip: The load balancer must not become the single point of failure. Run LBs in pairs (active/passive with a floating IP, or active/active behind DNS or anycast), or use a managed cloud LB, which is redundant internally.
Test yourself
Which algorithm adapts best when request costs vary a lot?
- Round robin
- Least connections
- IP hash
- Alphabetical
What can an L7 load balancer do that an L4 one cannot?
- Forward TCP connections
- Route by URL path or HTTP header
- Balance UDP traffic
- Work with IPv6
Why do health checks require several failures in a row before removing a server?
- To save bandwidth
- To avoid flapping on a single slow or lost probe
- Because servers need time to boot
- It is required by HTTP