TExcelTAD
Home › Computer Networking › Load Balancing

Load Balancing

A popular website can't run on one server: it would be too slow, and a single failure would take it down. A load balancer sits in front of a pool of servers (the backends), accepts client connections on one address, and spreads them across the healthy backends.

Layer 4 vs layer 7

L4 load balancer L7 load balancer
Sees IPs, ports, TCP/UDP full HTTP requests: path, headers, cookies
Decides by connection 5-tuple URL, host name, header, user…
TLS passes it through usually terminates it (holds the certificate)
Speed very fast, simple more CPU, much more flexible
Examples AWS NLB, LVS, Maglev nginx, HAProxy, Envoy, AWS ALB

An L7 balancer can send /api/* to API servers and /images/* to image servers, add headers like X-Forwarded-For (so the app knows the client's IP), retry failed requests, and do canary releases ("5% of traffic to the new version").

Algorithms

python · try it yourself
from itertools import cycle

backends = ["app1", "app2", "app3"]

# 1. Round robin: take turns
rr = cycle(backends)
print("round robin:      ", [next(rr) for _ in range(7)])

# 2. Weighted round robin: app1 is twice as powerful
weights = {"app1": 2, "app2": 1, "app3": 1}
wrr = cycle([b for b, w in weights.items() for _ in range(w)])
print("weighted RR:      ", [next(wrr) for _ in range(8)])

# 3. Least connections: send to the backend with the fewest active connections
active = {"app1": 12, "app2": 3, "app3": 7}
picks = []
for _ in range(5):
    choice = min(active, key=lambda b: (active[b], b))
    active[choice] += 1
    picks.append(choice)
print("least connections:", picks, active)
round robin:       ['app1', 'app2', 'app3', 'app1', 'app2', 'app3', 'app1']
weighted RR:       ['app1', 'app1', 'app2', 'app3', 'app1', 'app1', 'app2', 'app3']
least connections: ['app2', 'app2', 'app2', 'app2', 'app2'] {'app1': 12, 'app2': 8, 'app3': 7}

Round robin is fine when requests are similar. Least connections adapts when some requests take much longer than others (file uploads, reports), because slow backends naturally accumulate connections and get fewer new ones.

Hashing and sticky sessions

Some applications keep per-user state in a server's memory, so a user should keep reaching the same backend (session affinity). One way is to hash the client IP. Plain hash mod N has a nasty property, though: when a server is added or removed, almost every client moves. Consistent hashing places servers and keys on a ring, so only about 1/N of the keys move:

python · try it yourself
import bisect
import hashlib

def h(text):
    return int(hashlib.md5(text.encode()).hexdigest()[:8], 16)

clients = [f"203.0.113.{i}" for i in range(1, 21)]

def modulo(servers):
    return {c: servers[h(c) % len(servers)] for c in clients}

def ring(servers, replicas=50):
    points = sorted((h(f"{s}#{r}"), s) for s in servers for r in range(replicas))
    keys = [p[0] for p in points]
    return {c: points[bisect.bisect(keys, h(c)) % len(points)][1] for c in clients}

for name, strategy in [("hash mod N", modulo), ("consistent hashing", ring)]:
    before = strategy(["app1", "app2", "app3"])
    after = strategy(["app1", "app2", "app3", "app4"])
    moved = sum(before[c] != after[c] for c in clients)
    print(f"{name:<19} adding app4 moves {moved:>2} of {len(clients)} clients")
hash mod N          adding app4 moves 19 of 20 clients
consistent hashing  adding app4 moves  4 of 20 clients

L7 balancers more often use a cookie set by the balancer to remember the backend. Even better is keeping session state out of the app servers entirely (in Redis or a database), so any backend can serve any request.

Health checks

The balancer regularly probes every backend (for example GET /healthz every 5 s). A backend is marked down after several consecutive failures and up again after several successes, so one slow response doesn't flap it in and out:

python · try it yourself
probe_results = {
    "app1": "✓✓✓✓✓✓✓✓",
    "app2": "✓✓✗✗✗✓✓✓",
    "app3": "✓✗✓✗✓✗✓✓",
}
FALL, RISE = 3, 2

for backend, results in probe_results.items():
    healthy, fails, oks, timeline = True, 0, 0, ""
    for r in results:
        if r == "✓":
            oks, fails = oks + 1, 0
            if not healthy and oks >= RISE:
                healthy = True
        else:
            fails, oks = fails + 1, 0
            if healthy and fails >= FALL:
                healthy = False
        timeline += "U" if healthy else "D"
    print(f"{backend}: probes {results}  state {timeline}")
app1: probes ✓✓✓✓✓✓✓✓  state UUUUUUUU
app2: probes ✓✓✗✗✗✓✓✓  state UUUUDDUU
app3: probes ✓✗✓✗✓✗✓✓  state UUUUUUUU

app3 fails every other probe but never three in a row, so it stays in service; app2 is taken out after three failures and returns after two successes.

Real configuration: nginx

text
upstream app_servers {
    least_conn;
    server 10.0.1.11:8080 weight=2;
    server 10.0.1.12:8080;
    server 10.0.1.13:8080 max_fails=3 fail_timeout=30s;
}

server {
    listen 443 ssl;
    server_name shop.example.com;
    location / {
        proxy_pass http://app_servers;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

Avoiding a single point of failure

The load balancer itself must not become the weak spot. Common designs:

  • Active/passive pair sharing a virtual IP with VRRP/keepalived: if the active one dies, the standby takes over the IP within a second or two.
  • DNS load balancing: several A records for one name, each pointing at a different balancer or region.
  • Anycast + ECMP: many balancers announce the same IP; routers spread flows across them by hashing the 5-tuple (this is how large cloud and CDN front ends work).

Tip: When a user reports "the site is slow sometimes", check whether one backend is unhealthy but still in rotation. Per-backend latency and error metrics from the load balancer usually find it in seconds.

Test yourself

Which load balancer can route requests based on the URL path?

  1. Layer 2
  2. Layer 4
  3. Layer 7
  4. None can

Why is least-connections better than round robin when request durations vary a lot?

  1. It is random
  2. Busy backends hold more open connections and therefore receive fewer new ones
  3. It uses less memory
  4. It encrypts traffic

What is the advantage of consistent hashing over hash mod N?

  1. It is faster to compute
  2. Adding or removing a server moves only a small fraction of keys
  3. It needs no hash function
  4. It guarantees equal load