32.8. Load Balancing with HAProxy

Where the cluster sections move one service between hosts, load balancing spreads one service across hosts. HAProxy is the userspace proxy that does it with full knowledge of the protocol.

32.8.1. Choosing Application Proxying or Kernel-Level Load Balancing

Criterion HAProxy (userspace proxy) LVS/IPVS (kernel forwarding)
Where packets are processed every connection terminates in a userspace process the kernel rewrites and forwards; no daemon touches the data path
Protocol awareness full HTTP parsing, headers, TLS, redirects TCP/UDP addresses and ports only
Health checks arbitrary (HTTP status, response content, scripts) connect-based checks by default in Keepalived, extensible with checkers
Client address visibility the backend sees the proxy's address; X-Forwarded-For restores the original every mode preserves the client's source address; NAT rewrites the destination only
Cost per connection userspace scheduling, one more copy of each byte near line rate
Session stickiness stick-table with any key IPVS persistence by client address
Best fit HTTP(S) services needing routing decisions very high-throughput TCP/UDP pools

The two compose: LVS or IPVS can front HAProxy farms, and the redundant LVS directors of section 32.11 use the same VRRP mechanism as the Keepalived examples. Choose HAProxy when the service needs decisions made in the protocol - TLS termination, path routing, header manipulation (Chapter 23 uses it in exactly that role for application hosting) - and IPVS when the requirement is raw packet distribution at rates where a userspace hop would be the bottleneck.

32.8.2. Configuring TCP and HTTP Frontends and Backends

Before the balancers take addresses, take the competing address manager out of the picture: the Pacemaker stack from the first half of the chapter owns virtual addresses too, and section 32.9.6's rule is that one address has exactly one manager. Stop the cluster stack on ha1, as john:

$ sudo crm cluster stop
INFO: The cluster stack stopped on ha1

The stop is clean - resources are stopped on ha1 before the stack goes down - and the quorum arithmetic of section 32.3.4 does the right thing with the remainder: ha2, still holding the witness's vote, keeps quorum, inherits the NFS group, and serves the .100 address alone for as long as ha1's stack is down. The NFS service stays up throughout the load-balancing exercises; only its owner changed. The NFS client's hard mount rides through the move as section 32.6.5 showed.

The load-balancing exercises reuse the practice hosts in new roles: ha1 and ha2 are the load balancers, while haclient and lbclient run a small HTTP backend. Install the proxy and the socket tool on both balancers. On ha1, as john:

$ sudo apt install haproxy socat

On ha2, the same command.

The backend is a tiny Python server that reports which host answered and what forwarding headers it saw. Write it to ~/debian-handbook/ha/backend.py on both backend hosts - the file is identical everywhere:

#!/usr/bin/env python3
from http.server import BaseHTTPRequestHandler, HTTPServer
import socket, sys

class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        body = (
            f"backend={socket.gethostname()}\n"
            f"path={self.path}\n"
            f"x-forwarded-for={self.headers.get('X-Forwarded-For', '')}\n"
            f"x-forwarded-proto={self.headers.get('X-Forwarded-Proto', '')}\n"
        )
        data = body.encode()
        self.send_response(200)
        self.send_header("Content-Type", "text/plain")
        self.send_header("Content-Length", str(len(data)))
        self.end_headers()
        self.wfile.write(data)

    def log_message(self, *args):
        pass

HTTPServer(("0.0.0.0", int(sys.argv[1])), Handler).serve_forever()

Run it on haclient, as john:

$ python3 ~/debian-handbook/ha/backend.py 8081

The server runs in the foreground; leave it running, and stop it later with Ctrl-C. On lbclient, as john, start the same server the same way. Check each backend locally. On haclient, as john:

$ curl -s http://127.0.0.1:8081/
backend=haclient
path=/
x-forwarded-for=
x-forwarded-proto=

On lbclient, as john:

$ curl -s http://127.0.0.1:8081/
backend=lbclient
path=/
x-forwarded-for=
x-forwarded-proto=

The two backends answer identically apart from their hostnames, and both report empty forwarding headers because nothing has forwarded them yet. That emptiness is what the proxy will change.

The proxy configuration is one file, identical on both balancers. Write /etc/haproxy/haproxy.cfg on ha1 and ha2:

global
    daemon
    maxconn 1024
    log /dev/log local0
    stats socket /run/haproxy/admin.sock mode 660 level admin

defaults
    mode http
    timeout connect 2s
    timeout client 10s
    timeout server 10s

frontend http-in
    bind *:8080
    option forwardfor
    http-request set-header X-Forwarded-Proto http
    default_backend app

frontend https-in
    bind *:8443 ssl crt /etc/haproxy/certs/ha.pem
    option forwardfor
    http-request set-header X-Forwarded-Proto https
    default_backend app

backend app
    balance roundrobin
    option httpchk GET /
    server app1 192.168.232.13:8081 check inter 1s fall 2 rise 2
    server app2 192.168.232.14:8081 check inter 1s fall 2 rise 2

Read it top down. The stats socket line exposes a runtime administration socket on the filesystem, used below to watch backend state. The two frontends bind plain HTTP on port 8080 and TLS on 8443, both adding the forwarding headers section 32.8.4 examines. The backend names two servers, checks each once a second, and removes a server after two failed checks, restoring it after two successes.

The TLS listener needs a certificate. On both balancers, as john, create a key and certificate and combine them in the PEM file the bind line names - the practice certificate is self-signed and short-lived:

$ sudo openssl req -x509 -newkey rsa:2048 -nodes -keyout /tmp/ha.key -out /tmp/ha.crt -days 30 -subj "/CN=192.168.232.150"

openssl prints a short summary of the generated certificate to standard error and writes the two files. Combine and install them:

$ sudo install -d /etc/haproxy/certs
$ sudo sh -c "cat /tmp/ha.key /tmp/ha.crt > /etc/haproxy/certs/ha.pem"
$ sudo chmod 600 /etc/haproxy/certs/ha.pem

The sh -c wrapper keeps the redirection inside the root shell, where the target directory is writable; each command normally prints nothing.

Validate the configuration before loading it. On ha1, as john:

$ sudo haproxy -c -V -f /etc/haproxy/haproxy.cfg
Configuration file is valid

On ha2, the same command prints the same verdict.

Option Description
-c Check the configuration file and exit without starting
-V Show verbose errors during the check
-f FILE Configuration file to check or run
-v Print the HAProxy version

Start the service. On ha1, as john:

$ sudo systemctl restart haproxy

On ha2, the same. Each restart normally prints nothing; verify:

$ sudo systemctl is-active haproxy
active

Watch the backend state through the statistics socket:

$ echo "show stat" | sudo socat stdio /run/haproxy/admin.sock | cut -d, -f1,2,18
# pxname,svname,status
http-in,FRONTEND,OPEN
https-in,FRONTEND,OPEN
app,app1,UP
app,app2,UP
app,BACKEND,UP

The pipeline is one logical read: echo writes the administrative command show stat into socat, which relays standard input to the runtime socket and returns the CSV table, and cut extracts fields 1, 2, and 18 - the proxy name, the server name, and the status column. Both backends are UP, so the balancer is ready. From the independent client lbcli, as john:

$ for i in 1 2 3 4; do curl -s http://192.168.232.11:8080/ | head -1; done
backend=haclient
backend=lbclient
backend=haclient
backend=lbclient

Four requests, alternating hosts: roundrobin in action, addressed to ha1's own address. The loop is a natural way to see a balancer work; each curl prints the first line of one response, and the for loop issues four of them in sequence.

32.8.3. Application Health Checks, Backend Removal, and Recovery

The check option turns HAProxy into a judge of backend health. Stop one backend: in the terminal on haclient running backend.py, press Ctrl-C. Within the fall 2 interval - about two seconds at inter 1s - the balancer re-examines the server and withdraws it. On ha1, as john:

$ echo "show stat" | sudo socat stdio /run/haproxy/admin.sock | cut -d, -f1,2,18
# pxname,svname,status
http-in,FRONTEND,OPEN
https-in,FRONTEND,OPEN
app,app1,DOWN
app,app2,UP
app,BACKEND,UP

app1 is DOWN while the frontend and the other backend stay UP. The client sees the change as continuity, not as an error page. On lbcli, as john:

$ for i in 1 2 3 4; do curl -s http://192.168.232.11:8080/ | head -1; done
backend=lbclient
backend=lbclient
backend=lbclient
backend=lbclient

Every request landed on the healthy server, and no request failed. That is the entire point of health-checked load balancing: the failure of a backend is invisible except as a capacity reduction. Start the backend again on haclient, as john:

$ python3 ~/debian-handbook/ha/backend.py 8081

After rise 2 - about two more seconds - the socket reports recovery. On ha1, as john:

$ echo "show stat" | sudo socat stdio /run/haproxy/admin.sock | cut -d, -f1,2,18
# pxname,svname,status
http-in,FRONTEND,OPEN
https-in,FRONTEND,OPEN
app,app1,UP
app,app2,UP
app,BACKEND,UP

The measured behavior worth internalizing is the latency of the state change: with inter 1s fall 2 rise 2, a dead backend stops receiving new requests roughly two to three seconds after it stops answering. That is good for a lab; a production service decides the trade explicitly - shorter intervals withdraw backends faster but probe them harder, and a backend that is merely slow must not be confused with one that is dead (checks with timeouts sized to the real response time).

32.8.4. TLS Termination, Client Addresses, and Forwarded Headers

The second frontend terminates TLS at the balancer, which is the standard arrangement for backend pools: one place holds certificates and TLS policy, and the backends speak plain HTTP on a private network. From the client lbcli, as john, using -k because the practice certificate is self-signed:

$ curl -s -k https://192.168.232.11:8443/
backend=haclient
path=/
x-forwarded-for=192.168.232.15
x-forwarded-proto=https

Compare against the direct backend request in section 32.8.2: the two header lines are no longer empty. option forwardfor added X-Forwarded-For carrying the client's address (192.168.232.15 is lbcli), and http-request set-header X-Forwarded-Proto https recorded that the client connection was TLS even though the backend connection was not. The backend's application can now log the true client address and protocol - provided it trusts the proxy, which is an access-control decision, not a technicality: only known proxies may set those headers, or a client could forge them (Chapter 23 makes the same argument for application servers behind reverse proxies).

The certificate itself is the production difference between this practice setup and a deployment: a real service presents a certificate trusted by clients, renews it before expiry, and usually serves it on a floating address rather than per-node addresses - which is exactly what the next section adds.

32.8.5. Connection Loss, Client Retries, and Application Session State

What a client experiences when a backend is removed depends on when it happens. Requests between removal and recovery never reach the dead backend - new connections go to healthy servers. A request in flight when its backend dies is closed by the proxy, and the client sees a connection reset and retries. HAProxy can retry connection failures to a different server before answering the client, which converts some failures into a few milliseconds of latency - but a retry after the request reached the application is a duplicate from the application's point of view, and section 32.2.3's idempotency rule is the only real defense. The backend exercises in this chapter made retries harmless by construction: every request was a read or a uniquely-keyed write.

Session state decides the blast radius of a backend failure. Stateless requests fail over freely - the alternation captures show the pool absorbing one server's loss with no client action. Sessions stored in a backend's memory die with it; the standard answers are sticky routing so a session's requests stay with its server, an external session store so any server can resume, or acceptance that clients log in again. HAProxy's stick-table mechanism implements the first by recording which server a client key mapped to; it is the userspace analogue of IPVS persistence seen in section 32.10.5, and it shares that mechanism's limitation: the table is per-proxy, and a failover of the balancer is a separate event with its own design, which is the subject of the next section.