1. Performance optimization #
Making sure HAProxy makes the best use of available resources to handle traffic.
Global settings and reuse #
To get the most out of HAProxy, some global settings are essential to limit the load on backends and ensure network resilience.
- Maxconn: sets the global connection limit (e.g. 10,000).
Advantage: protects the system against RAM and file descriptor exhaustion.
Risk: if the value is too low, HAProxy will reject legitimate clients during traffic peaks. - Keep-alive: enable
option http-keep-alive.
Advantage: reduces latency by reusing existing TCP connections (avoids repeated 3-way handshakes).
Risk: can keep too many connections open on limited backend servers if the timeout is too long. - Retries & redispatch:
Advantage: improves the availability perceived by the user. If a server goes down right at the time of the request, HAProxy retries on another one.
Risk: can worsen a cluster's overload if servers are going down because of saturation (cascade effect).
global
maxconn 10000
log stdout format raw local0
defaults
option http-keep-alive
retries 3
option redispatch
Optimizing timeouts #
A frequent mistake is keeping the default values. You should define explicit timeouts.
- Standard values: 5s for connect, 30s for client and server.
Advantage: quickly frees resources held by sluggish clients or servers.
Risk: a server timeout that is too short will cut large file transfers or long exports. - Slowloris protection: keep a short
timeout http-request(5s).
Advantage: prevents an attacker from saturating connections by sending headers very slowly.
defaults
timeout connect 5s
timeout client 30s
timeout server 30s
backend slow_api
timeout server 2m
Choosing the right algorithm #
The choice of algorithm directly affects how your resources are used and the quality of the user experience. To dig into the theory, read our article: Load balancing: principles, algorithms and use cases.
- Round robin:
Advantage: simple, perfectly fair if requests are homogeneous.
Risk: inefficient if some servers are more powerful than others or if some requests are much heavier. - Least connections:
Advantage: the smartest algorithm from an APM point of view; it avoids sending traffic to a server that is already struggling.
Risk: less efficient on very short flows because counting connections adds slight overhead. - Source hash:
Advantage: persistence without injecting cookies.
Risk: imbalance if many users come out of the same corporate proxy/NAT (a single IP for thousands of clients).
2. Security and hardening #
Protecting your applications against common threats with HAProxy.
TLS/SSL management #
TLS encryption is fundamental for communication security. HAProxy lets you centralize SSL termination.
- HTTP/2 through ALPN:
Advantage: speeds up page loading through multiplexing.
Risk: uses a bit more CPU on HAProxy to manage streams. - HSTS:
Advantage: prevents SSL downgrade attacks (man-in-the-middle).
Risk: if you lose your certificates or want to go back to HTTP, browsers will block access until the max-age expires (often 1 year).
Disabling obsolete protocols #
To protect your traffic against protocol vulnerabilities (POODLE, BEAST), you must limit the accepted protocols.
- TLS 1.2 / 1.3 only:
Advantage: maximum security level, compliant with PCI-DSS / GDPR standards.
Risk: incompatible with very old clients (old payment terminals, old Android/IE browsers).
global
ssl-default-bind-options no-sslv3 no-tlsv10 no-tlsv11
Protection against attacks (DDoS, Slowloris) #
HAProxy can act as a first line of defense against DDoS or Slowloris attacks through stick-tables.
- Rate limiting:
Advantage: automatically blocks IPs that saturate the service before they reach your servers.
Risk: false positives (e.g. a school or company using a single public IP will be blocked if too many users browse at the same time).
WAF (Web Application Firewall) best practices #
HAProxy can inspect request content to block SQL injection or XSS attempts.
- Method filtering:
Advantage: reduces the attack surface by forbidding methods such asPUTorDELETEif they are not used.
Risk: can break some modern API features if the configuration is not kept up to date. - Payload inspection:
Advantage: blocks known attacks at layer 7.
Risk: significant CPU impact if the inspection rules (regex) are too complex or too numerous.
ACL best practices #
ACLs are the decision engine. Rigorous management avoids routing errors.
- Naming:
Advantage: makes logs easier to read and troubleshooting easier.
Risk: vague ACL names (e.g.acl test) make the configuration unreadable and dangerous. - Externalization (maps):
Advantage: lets you update lists (e.g. allowed domains) without changing the main file, and sometimes without a reload through the Runtime API.
Risk: requires rigorous management of external files to avoid missing files at startup.
3. High availability and resilience #
Ensuring service continuity and the robustness of your infrastructure.
Configuring health checks #
Health checks avoid sending clients to a 'zombie' server (port open but application crashed).
- Application check (HTTP):
Advantage: guarantees that the application really responds (e.g. database connected).
Risk: if the health endpoint is too complex, the check itself can slow down the backend (avoid heavy computation in/health).
backend app_servers
option httpchk GET /health
http-check expect status 200
server s1 10.0.0.1:80 check inter 2s fall 3 rise 2
Managing backup servers and maintenance #
Always plan an emergency exit.
- Backup server:
Advantage: avoids a total 503 error page. Can be used to display a 'degraded' static site.
Risk: if the backup is never tested, it may fail exactly when you need it. - Maintenance page:
Advantage: clean communication with users during major incidents.
Risk: if poorly configured, it can prevent search engine crawlers (SEO) from understanding that the site will come back.
4. Organization and modularity #
Structuring your configuration to make automation and maintenance easier.
Separating blocks and using multiple files #
In a complex infrastructure, having a single 3,000-line file is a major bad practice.
- Logical separation: the Global and Defaults sections must be isolated from business routing.
- Includes: use directories (e.g.
conf.d/) to load your backends per application.
Advantage: lets you deploy a new application (new file) through CI/CD without risking corrupting another service's ACLs.
Risk: HAProxy loads files in alphabetical order. The Global > Defaults > Frontend > Backend order must be respected.
# Lancer HAProxy en chargeant un répertoire
haproxy -f /etc/haproxy/haproxy.cfg -f /etc/haproxy/conf.d/5. Operational maintenance and high availability #
Managing updates and eliminating single points of failure (SPOF).
Hot reload (zero downtime) #
To apply a change without disconnecting users, never restart the service. You must reload it:
systemctl reload haproxy or, in the Docker world for example: sudo docker compose kill -s HUP haproxy- Master-worker mode: use the modern mode (the standard under systemd), which hands the listening sockets over to the new processes.
- Advantage: long sessions (WebSockets, transfers) finish normally on the old process while the new one takes the new calls.
Risk: if there is a syntax error, the reload fails. Always test first:haproxy -c -f /etc/haproxy/haproxy.cfg.
Network high availability (Keepalived) #
If HAProxy goes down, your application is unreachable. The solution is to set up a redundant HAProxy cluster.
- VIP (virtual IP): a floating IP address is managed by Keepalived through the VRRP protocol.
- How it works: if the 'master' HAProxy stops responding, the VIP instantly fails over to the 'backup'.
Advantage: eliminates the hardware or software SPOF.
Risk: 'split-brain' (both nodes believe they are master) can happen if the network link between them is unstable, causing IP conflicts.
Logging and monitoring #
Use detailed logs for application debugging.
frontend http_front
# Capture le Host et le User-Agent pour l'analyse
capture request header Host len 64
capture request header User-Agent len 128
