HAProxy: the load balancer that predates the cool reverse proxies

Twenty-plus years old and still the thing serious traffic runs through

Contents

Every reverse proxy conversation I have lately starts with Traefik or Caddy, both genuinely good tools with automatic HTTPS and configuration that reads cleanly. HAProxy came up in none of them for a while, which is a strange gap given that it’s still running underneath a large share of the internet’s serious traffic and has been doing so since 2001 — two decades of a single, narrowly-focused tool getting better at exactly one job rather than accumulating features it didn’t need. I moved my homelab’s load-balancing layer to it after outgrowing what a simpler reverse proxy could tell me about the backends it was routing to, and the config file that scared me off initially turned out to be the thing I appreciate most about it now.

What HAProxy actually is, distinct from a reverse proxy

“Reverse proxy” and “load balancer” get used interchangeably, and for tools like Traefik or nginx that do both reasonably well, that’s fine. HAProxy’s own framing is more precise: it’s a TCP/HTTP load balancer first, with proxying as the mechanism that makes load balancing possible rather than the other way around. That distinction shows up in what it’s good at — HAProxy has some of the most sophisticated backend health checking, load-balancing algorithm choices and connection-level control of any tool in this category, at the cost of a configuration syntax that’s older and more explicit than what Caddy or Traefik offer. Sticky Sessions covers how cookie-based and IP-hash affinity work in a load balancer, and why removing the need for stickiness is the better fix.

Two rack-mounted network switches in a dark equipment rack.
Rack-mounted switches in a data hall: the sort of equipment whose traffic a load balancer such as HAProxy spreads across backend servers. Photo: Summit Computer Room Installation (rubin-2018-05-02-192537) by Rubin Observatory/NSF/AURA, CC BY 4.0, via Wikimedia Commons.

Traefik and Caddy both do this well enough for the overwhelming majority of homelab setups, and their automatic HTTPS story genuinely beats HAProxy’s out of the box. HAProxy earns its place once the distribution logic itself needs fine-grained control — weighted algorithms, detailed per-backend health checks with configurable failure thresholds, and connection-level statistics that make debugging an unbalanced backend pool considerably less guesswork than watching aggregate request counts and guessing.

Basic configuration

HAProxy’s config splits into global (process-level settings), defaults (settings inherited by everything below), frontend (where traffic arrives) and backend (where it’s sent) sections:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
global
    maxconn 4096
    log stdout format raw local0

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

frontend web
    bind *:80
    default_backend app_servers

backend app_servers
    balance roundrobin
    server app1 192.168.1.11:8080 check
    server app2 192.168.1.12:8080 check
    server app3 192.168.1.13:8080 check

That’s a complete, working load balancer: three backend app servers, round-robin distribution, and check on each server line enabling active health checking with HAProxy’s defaults. It reads more like a description of the topology than a set of routing rules, which is the config style that takes some adjustment coming from label-based systems like Traefik but becomes genuinely easy to reason about once it clicks — every section maps directly onto a real piece of the network path.

Load-balancing algorithms

balance roundrobin in the example above is one of several algorithms HAProxy supports, each suited to different backend behaviour:

1
2
3
4
backend app_servers
    balance leastconn
    server app1 192.168.1.11:8080 check
    server app2 192.168.1.12:8080 check

leastconn routes new connections to whichever backend currently has the fewest active connections, which suits backends with widely varying request durations far better than round-robin — a backend stuck on a slow request under round-robin still gets its fair share of new connections piled on top, while leastconn naturally routes around it. source hashes on the client’s source IP for session affinity without cookies, useful for stateful backends that expect a client to keep talking to the same server. uri hashes on the request path, which is the right choice for a caching layer where you want the same URL consistently landing on the same backend to maximise cache hits.

1
2
3
4
5
backend app_servers
    balance uri
    hash-type consistent
    server cache1 192.168.1.21:8080 check
    server cache2 192.168.1.22:8080 check

hash-type consistent matters specifically for that caching case: without it, adding or removing a single backend reshuffles which requests map to which server across the whole hash space, which for a caching layer means a mass cache-miss event on any topology change. Consistent hashing limits the reshuffling to roughly the fraction of traffic that belonged to the added or removed server.

Health checks that actually mean something

The check keyword in the earlier examples enables the simplest form — a TCP connection attempt on the configured port. HAProxy’s health checks go considerably further than that when the backend can support it:

1
2
3
4
backend app_servers
    option httpchk GET /healthz
    http-check expect status 200
    server app1 192.168.1.11:8080 check inter 5s fall 3 rise 2

option httpchk switches to an actual HTTP request against a health endpoint rather than just confirming the port accepts connections — a backend can accept TCP connections while its application logic is completely broken, so an HTTP-level check that expects a specific status code catches failures a bare TCP check misses entirely. inter 5s sets the check interval, fall 3 requires three consecutive failures before marking a server down (avoiding a single blip taking it out of rotation), and rise 2 requires two consecutive successes before bringing a recovered server back in, which prevents a server that’s still warming up from immediately taking a full share of traffic the moment it starts responding again.

The stats page

HAProxy ships a built-in stats interface that’s worth enabling on every instance, homelab or otherwise — it’s the fastest way to see exactly what the load balancer thinks is happening, backend by backend, without reaching for external monitoring:

1
2
3
4
5
6
frontend stats
    bind *:8404
    stats enable
    stats uri /stats
    stats refresh 10s
    stats auth admin:changeme

Pointing a browser at that URL shows every backend’s current status (up, down, or draining), request counts, error rates, response times and current connection counts, refreshed live. For diagnosing an unevenly loaded backend pool or confirming a health check is actually catching the failure mode you expect, this single page has saved me more debugging time than any external tool pointed at the same problem.

Why the config style has stayed this way for two decades

HAProxy’s config format hasn’t chased the label-based or annotation-driven styles that Traefik and Kubernetes ingress controllers popularised, and that’s a deliberate choice rather than neglect — the project’s maintainers have been explicit for years that a single, explicit config file that reads top-to-bottom as a description of the actual traffic path is easier to audit and reason about under pressure than dynamic configuration scattered across container labels or annotations in a dozen different manifest files. When something is actively misrouting traffic during an incident, being able to read one file and see exactly where every request goes is worth more than the convenience of config-as-labels most of the time.

That trade-off is also why HAProxy pairs so well as the layer behind a more dynamic edge proxy rather than replacing it outright: Traefik or an ingress controller can handle the churn of containers starting and stopping, discovering new backends automatically, while HAProxy’s static, auditable config handles the smaller number of genuinely stable backend pools that actually need its more sophisticated balancing logic.

TLS termination

HAProxy handles TLS termination directly, though — unlike Caddy — it doesn’t provision certificates automatically; you’re supplying certs from somewhere else, typically an ACME client like certbot running separately or a certificate from an internal CA.

1
2
3
4
5
6
7
frontend web-tls
    bind *:443 ssl crt /etc/haproxy/certs/example.com.pem
    default_backend app_servers

frontend web
    bind *:80
    redirect scheme https code 301

That’s a meaningfully heavier setup step than Caddy’s automatic HTTPS, and it’s the single biggest reason I still run Caddy in front of small personal services where zero-config TLS matters more than fine-grained load-balancing control. The two aren’t mutually exclusive either — a common pattern is Caddy or Traefik handling TLS and simple routing at the edge, with HAProxy behind it doing the actual load-balancing work across a backend pool that needs its more sophisticated health checks and algorithms.

ACLs and content-based routing

HAProxy’s ACL system is where the config language stops looking like plumbing and starts looking like a small routing language — conditions matched against the request, combined into rules that decide where traffic goes:

1
2
3
4
5
6
7
frontend web
    bind *:80
    acl is_api path_beg /api/
    acl is_websocket hdr(Upgrade) -i websocket
    use_backend api_servers if is_api
    use_backend websocket_servers if is_websocket
    default_backend web_servers

That’s routing by path prefix and by header value in the same frontend, directing API traffic, WebSocket upgrades and everything else to three different backend pools from one entry point. ACLs can match on nearly anything HAProxy can see in a request — headers, cookies, source IP, SSL SNI, request method — and combine with and/or for rules more specific than a single condition, which covers a lot of routing logic that would otherwise need a separate reverse proxy layer in front of the load balancer.

Stick tables for rate limiting and abuse control

Beyond routing and health checks, HAProxy’s stick tables track per-client state across requests — connection counts, request rates, error rates — directly in the load balancer, without needing an external tool to enforce it:

1
2
3
4
5
6
frontend web
    bind *:80
    stick-table type ip size 100k expire 30s store http_req_rate(10s)
    http-request track-sc0 src
    http-request deny deny_status 429 if { sc_http_req_rate(0) gt 20 }
    default_backend web_servers

That configuration tracks request rate per source IP over a ten-second window and rejects with a 429 once a client exceeds twenty requests in that window — a working rate limiter in five lines, entirely within the load balancer’s own config, with no separate rate-limiting service to run and keep in sync. It’s a genuinely useful line of defence against runaway clients or basic scraping before requests ever reach a backend that has to spend real resources handling them.

Troubleshooting

Config changes not taking effect — HAProxy needs an explicit reload (systemctl reload haproxy or haproxy -sf $(pidof haproxy) -f /etc/haproxy/haproxy.cfg), and unlike some proxies it validates the entire config file before reloading, refusing to apply a broken config rather than reloading into a half-working state. Run haproxy -c -f /etc/haproxy/haproxy.cfg to check syntax before every reload — catching a typo this way beats discovering it mid-outage.

A backend marked down that’s actually healthy — check what the health check is actually hitting. A common mistake is an httpchk path that requires authentication or returns a redirect instead of a direct 200, both of which HAProxy correctly interprets as a failed check even though a browser hitting the same URL would eventually succeed after following the redirect or logging in.

Uneven load despite round-robin — persistent or long-lived connections (WebSockets, long-polling, HTTP/2 multiplexed streams) don’t redistribute the way round-robin assumes; a handful of long-lived connections established early can leave one backend permanently more loaded than the others for as long as those connections stay open. Switching to leastconn for backend pools with long-lived connections usually fixes this better than tuning round-robin ever will.

Reload dropping in-flight connections — a plain systemctl restart tears down existing connections along with the old process; -sf (“seamless finish”) on the command line, or the reload mechanism most init systems wire up for HAProxy by default, starts a new process that takes over the listening sockets while the old one finishes serving its existing connections before exiting. Confirming your init system is actually invoking -sf rather than a plain stop-and-start is worth checking once, since silently dropping connections on every config change is the kind of thing that only shows up as a mysterious blip in error rates rather than an obvious failure.

Is it worth the config file

For a homelab with a handful of simple services behind a proxy, Caddy or Traefik remain the better default — the automatic HTTPS and simpler config outweigh HAProxy’s extra sophistication when you don’t need it. Once you’re actually load-balancing across multiple backend instances of the same service and the distribution logic itself matters, HAProxy’s health checks and algorithm choices are worth the steeper config syntax. It pairs naturally with keepalived and virtual IPs for high availability for removing the load balancer itself as a single point of failure, and it’s worth comparing directly against Caddy and Traefik as reverse proxies before deciding which layer of the stack each tool should own. The underlying idea is laid out in Load Balancing Is Just a Bouncer With a Clipboard, which treats a load balancer as a bouncer deciding which door a request goes through.

Smarc
Written by Smarc

Founder and editor of Aside House. A lifelong tinkerer who self-hosts far more than is sensible, hardens Linux boxes for fun, and prods the latest AI tools to see what they can really do. The how-to guides here are the notes Smarc wishes had existed the first time round.

Smarc is the editor of Aside House. The homelab, the hardware and the opinions are real; the guides are drafted with AI assistance. Infrastructure details are genericised on purpose.