How It Works
Clients connect to one address, the load balancer's. For each new connection or request, the balancer picks a backend by a balancing method, forwards the traffic, and returns the answer. In the background it checks that every backend is healthy. A load balancer is a kind of reverse proxy whose main job is spreading load. Common open-source choices on Linux are HAProxy and Nginx.
Layer 4 vs Layer 7
| Layer 4 | Layer 7 | |
|---|---|---|
| Works with | TCP or UDP connections | HTTP requests |
| Decides by | Address and port | Host, path, headers, cookies |
| Sees content | No | Yes |
| TLS | Passed through | Usually terminated |
| Suits | Databases, mail, any TCP | Websites and APIs |
Layer 4 balancing is lighter and works for any protocol. Layer 7 can route /api/ to other servers than /, add headers, and retry a failed request elsewhere. The layers refer to the OSI model; TCP and UDP sit at layer 4.
Balancing Methods
- Round robin: each backend in turn. Good when requests cost about the same.
- Weighted: a larger server gets a larger share.
- Least connections: the backend with the fewest open connections. Good when some requests take much longer than others.
- Hashing: the client address, a cookie, or the URL decides the backend, so the same key always lands on the same server. Consistent hashing keeps most keys in place when a backend is added or removed.
Health Checks
An active check probes each backend on a schedule, for example by requesting /health every few seconds, and removes a backend that fails until it recovers. A passive check watches real traffic and marks a backend as failed after errors or timeouts. HAProxy does active checks; check on a server line turns them on, every two seconds by default, and option httpchk makes them HTTP requests:
backend app
balance roundrobin
option httpchk
http-check send meth GET uri /health
server app1 10.10.0.11:8080 check
server app2 10.10.0.12:8080 check
A good health endpoint checks what the application needs, such as its database connection, and answers quickly.
An Example with Nginx
upstream app {
least_conn;
server 10.10.0.11:8080 max_fails=3 fail_timeout=30s;
server 10.10.0.12:8080 max_fails=3 fail_timeout=30s;
}
server {
listen 443 ssl;
server_name example.com;
location / {
proxy_pass http://app;
}
}
Open-source Nginx checks passively: with these parameters, three failed attempts within 30 seconds make a backend unavailable for 30 seconds. Without them, the defaults are max_fails=1 and fail_timeout=10s, so a single failure takes a backend out for 10 seconds. The backends use private addresses, as described in public vs private IP.
Sticky Sessions
If an application keeps login sessions in a backend's memory, a user sent to another backend appears logged out. Sticky sessions send a user back to the same backend, by a cookie the balancer sets or by hashing the client address (ip_hash in Nginx, which uses the first three parts of an IPv4 address or the whole IPv6 address). The sturdier fix is to keep sessions in a shared store, such as a database or Redis, so any backend can serve any user.
On Your Server: Watch the Balancing
Let each backend name itself in a header, for example with add_header X-Served-By $hostname; in each backend's Nginx configuration. Then send several requests:
for i in $(seq 1 6); do curl -sI https://example.com/ | grep -i x-served-by; done
With requests sent one after another, the names alternate, since least_conn falls back to round robin when the backends are equally busy. Stop the service on one backend and run the loop again: after the health check notices, only the other names appear. On the balancer, ss -tn state established '( dport = :8080 )' lists the open connections to the backends.
Client Addresses and the Single Point of Failure
- Client address: a layer 7 balancer passes it in
X-Forwarded-For; a layer 4 balancer can use the PROXY protocol. The backends must be set up to read it. - The balancer itself: with one balancer, its failure takes everything down. The usual answer is two balancers sharing a floating IP address that moves to the standby when the active one fails, for example with keepalived and VRRP.
- Changes: test the configuration before reloading, with
sudo nginx -torhaproxy -c -f /etc/haproxy/haproxy.cfg.