Part 1: Foundational Load Balancing
1. Basic HTTP Load Balancing
frontend web_frontend
bind *:80
default_backend web_servers
backend web_servers
balance roundrobin
server web1 192.168.1.10:80 check
server web2 192.168.1.11:80 check
server web3 192.168.1.12:80 check
2. TCP Load Balancing
frontend tcp_frontend
bind *:3306
mode tcp
default_backend mysql_cluster
backend mysql_cluster
mode tcp
balance leastconn
server mysql1 192.168.1.20:3306 check
server mysql2 192.168.1.21:3306 check
3. SSL/TLS Termination
frontend https_frontend
bind *:443 ssl crt /etc/haproxy/certs/domain.pem
http-request redirect scheme https unless { ssl_fc }
default_backend web_servers
4. SSL Passthrough
frontend ssl_passthrough
bind *:443
mode tcp
tcp-request inspect-delay 5s
tcp-request content accept if { req_ssl_hello_type 1 }
use_backend backend1 if { req_ssl_sni -i app1.example.com }
use_backend backend2 if { req_ssl_sni -i app2.example.com }
5. Health Checking
backend app_servers
option httpchk GET /health
http-check expect status 200
default-server check fall 3 rise 2
server app1 192.168.1.30:8080 check port 8080
server app2 192.168.1.31:8080 check port 8080
6. Session Persistence
backend app_servers
balance roundrobin
cookie SERVERID insert indirect nocache
server app1 192.168.1.40:80 cookie s1 check
server app2 192.168.1.41:80 cookie s2 check
7. Layer 7 URL Path Routing
frontend http_frontend
bind *:80
acl is_api path_beg /api/
acl is_static path_beg /static/ /images/
acl is_admin path_beg /admin/
use_backend api_servers if is_api
use_backend static_servers if is_static
use_backend admin_servers if is_admin
default_backend web_servers
8. Layer 4 IP/Port Routing
frontend multi_port
bind *:80
bind *:8080
acl port_8080 dst_port 8080
use_backend backend_8080 if port_8080
default_backend backend_80
Part 2: Security & Access Control
9. WAF Integration
frontend web
bind *:80
# Forward to WAF first
use_backend waf_backend
backend waf_backend
server waf 192.168.1.50:80
# Then to actual servers
use_backend actual_servers if { req.hdr(X-WAF-Status) -i passed }
10. Rate Limiting
frontend web
bind *:80
# 10 requests per minute per IP
stick-table type ip size 100k expire 1m store http_req_rate(60s)
http-request track-sc0 src
http-request deny deny_status 429 if { sc_http_req_rate(0) gt 10 }
11. DDoS Protection
frontend web
bind *:80
# Connection limiting
maxconn 10000
# Per-IP connection limiting
stick-table type ip size 200k expire 30s store conn_cur
tcp-request connection track-sc0 src
tcp-request connection reject if { sc_conn_cur(0) gt 50 }
# Tarpitting (slow down attackers)
tcp-request content tarpit if { src_get_gpc0 gt 2 }
12. IP Whitelisting/Blacklisting
frontend web
bind *:80
acl trusted_networks src 192.168.1.0/24 10.0.0.0/8
acl blocked_ips src 203.0.113.1 198.51.100.50
http-request deny if blocked_ips
http-request deny if !trusted_networks
13. Basic HTTP Authentication
frontend web
bind *:80
acl auth_ok http_auth(admin_users)
http-request auth realm "Admin Area" unless auth_ok
userlist admin_users
user admin1 password $6$encrypted_password_hash
user admin2 insecure-password plaintextpass
14. Geolocation-Based Access
frontend web
bind *:80
# Load GeoIP database
geolite2-country /etc/haproxy/geoip/GeoLite2-Country.mmdb
# Block specific countries
acl country_blocked src_cntry(RU,CN,IR)
http-request deny if country_blocked
# Allow only specific countries
acl country_allowed src_cntry(US,CA,GB)
http-request deny if !country_allowed
15. Bot Management
frontend web
bind *:80
# Common bot user agents
acl is_bot hdr_sub(User-Agent) -i bot spider crawler scrape
# Challenge suspected bots
http-request deny if is_bot { path_beg /api/ }
# Rate limit bots more aggressively
stick-table type ip size 100k expire 5m store http_req_rate(60s)
http-request track-sc0 src if is_bot
http-request deny if is_bot { sc_http_req_rate(0) gt 5 }
16. Hide Backend Headers
frontend web
bind *:80
# Remove sensitive headers
http-response del-header Server
http-response del-header X-Powered-By
http-response del-header X-AspNet-Version
# Add custom header
http-response add-header X-Proxy "HAProxy"
Part 3: Performance & Optimization
17. HTTP/2 Support
frontend https
bind *:443 ssl crt /etc/haproxy/certs/domain.pem alpn h2,http/1.1
default_backend servers
18. HTTP Caching
backend cache_backend
# Cache static content
http-request cache-use static_cache
http-response cache-store static_cache
server origin 192.168.1.60:80
cache static_cache
total-max-size 1024
max-age 3600
19. Compression
frontend web
bind *:80
# Enable compression for text-based content
compression algo gzip
compression type text/html text/plain text/css application/javascript
default_backend web_servers
20. Connection Multiplexing
defaults
option http-server-close
option http-keep-alive
timeout http-keep-alive 30000
21. Offloading Slow Clients
defaults
option http-buffer-request
timeout http-request 30s
timeout queue 1m
22. Traffic Shaping
frontend web
bind *:80
# Prioritize API traffic
acl is_api path_beg /api/
use_backend api_priority if is_api
default_backend default_backend
backend api_priority
server api1 192.168.1.70:8080 maxconn 1000
server api2 192.168.1.71:8080 maxconn 1000
backend default_backend
server web1 192.168.1.72:80 maxconn 500
Part 4: Advanced Routing & Traffic Management
23. Blue-Green Deployments
frontend app
bind *:80
# By default, use blue environment
default_backend blue_backend
# Switch to green via cookie or header
acl use_green hdr(X-Deployment) -i green
use_backend green_backend if use_green
backend blue_backend
server blue1 192.168.1.100:80 check
server blue2 192.168.1.101:80 check
backend green_backend
server green1 192.168.1.102:80 check
server green2 192.168.1.103:80 check
24. Canary Releases
frontend app
bind *:80
# 95% to stable, 5% to canary
default_backend stable_servers
# Route 5% of traffic to canary
acl is_canary rand(100) lt 5
use_backend canary_servers if is_canary
25. A/B Testing
frontend app
bind *:80
# Check for test group cookie
acl group_a req.cook(ab_test) -i group_a
acl group_b req.cook(ab_test) -i group_b
# Set cookie if not present (50/50 split)
http-request set-var(txn.ab_group) str("group_a") if !group_a !group_b { rand(100) lt 50 }
http-request set-var(txn.ab_group) str("group_b") if !group_a !group_b
# Set cookie
http-response set-header Set-Cookie "ab_test=%[var(txn.ab_group)]; Path=/; Max-Age=86400" if !group_a !group_b
# Route based on cookie
use_backend variant_a if group_a
use_backend variant_b if group_b
default_backend variant_a
26. Dark Launching
frontend app
bind *:80
# Normal traffic
default_backend production
# Internal test traffic to new feature
acl is_internal src 10.0.0.0/8
acl test_feature hdr(X-Test-Feature) -i new_search
use_backend feature_backend if is_internal test_feature
27. Multi-Tenant Routing
frontend multi_tenant
bind *:80
# Route by hostname
acl tenant1 hdr(host) -i customer1.example.com
acl tenant2 hdr(host) -i customer2.example.com
use_backend tenant1_backend if tenant1
use_backend tenant2_backend if tenant2
default_backend default_tenant
28. Mobile vs Desktop Routing
frontend web
bind *:80
# Detect mobile devices
acl is_mobile hdr_sub(User-Agent) -i mobile android iphone
use_backend mobile_backend if is_mobile
default_backend desktop_backend
29. Failover & Redundancy
backend app_servers
balance roundrobin
option redispatch
# Primary servers
server primary1 192.168.1.110:80 check
server primary2 192.168.1.111:80 check
# Backup servers (used only if primaries fail)
server backup1 192.168.1.112:80 check backup
server backup2 192.168.1.113:80 check backup
Part 5: Observability & Monitoring
30. Detailed Logging
global
log /dev/log local0 info
log /dev/log local1 notice
defaults
log global
option httplog
log-format "%ci:%cp [%tr] %ft %b/%s %TR/%Tw/%Tc/%Tr/%Ta %ST %B %CC %CS %tsc %ac/%fc/%bc/%sc/%rc %sq/%bq %hr %hs %{+Q}r"
# Extended TCP logging
option tcplog
tcplog-format "%ci:%cp [%t] %ft %b/%s %Tw/%Tc/%Tt %B %ts %ac/%fc/%bc/%sc/%rc %sq/%bq"
31. Real-Time Stats Dashboard
frontend stats
bind *:8404
stats enable
stats uri /stats
stats refresh 10s
stats admin if LOCALHOST
# Or with authentication
stats auth admin:password
stats hide-version
32. Prometheus Metrics
frontend metrics
bind *:9101
acl prometheus path /metrics
use_backend prometheus_backend if prometheus
backend prometheus_backend
http-request return status 200 content-type text/plain \
lf-string "# HELP haproxy_up HAProxy is ready\n# TYPE haproxy_up gauge\nhaproxy_up 1\n"
33. Distributed Tracing
frontend web
bind *:80
# Generate or pass through request ID
http-request set-header X-Request-ID %[unique-id] if ! { req.hdr(X-Request-ID) -m found }
# Add proxy headers
http-request add-header X-Forwarded-For %[src]
http-request add-header X-Forwarded-Proto https if { ssl_fc }
http-request add-header X-Forwarded-Port %[dst_port]
Part 6: Infrastructure & Cloud Integration
34. Docker Container Load Balancing
resolvers docker
nameserver dns 127.0.0.11:53
backend container_app
balance roundrobin
server-template app 10 app:8080 check resolvers docker init-addr none
35. Service Discovery with Consul
backend dynamic_servers
balance roundrobin
# Dynamic server template with Consul
server-template srv 1-10 _http._tcp.service.consul resolvers consul init-addr libc,none
resolvers consul
nameserver consul 127.0.0.1:8600
36. Hybrid Cloud Routing
frontend global
bind *:80
# Route based on latency or geolocation
acl from_europe src_cntry(EU)
acl from_us src_cntry(US)
use_backend aws_eu if from_europe
use_backend gcp_us if from_us
default_backend on_premise
backend aws_eu
server aws1 10.10.10.10:80 check
server aws2 10.10.10.11:80 check
backend on_premise
server local1 192.168.1.200:80 check
37. Multi-Datacenter HA with Keepalived
# Config for DC1 (master)
global
daemon
maxconn 10000
defaults
mode http
timeout client 30s
timeout server 30s
timeout connect 5s
listen stats
bind *:8080
stats enable
stats uri /
stats refresh 5s
frontend http
bind 192.168.100.100:80
default_backend app_servers
backend app_servers
balance roundrobin
option httpchk GET /health
server dc1_app1 192.168.1.1:80 check
server dc1_app2 192.168.1.2:80 check
server dc2_app1 10.0.0.1:80 check backup
server dc2_app2 10.0.0.2:80 check backup
Part 7: Protocol-Specific Use Cases
38. MySQL Read/Write Split
frontend mysql
bind *:3306
mode tcp
# Detect read queries (simplified approach)
tcp-request content accept if { req.len 0 }
tcp-request content reject
# Parse initial packet to detect SELECT
tcp-request inspect-delay 5s
acl is_select payload(0,1) 0x03
acl select_query payload(1,6) -m str "SELECT"
use_backend read_replicas if is_select select_query
default_backend primary_master
backend primary_master
mode tcp
server master1 192.168.2.10:3306 check
backend read_replicas
mode tcp
balance roundrobin
server replica1 192.168.2.11:3306 check
server replica2 192.168.2.12:3306 check
39. SMTP Load Balancing
frontend smtp
bind *:25
mode tcp
timeout client 1m
default_backend smtp_servers
backend smtp_servers
mode tcp
balance source
timeout server 1m
timeout connect 10s
server smtp1 192.168.3.10:25 check
server smtp2 192.168.3.11:25 check
40. DNS Load Balancing (UDP)
global
stats socket /var/run/haproxy.sock mode 600 level admin
defaults
mode udp
timeout client 30s
timeout server 30s
timeout connect 5s
frontend dns
bind *:53
default_backend dns_servers
backend dns_servers
balance roundrobin
server dns1 192.168.4.10:53 check
server dns2 192.168.4.11:53 check
41. RTMP Load Balancing
global
maxconn 10000
defaults
mode tcp
timeout client 30s
timeout server 30s
timeout connect 5s
frontend rtmp
bind *:1935
default_backend rtmp_servers
backend rtmp_servers
balance leastconn
server rtmp1 192.168.5.10:1935 check
server rtmp2 192.168.5.11:1935 check
42. MQTT Load Balancing
frontend mqtt
bind *:1883
mode tcp
option clitcpka
default_backend mqtt_cluster
backend mqtt_cluster
mode tcp
balance source
option srvtcpka
timeout server 2h
timeout client 2h
server mqtt1 192.168.6.10:1883 check
server mqtt2 192.168.6.11:1883 check
Conclusion
These 42 configuration examples demonstrate HAProxy’s incredible versatility. Start with the basics, test in a staging environment, and gradually implement more advanced features as needed.