What we're actually comparing
HAProxy and Nginx get lumped together constantly, and that's the first problem. HAProxy was built from day one as a load balancer and proxy. Nginx started life as a web server that happened to be very good at proxying, and it grew load balancing features around that core. Both can sit in front of a pool of application servers and spread traffic across them. Both are fast, free, and battle-tested. But they come from different philosophies, and those differences show up the moment you stop serving a demo and start running production traffic.
In my experience, the question "which one is better?" is the wrong question. The useful question is "what is this box going to do besides balancing?" If it also needs to serve static files, cache responses and rewrite URLs, Nginx earns its place. If its only job is to distribute connections intelligently, shed bad backends fast and tell you exactly what's happening, HAProxy usually wins. Let's go through why.
How each one works under the hood
Nginx uses a master process and a set of worker processes. Each worker runs an event loop, handles thousands of connections, and shares nothing with its siblings except a small shared memory zone. That model is simple and scales across cores nicely. State that needs to be global, like rate limit counters or upstream health data, has to live in those shared memory zones, which you declare explicitly.
HAProxy runs a single process with multiple threads (since the 1.8 era, and it's the default model in current releases). Threads share memory directly, so things like stick tables, health check state and server weights are global by design. There's no worry about each worker having its own view of a backend. HAProxy also treats the proxy sections as first-class concepts:
frontend,
backend,
listen. You describe a traffic flow, and the config reads like the flow.
Here's a minimal HAProxy setup for a three-node application pool on sw-infrarunbook-01:
global
log /dev/log local0
maxconn 50000
nbthread 4
defaults
mode http
log global
option httplog
timeout connect 5s
timeout client 30s
timeout server 30s
frontend fe_web
bind 10.10.10.5:80
default_backend be_app
backend be_app
balance leastconn
option httpchk GET /healthz
http-check expect status 200
server app1 10.10.20.11:8080 check inter 2s fall 3 rise 2
server app2 10.10.20.12:8080 check inter 2s fall 3 rise 2
server app3 10.10.20.13:8080 check inter 2s fall 3 rise 2And the equivalent in Nginx:
upstream be_app {
least_conn;
server 10.10.20.11:8080 max_fails=3 fail_timeout=10s;
server 10.10.20.12:8080 max_fails=3 fail_timeout=10s;
server 10.10.20.13:8080 max_fails=3 fail_timeout=10s;
keepalive 64;
}
server {
listen 10.10.10.5:80;
server_name app.solvethenetwork.com;
location / {
proxy_pass http://be_app;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_set_header Host $host;
}
}They look similar until you read the health check lines closely. That difference is where many real incidents begin.
Health checks: the biggest practical gap
HAProxy actively probes every server. It sends a request on a timer, expects a defined answer, and marks the server down after a set number of failures. It can run HTTP checks, TCP checks, or protocol-aware checks for things like MySQL, Redis and SMTP. A backend that's dying gets pulled before a customer ever hits it.
Nginx open source does passive checking only. A server gets marked as failed only after real client requests to it fail,
max_failstimes within
fail_timeout. That means real users absorb the first failures. Active health checks exist in the commercial NGINX Plus product, and third-party modules can bolt them on, but out of the box you're relying on user traffic as your canary.
I have seen this happen when an application server's database connection pool exhausted itself. The process was up, the port was open, and it returned 500s on every request. With HAProxy and an
httpchkhitting a real health endpoint, the node was out of rotation in six seconds. On the Nginx side of the same estate, a slice of users saw errors until the passive thresholds tripped, and then the server came back after
fail_timeoutexpired, only to fail again. You can tune around it with
proxy_next_upstreamretries, but retrying non-idempotent requests carries its own risk.
Balancing algorithms and persistence
Both support round robin, least connections and hash-based selection. HAProxy offers
roundrobin,
static-rr,
leastconn,
source,
uri,
url_param,
hdr(),
randomand consistent hashing via
hash-type consistent. Nginx offers round robin,
least_conn,
ip_hash, generic
hash(with an optional
consistentflag) and
random two least_conn.
For stateless services the choice rarely matters much. Where it does matter is session persistence. HAProxy can insert its own cookie, learn an application's session cookie, or key persistence off a stick table entry. Open source Nginx is mostly limited to
ip_hashor a hash on a variable you choose. That works, but it falls apart behind NAT, where thousands of users share one source address and land on a single backend.
Stick tables, rate limiting and traffic shaping
Stick tables are the HAProxy feature I miss most when I'm on other platforms. A stick table is an in-memory key-value store that tracks things per client: request rate, connection count, error rate, bytes transferred. You can then make routing and blocking decisions on those counters, in real time, shared across all threads.
frontend fe_web
bind 10.10.10.5:443 ssl crt /etc/haproxy/certs/solvethenetwork.com.pem
stick-table type ip size 200k expire 5m store http_req_rate(10s),conn_cur
http-request track-sc0 src
http-request deny deny_status 429 if { sc_http_req_rate(0) gt 100 }
http-request deny deny_status 429 if { sc_conn_cur(0) gt 50 }
default_backend be_appThat's per-client rate limiting and connection capping in four lines, and the same table can feed ACLs, stats and the runtime API. Nginx does have
limit_reqand
limit_conn, which are perfectly good for straightforward cases. They use a leaky bucket model with shared memory zones, and for protecting a login endpoint they're often all you need. But they're counters you configure, not a general-purpose state store you can query and manipulate while the process is running.
Layer 4 and Layer 7
HAProxy handles both TCP and HTTP in the same configuration with the
modekeyword. Balancing a PostgreSQL replica set or an MQTT broker is the same shape of config as balancing a web app. Nginx does TCP and UDP through its separate
streammodule, with a separate context and a reduced feature set. It works fine, but I find myself reaching for HAProxy whenever the backend isn't HTTP, because the health checks, ACLs and logging all carry over.
For HTTP, Nginx is stronger at the application edge: caching, response buffering, static file serving, and a huge ecosystem of modules and Lua or njs scripting. HAProxy's HTTP rewriting, ACL engine and Lua support are very capable, but it has no built-in static file serving, and it doesn't cache the way Nginx's
proxy_cachedoes (it has a small object cache, but that's not the same thing).
Observability and runtime control
This is the part that changes how you operate the thing at 3 a.m. HAProxy ships with a stats page and a runtime API over a Unix socket. You can drain a server, change a weight, disable a backend or inspect a stick table without reloading anything.
listen stats
bind 10.10.10.5:8404
stats enable
stats uri /stats
stats refresh 5s
stats auth infrarunbook-admin:ChangeMeNow
# drain a server without a reload
echo "set server be_app/app2 state drain" | socat stdio /run/haproxy/admin.sock
# watch the abusive clients
echo "show table fe_web" | socat stdio /run/haproxy/admin.sockThe log format matters too. HAProxy's HTTP log line includes timing breakdowns: time waiting for the client, time to connect to the backend, time to first response byte, and a termination state code that tells you who closed the connection and why. A line ending in
sH--versus
cD--immediately tells you whether the server timed out or the client walked away. Nginx's access log is flexible, and you can build a similar format with
$upstream_connect_timeand
$upstream_response_time, but you assemble it yourself and you won't get the termination reasons. Open source Nginx also exposes only a minimal
stub_statuspage, with much richer live metrics reserved for NGINX Plus.
Config changes differ as well. Nginx reloads gracefully: new workers start, old ones finish their connections. HAProxy also does seamless reloads, and with the runtime API a lot of changes never need one. When I'm managing a fleet where backends come and go, being able to add and remove servers on a live process is a real advantage.
Performance: what the numbers really say
Let me be straight about this, because benchmark posts are mostly noise. Both proxies can saturate a 10 Gbps link on modest hardware when they're tuned properly. On a typical 8 core VM, I've pushed either one past tens of thousands of requests per second for small responses before the application tier, not the proxy, became the bottleneck. If you're picking between them on raw throughput, you're solving a problem you probably don't have.
The differences are subtler. HAProxy tends to show lower and more consistent tail latency under heavy connection churn and high concurrency, largely because its scheduler and shared-memory design are built around exactly that workload. Nginx shines when it's serving cached or static content from memory or disk, because that's work HAProxy simply doesn't do. TLS termination performance is comparable, since both lean on OpenSSL (or a compatible library) and both support session resumption, OCSP stapling and modern protocols including HTTP/2, with HTTP/3 over QUIC supported in current releases of each.
What actually matters for performance is configuration. A few rules I follow on either platform:
- Keep connections to backends alive. In Nginx that means
keepalive
in the upstream block plus HTTP/1.1 and a clearedConnection
header. In HAProxy it'soption http-reuse safe
or stronger. - Set connection limits deliberately. HAProxy's
maxconn
at global, frontend and server level prevents a spike from flattening a backend. Nginx hasworker_connections
and per-servermax_conns
. - Match thread or worker count to real CPU cores, and watch for noisy neighbors on virtualized hosts.
- Raise file descriptor limits. Both will fail in confusing ways when
ulimit -n
is too low.
Real-world examples
A pattern I've deployed several times: HAProxy as the front door on a pair of hosts running Keepalived with a floating address, terminating TLS and routing by ACL to different pools. API traffic goes to one backend, the admin UI to another, with the stick table guarding against abuse. Behind that, some of the application pools are fronted by their own Nginx instances that serve static assets and cache. It's not over-engineering; each tool does the job it's best at.
frontend fe_https
bind 10.10.10.5:443 ssl crt /etc/haproxy/certs/solvethenetwork.com.pem alpn h2,http/1.1
acl is_api path_beg /api/
acl is_admin hdr(host) -i admin.solvethenetwork.com
use_backend be_api if is_api
use_backend be_admin if is_admin
default_backend be_webThe opposite case is just as real. A small team running a handful of sites on one server, needing a reverse proxy, TLS, gzip, caching and a bit of load balancing across two app nodes. Installing HAProxy in addition to Nginx would add a component for little gain. Nginx handles it all, and the passive health checks are acceptable when the two nodes are well monitored by something else. I wouldn't argue for HAProxy there.
One more scenario worth describing: a database proxy tier. A team had Nginx's stream module sending connections to three read replicas with no real health awareness, so a lagging replica kept receiving queries. Moving to HAProxy with a protocol-aware check and a custom check script that read replication lag meant unhealthy replicas dropped out automatically. That's a case where the feature gap wasn't theoretical.
Common misconceptions
"Nginx is faster." Not in a way you'll notice for load balancing. Both are limited by network, TLS and your backends long before the proxy runs out of steam. The reputation comes partly from static file serving, which is a different job.
"HAProxy can't do HTTP properly." That was a fair criticism in the very early days. It's been a full HTTP/1, HTTP/2 and HTTP/3 capable proxy for years, with powerful header manipulation and ACLs.
"Nginx can't do health checks." It can, passively, and NGINX Plus does them actively. The open source build just won't probe a server on its own, and that distinction matters when you design for failure.
"You have to pick one." You really don't. Stacking them is common and sensible. Just don't add layers that don't earn their keep, because every proxy hop is another thing to monitor, another timeout to align and another place for a 502 to come from.
"Config complexity decides it." Nginx's config feels familiar if you've written web server configs. HAProxy's feels familiar if you think in terms of traffic flows. Neither is harder once you've written a few; the cost is in learning the mental model, not the syntax.
My recommendation
If the machine's job is load balancing, especially across mixed protocols, with serious needs around health detection, persistence, rate limiting and visibility, I reach for HAProxy. If the machine is a web server first and a balancer second, or you need caching and static content in the same process, Nginx is the sensible choice. And if your requirements sit in the middle, pick the one your team already knows how to debug at 3 a.m. That operational familiarity is worth more than any benchmark chart.
