Nginx and HAProxy Load Balancing
Once we were approached by a project with five servers: at a peak of 3000 RPS, some requests returned 503 due to suboptimal distribution. After implementing load balancing with active health checks and least-connections, the load distributed evenly, and uptime rose to 99.99%. We configure load balancing that distributes requests across multiple backends, eliminates single points of failure, and enables scaling without service interruption. Over 5+ years, we have completed more than 50 projects with high-load infrastructure, where peak load reached 30,000 RPS, and none went down after load balancing was deployed.
What Problems Does Load Balancing Solve?
Load balancing addresses three key tasks. First, fault tolerance: when one backend fails, traffic is automatically redirected to others, achieving uptime of 99.95%. Second, horizontal scaling: servers can be added on the fly without restarting the load balancer. Third, optimal load distribution: algorithms like least-connections and weighted round-robin spread requests evenly, preventing overload of individual nodes.
Why Are Health Checks Important and How to Configure Them?
Without health checks, the load balancer continues sending requests to a failed server, causing errors for some users. Passive checks (built into Nginx) exclude a server after a certain number of errors within a given interval. Active checks (HAProxy, Nginx Plus) poll the /health endpoint every 2–3 seconds and instantly exclude a problematic backend. In a project with 10,000 RPS, replacing passive checks with active ones reduced 5xx errors by 80%.
Comparison of Nginx and HAProxy
| Parameter | Nginx | HAProxy |
|---|---|---|
| Max RPS | ~20,000 | ~50,000+ |
| Health checks | Passive (free) / Active (Plus) | Active built-in |
| ACL/routing | Limited (location) | Flexible ACLs, use_backend |
| Statistics | Basic (stub_status) | Detailed (stats) |
| SSL termination | Yes (built-in) | Yes (built-in) |
| Sticky sessions | ip_hash | cookie insert |
| TCP balancing | stream module | Yes (mode tcp) |
HAProxy handles up to 50,000 RPS—roughly 2.5 times more than Nginx in balancing mode. Moreover, HAProxy detects failures faster thanks to active checks: according to the official HAProxy documentation, the time to detect a failed server is reduced to 2 seconds.
How to Choose Between Nginx and HAProxy?
The choice depends on load and additional requirements. Nginx is suitable if you need a web server and load balancer in one, with load up to 20,000 RPS. HAProxy is for pure balancing with high performance (up to 50,000+ RPS) and flexible ACLs. In one project, replacing Nginx with HAProxy reduced latency by 20% thanks to fast health checks and least-connections.
Configuring Load Balancing with Nginx
Nginx is a versatile tool: it works both as a web server and as a load balancer. For 5–20 backends, its capabilities are sufficient. A basic config includes an upstream block with keepalive and proxying with timeouts:
upstream myapp_backend {
server 10.0.1.10:8080;
server 10.0.1.11:8080;
server 10.0.1.12:8080;
keepalive 32;
}
server {
listen 443 ssl http2;
server_name example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
location / {
proxy_pass http://myapp_backend;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_connect_timeout 5s;
proxy_read_timeout 60s;
proxy_next_upstream error timeout http_502 http_503;
}
}
For high loads, we use least-connections or ip-hash algorithms (for sticky sessions). Backup servers and passive health checks are configured via max_fails and fail_timeout parameters.
Configuring Load Balancing with HAProxy
HAProxy is a specialized load balancer for loads from 10,000 RPS. It offers flexible ACLs, detailed statistics, and active health checks. Example config for a web application and API:
global
maxconn 100000
nbthread 4
stats socket /run/haproxy/admin.sock mode 660 level admin
defaults
mode http
timeout connect 5s
timeout client 30s
timeout server 60s
frontend http_front
bind *:80
bind *:443 ssl crt /etc/haproxy/certs/example.com.pem alpn h2,http/1.1
acl is_api path_beg /api/
use_backend api_backend if is_api
default_backend web_backend
backend web_backend
balance leastconn
option httpchk GET /health
cookie SERVERID insert indirect nocache
server web01 10.0.1.10:8080 check inter 3s rise 2 fall 3 cookie web01
server web02 10.0.1.11:8080 check inter 3s rise 2 fall 3 cookie web02
backend api_backend
balance roundrobin
server api01 10.0.2.10:3000 check inter 2s
server api02 10.0.2.11:3000 check inter 2s
HAProxy supports SSL termination (combining certificate and key into a single PEM file), TCP balancing for databases and WebSocket, and built-in statistics on port 8404.
How to Set Up High Availability with Keepalived?
To prevent the load balancer itself from becoming a single point of failure, we configure a Keepalived pair with a floating VIP. When the primary balancer fails, the backup takes over the IP within seconds, ensuring 99.99% uptime. The configuration includes a VRRP instance with an advertisement interval of 1 second and tracking of the HAProxy process.
What Is Included in the Setup?
- Audit of the current architecture: servers, applications, bandwidth.
- Design of the balancing scheme: algorithm selection, health checks, SSL termination.
- Configuration of upstream and backup servers.
- Development of scripts for dynamic backend updates (if required).
- Load testing up to 100,000 RPS.
- Operations documentation and instructions for the on-call team.
- 3-month warranty on the load balancer's uninterrupted operation.
Process and Timelines
| Stage | Duration |
|---|---|
| Audit and design | 1–2 days |
| Nginx + SSL | 1–2 days |
| HAProxy + ACLs + statistics | 2–3 days |
| Keepalived | +1 day |
| Dynamic updates | +1–2 days |
| Testing and documentation | 1–2 days |
The full cycle takes from 3 to 6 working days, depending on complexity.
Common Configuration Mistakes
| Mistake | Consequences | Solution |
|---|---|---|
| No health checks | Traffic to dead backend, 5xx errors | Configure active checks |
| Too small timeouts (<30s) | Timeouts on long requests | Increase proxy_read_timeout to 60–120s |
| Incorrect sticky session config | Sessions hop between servers | Enable cookie insert with proper parameter |
Savings on server infrastructure after implementing load balancing reach up to 40%, and downtime decreases by 95%. Get a consultation from a load balancing engineer—we will analyze your architecture and choose the optimal solution. Contact us for an assessment of your project.
Example of a dynamic upstream update script for Nginx
import subprocess
import boto3
def update_nginx_upstream():
ec2 = boto3.client('ec2', region_name='eu-west-1')
response = ec2.describe_instances(Filters=[
{'Name': 'tag:Role', 'Values': ['app']},
{'Name': 'instance-state-name', 'Values': ['running']},
])
ips = [i['PrivateIpAddress'] for r in response['Reservations'] for i in r['Instances']]
config = "upstream myapp_backend {\n" + "\n".join(f" server {ip}:8080;" for ip in ips) + "\n keepalive 32;\n}\n"
with open('/etc/nginx/conf.d/upstream.conf', 'w') as f:
f.write(config)
subprocess.run(['nginx', '-t'], check=True)
subprocess.run(['nginx', '-s', 'reload'], check=True)
We guarantee 99.99% uptime and provide post-deployment support. Our engineers hold Nginx and HAProxy certifications. Request a consultation right now.







