Cloud VPS from $1.98/mo · pay with Bitcoin, Ethereum, Monero, USDT or Solana · paid in crypto
Networking

Load balancing in practice: two web servers behind HAProxy

Build a working load balancer: HAProxy in front of two web servers, with health checks, TLS, shared sessions and a standby for when the balancer fails.

CloudSat teamNovember 18, 20268 min read
Abstract illustration of a single beam of light splitting evenly into two paths that end at twin glowing server blocks
On this pageWhat a load balancer buys you

A site that lives on one server fails as one piece. A kernel update, a bad deploy or a full disk, and every visitor sees the same error. A load balancer splits that risk: it accepts every request, hands each one to a healthy copy of the application and drops a broken copy from rotation on its own. This guide builds the smallest setup worth running, HAProxy in front of two web servers, then deals with the weak spot most tutorials leave in place: the balancer itself.

What a load balancer buys you

Each benefit maps to a line of configuration you will write below.

Benefit Where it comes from
A failed server leaves rotation by itself check plus an HTTP health check
Deploys without downtime draining a server through the runtime API
More capacity in minutes one more server line
One place for TLS and redirects bind :443 ssl on the balancer
Overload becomes a short queue maxconn per server and timeout queue

The costs are concrete too: one more hop per request, one more server to patch, and anything the app kept on its own disk (sessions, uploads, cron jobs) now exists twice.

Layer 4 or layer 7

HAProxy works in one of two modes. With mode tcp it forwards connections and sees only addresses and ports, which suits databases, mail and other protocols that are not HTTP, with TLS passing through to the servers. With mode http it reads each request, so it can run HTTP health checks, route by host or path, add headers, set cookies and terminate TLS. A website wants HTTP mode, which the configuration below uses.

The layout

Three servers in one region, each with a public address (documentation addresses here, so use your own).

Server Role Address
lb-01 HAProxy 203.0.113.10
web-01 nginx and the app 198.51.100.21
web-02 nginx and the app 198.51.100.22

DNS for example.com points at lb-01. Both web servers run the same code, deployed the same way.

Prepare the web servers

Each web server needs a health endpoint and a firewall that accepts port 80 from the balancer only. The static reply below only proves that nginx is up; if a lost database connection should also take a server out of rotation, point the check at an app route that queries the database.

server {
    listen 80 default_server;
    server_name example.com;
    root /var/www/example;

    set_real_ip_from 203.0.113.10;
    real_ip_header X-Forwarded-For;

    location = /healthz {
        access_log off;
        default_type text/plain;
        return 200 "ok\n";
    }
}

The two real_ip lines restore the visitor's address in your logs; without them, every request seems to come from 203.0.113.10. Since only the balancer can reach port 80, the header can be trusted.

sudo ufw allow OpenSSH
sudo ufw allow from 203.0.113.10 to any port 80 proto tcp
sudo ufw enable

On CloudSat, the same restriction can also live in a cloud firewall, so it still holds if someone disables ufw on the server.

Configure HAProxy

Install HAProxy, certbot and socat on lb-01 with sudo apt install haproxy certbot socat. Packaged versions differ by release (2.8 on Ubuntu 24.04, 3.0 on Debian 13, 3.2 on Ubuntu 26.04, while the newest upstream LTS branch is 3.4), and everything below works on all of them. Keep the global section the package installed, since it defines the admin socket used later, and replace the rest of /etc/haproxy/haproxy.cfg with this:

defaults
    log     global
    mode    http
    option  httplog
    timeout connect 5s
    timeout client  30s
    timeout server  30s

frontend fe_web
    bind :80
    bind :443 ssl crt /etc/haproxy/certs/example.com.pem alpn h2,http/1.1
    acl acme path_beg /.well-known/acme-challenge/
    http-request redirect scheme https code 301 if !{ ssl_fc } !acme
    http-request set-header X-Forwarded-Proto https if { ssl_fc }
    option forwardfor
    use_backend be_acme if acme
    default_backend be_web

backend be_web
    balance leastconn
    option httpchk
    http-check send meth GET uri /healthz ver HTTP/1.1 hdr Host example.com
    http-check expect status 200
    retries 2
    option redispatch
    timeout queue 10s
    default-server inter 3s fall 3 rise 2 maxconn 200
    server web-01 198.51.100.21:80 check
    server web-02 198.51.100.22:80 check

backend be_acme
    server certbot 127.0.0.1:8888

The backend does the real work. option httpchk and the two http-check lines send GET /healthz to each server every three seconds (inter 3s). Three failures in a row mark a server DOWN (fall 3), and two successes bring it back (rise 2). retries 2 with option redispatch sends a request that could not connect to the other server instead of returning an error. maxconn 200 caps concurrent requests per server, so extra requests wait in HAProxy's queue for up to ten seconds rather than piling onto a struggling app. Treat 200 as a placeholder for what one app server handles comfortably.

Add the certificate

HAProxy expects the certificate chain and private key in one PEM file, and it refuses to start when that file is missing. Leave the bind :443 line out at first, reload, and request the certificate through the acme route, which forwards challenges to certbot on a local port:

sudo mkdir -p /etc/haproxy/certs
sudo certbot certonly --standalone --http-01-port 8888 --http-01-address 127.0.0.1 -d example.com \
  --deploy-hook 'umask 077; cat "$RENEWED_LINEAGE/fullchain.pem" "$RENEWED_LINEAGE/privkey.pem" > /etc/haproxy/certs/example.com.pem && systemctl reload haproxy'

Certbot runs the deploy hook after the first issuance and after every renewal, so the PEM file stays current. Put the bind :443 line back, then test the file before every reload:

sudo haproxy -c -f /etc/haproxy/haproxy.cfg && sudo systemctl reload haproxy

Pick a balancing algorithm

Algorithm Sends each request to Suits
roundrobin the next server in turn short, similar requests
leastconn the server with the fewest open connections uneven request times, WebSockets
source a server chosen from a hash of the client IP rough stickiness without cookies

Without a balance line, the default depends on the HAProxy version (roundrobin in older releases, random since 3.3), so always set it explicitly. The configuration above uses leastconn because most web apps mix fast pages with slow ones.

Make the application safe to duplicate

Two servers expose every shortcut that worked on one.

Sessions. Frameworks that keep sessions in local files, PHP with its default handler among them, log users out when consecutive requests land on different servers. Move sessions to Redis, Valkey or the database. As a stopgap, HAProxy can pin each visitor to one server with a cookie:

backend be_web
    cookie SRV insert indirect nocache
    server web-01 198.51.100.21:80 check cookie w1
    server web-02 198.51.100.22:80 check cookie w2

Stickiness hides the problem rather than fixing it: when a server dies, its visitors still lose their sessions.

Uploads. A file written to web-01's disk does not exist on web-02. Store uploads in object storage or on a shared file server.

Scheduled jobs. A cron job deployed to both servers runs twice. Pick one server for jobs, or take a lock in the database before each run.

Break it on purpose

A setup you have never seen fail is one you cannot trust yet. Stop nginx on web-01, then ask HAProxy what it sees while you keep requesting the site:

sudo systemctl stop nginx                     # on web-01
echo "show stat" | sudo socat stdio /run/haproxy/admin.sock | cut -d, -f1,2,18 | grep be_web
for i in $(seq 1 10); do curl -sI https://example.com/ | head -n 1; done

After three failed checks, about nine seconds with this configuration, web-01 shows DOWN and every request is answered by web-02. Start nginx again and web-01 returns after two good checks. The same runtime API handles deploys: drain a server, update it, put it back.

echo "set server be_web/web-01 state drain" | sudo socat stdio /run/haproxy/admin.sock
echo "set server be_web/web-01 state ready" | sudo socat stdio /run/haproxy/admin.sock

A drained server gets no new visitors but stays health-checked, and visitors pinned to it by cookie can finish.

The balancer is now the weak spot

Everything above survives the loss of a web server, but lb-01 is a single machine, and losing it still takes the site down. The usual fix is a second, identical balancer and an address that can move between the two.

  1. Build lb-02 with the same packages, configuration and certificate. Copy /etc/haproxy across after every change, or keep it in Git, and add lb-02's address to the web servers' firewall and set_real_ip_from lines.
  2. Point DNS at a floating IP attached to lb-01 rather than at lb-01's own address. The frontend binds :80 and :443 on every address, so lb-02 accepts traffic as soon as the floating IP reaches it.
  3. When lb-01 fails, move the floating IP to lb-02. keepalived can automate the switch, with VRRP where the network allows it or with a script that calls the provider's API, so check that such an API exists first.

On CloudSat, a floating IP costs $2.00 a month and is reassigned to the standby from the console, and HAProxy is available as a one-click app for both balancers.

DNS failover is the other route: a DNS service checks lb-01 and swaps the record when it stops answering. It needs no movable address, but resolvers cache answers for the record's TTL, so the switch is slower and less predictable. Plain round robin, two A records and no checks, is weaker still: DNS keeps handing out a dead server's address until someone removes it.

FAQ

Is a load balancer worth it with only one app server?

For availability, no, because there is still one copy of the application. It can still serve as the single place for TLS, redirects and request queueing, and adding a second server later becomes one configuration line with no DNS change. If none of that matters yet, skip it.

HAProxy or nginx as the balancer?

Both can do the job. The difference that matters most here is health checking: open-source nginx only notices a failed server when real requests to it fail, while active health checks belong to the commercial NGINX Plus. HAProxy ships active checks, the runtime API and a statistics page in its free version.

How large should the balancer server be?

Usually smaller than the app servers. HAProxy uses little memory, and the expensive part is TLS handshakes, which cost CPU. Start on a small plan, watch CPU at your busiest hour with top or the HAProxy statistics, and resize if it stays high.

Run it on CloudSat. Cloud VPS on AMD EPYC and NVMe from $1.98/mo in 13 regions, delivered in under 5 minutes and paid in crypto. See plans or deploy a server.