HAProxy

High-performance TCP/HTTP load balancer. Provides high availability, load balancing, and proxy capabilities. Handles tens of thousands of concurrent connections per second. Detailed statistics and monitoring.

Load BalancerProxyHigh AvailabilityLoad BalancingSSL TerminationTCPHTTPHealth Check

Server

HAProxy

Overview

HAProxy stands for "High Availability Proxy" and is one of the world's most widely used open-source load balancers. As a high-performance load balancing and proxying solution at TCP/HTTP levels, it can handle tens of thousands of concurrent connections per second and is adopted by the world's largest websites. With its simple and clear configuration syntax, detailed statistics and monitoring capabilities, and advanced health check features, it is optimized for operation in mission-critical environments.

Details

HAProxy was started by Willy Tarreau in 2000 and has over 20 years of history as a mature load balancer. The current version 3.1 fully supports modern protocols such as HTTP/2, HTTP/3 (QUIC), WebSocket, and gRPC, and is also compatible with microservices architectures. Its event-driven, non-blocking I/O architecture enables efficient handling of large numbers of concurrent connections with limited memory usage. Declarative configuration through configuration files enables operation in Docker containers, Kubernetes, and on-premises environments.

Key Features

  • High-Performance Architecture: Event-driven single-process design for maximum performance
  • Rich Load Balancing Algorithms: Support for round-robin, least connections, consistent hashing, etc.
  • Advanced Health Checks: Detailed monitoring through HTTP, TCP, SSL, and custom checks
  • Complete SSL/TLS Support: Certificate management, SNI, OCSP stapling, secure protocol support
  • Detailed Statistics & Monitoring: Real-time statistics, management interface, Prometheus integration
  • Zero-Downtime Configuration Reload: Configuration changes and process replacement without downtime

Pros and Cons

Pros

  • Established reliability and track record as industry standard (adopted by Amazon, GitHub, Reddit, etc.)
  • Extremely high performance and low memory usage
  • Flexible and powerful configuration system and ACL (Access Control List) features
  • Rich documentation and community support
  • Enterprise services through commercial support (HAProxy Enterprise)
  • Integration with Kubernetes ecosystem (HAProxy Ingress Controller)

Cons

  • High learning cost for configuration files, and readability may decrease with complex configurations
  • Configuration changes require reload (but zero-downtime)
  • Limited web UI management interface (third-party tools recommended)
  • Some advanced features are only available in commercial version (HAProxy Enterprise)
  • Performance tuning during initial setup requires specialized knowledge
  • Additional integration work needed for modern service mesh features

Reference Pages

Code Examples

Installation and Basic Setup

# Ubuntu/Debian
sudo apt update
sudo apt install haproxy

# CentOS/RHEL
sudo yum install haproxy

# Build from source
wget https://www.haproxy.org/download/3.1/src/haproxy-3.1.0.tar.gz
tar -xzf haproxy-3.1.0.tar.gz
cd haproxy-3.1.0
make TARGET=linux-glibc USE_OPENSSL=1 USE_PCRE=1 USE_SYSTEMD=1
sudo make install

# Enable and start service
sudo systemctl enable haproxy
sudo systemctl start haproxy

Basic Load Balancing Configuration

# /etc/haproxy/haproxy.cfg

global
    log stdout local0
    chroot /var/lib/haproxy
    stats socket /run/haproxy/admin.sock mode 660 level admin
    stats timeout 30s
    user haproxy
    group haproxy
    daemon

defaults
    mode http
    timeout connect 5000ms
    timeout client 50000ms
    timeout server 50000ms
    option httplog
    option dontlognull
    option http-server-close
    option forwardfor except 127.0.0.0/8
    option redispatch
    retries 3

# Web frontend
frontend web_frontend
    bind *:80
    bind *:443 ssl crt /etc/haproxy/certs/
    redirect scheme https if !{ ssl_fc }
    
    # ACL definitions
    acl is_api path_beg /api/
    acl is_static path_end .css .js .png .jpg .gif .ico
    
    # Backend routing
    use_backend api_servers if is_api
    use_backend static_servers if is_static
    default_backend web_servers

# Web server pool
backend web_servers
    balance roundrobin
    option httpchk GET /health
    http-check expect status 200
    
    server web1 192.168.1.10:80 check
    server web2 192.168.1.11:80 check
    server web3 192.168.1.12:80 check backup

# API server pool
backend api_servers
    balance leastconn
    option httpchk GET /api/health
    http-check expect string "healthy"
    
    server api1 192.168.1.20:8080 check inter 2s rise 2 fall 3
    server api2 192.168.1.21:8080 check inter 2s rise 2 fall 3
    server api3 192.168.1.22:8080 check inter 2s rise 2 fall 3

# Static content servers
backend static_servers
    balance uri
    hash-type consistent
    
    server static1 192.168.1.30:80 check
    server static2 192.168.1.31:80 check

SSL Termination and Security Configuration

# SSL configuration
global
    ssl-default-bind-ciphers ECDHE+AESGCM:ECDHE+CHACHA20:DHE+AESGCM:DHE+CHACHA20:!aNULL:!SHA1:!AESCCM
    ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets
    ssl-default-server-ciphers ECDHE+AESGCM:ECDHE+CHACHA20:DHE+AESGCM:DHE+CHACHA20:!aNULL:!SHA1:!AESCCM
    ssl-default-server-options ssl-min-ver TLSv1.2 no-tls-tickets

# Secure frontend
frontend secure_frontend
    bind *:443 ssl crt-list /etc/haproxy/certs/crt-list.txt alpn h2,http/1.1
    
    # Security headers
    http-response set-header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"
    http-response set-header X-Frame-Options DENY
    http-response set-header X-Content-Type-Options nosniff
    http-response set-header X-XSS-Protection "1; mode=block"
    http-response set-header Content-Security-Policy "default-src 'self'"
    
    # Rate limiting
    stick-table type ip size 100k expire 30s store http_req_rate(10s)
    http-request track-sc0 src
    http-request reject if { sc_http_req_rate(0) gt 20 }
    
    # Geographic blocking
    acl blocked_countries src -f /etc/haproxy/blocked_countries.lst
    http-request reject if blocked_countries
    
    default_backend secure_backend

backend secure_backend
    # Backend SSL configuration
    server secure1 192.168.1.40:443 ssl verify required ca-file /etc/haproxy/ca.crt check
    server secure2 192.168.1.41:443 ssl verify required ca-file /etc/haproxy/ca.crt check

Health Checks and High Availability Configuration

# Advanced health checks
backend advanced_health_backend
    option httpchk GET /api/health/deep
    http-check expect status 200
    http-check expect header Content-Type application/json
    http-check expect string "database_ok"
    
    # Server configuration
    server app1 192.168.1.50:8080 check inter 5s downinter 2s rise 3 fall 2 maxconn 500
    server app2 192.168.1.51:8080 check inter 5s downinter 2s rise 3 fall 2 maxconn 500
    server app3 192.168.1.52:8080 check inter 5s downinter 2s rise 3 fall 2 maxconn 500 backup

# TCP load balancing (database)
listen mysql_cluster
    bind *:3306
    mode tcp
    balance leastconn
    option tcplog
    option tcp-check
    tcp-check connect
    tcp-check send-binary 0e000000
    tcp-check send-binary 0a353030302e31302e3337000d00000000000000000000000000000000000000000000000000000000
    tcp-check expect binary 0000000a
    
    server mysql1 192.168.1.60:3306 check
    server mysql2 192.168.1.61:3306 check backup

# Redis Sentinel
listen redis_sentinel
    bind *:26379
    mode tcp
    balance first
    option tcp-check
    tcp-check send PING\r\n
    tcp-check expect string +PONG
    
    server sentinel1 192.168.1.70:26379 check
    server sentinel2 192.168.1.71:26379 check
    server sentinel3 192.168.1.72:26379 check

Statistics and Monitoring Configuration

# Statistics page configuration
listen stats
    bind *:8404
    stats enable
    stats uri /haproxy/stats
    stats realm HAProxy\ Statistics
    stats auth admin:SecurePassword123
    stats admin if TRUE
    stats refresh 30s
    stats show-legends
    stats show-desc HAProxy Load Balancer Statistics

# Prometheus statistics export
frontend prometheus_exporter
    bind *:8405
    http-request use-service prometheus-exporter if { path /metrics }
    http-request return status 404

# Logging configuration
global
    log 127.0.0.1:514 local0 info
    log-tag haproxy

# Detailed access logging
defaults
    option httplog
    capture request header Host len 32
    capture request header User-Agent len 64
    capture response header Content-Type len 32

Advanced Load Balancing and Failover

# Weighted round-robin
backend weighted_backend
    balance roundrobin
    server app1 192.168.1.80:8080 weight 100 check
    server app2 192.168.1.81:8080 weight 50 check
    server app3 192.168.1.82:8080 weight 25 check

# Consistent hashing (session persistence)
backend session_backend
    balance uri whole
    hash-type consistent
    cookie SERVERID insert indirect nocache
    
    server web1 192.168.1.90:8080 cookie web1 check
    server web2 192.168.1.91:8080 cookie web2 check
    server web3 192.168.1.92:8080 cookie web3 check

# Multi-zone configuration
backend multi_zone_backend
    balance roundrobin
    
    # Zone A (Primary)
    server zone_a_1 10.1.1.10:8080 check
    server zone_a_2 10.1.1.11:8080 check
    
    # Zone B (Secondary)
    server zone_b_1 10.2.1.10:8080 backup check
    server zone_b_2 10.2.1.11:8080 backup check
    
    # Zone C (Disaster Recovery)
    server zone_c_1 10.3.1.10:8080 backup check

# A/B testing configuration
frontend ab_test_frontend
    bind *:80
    
    # Route 1% of users to beta version
    acl is_beta_user hdr(Cookie) -m sub beta=true
    acl random_beta rand(100) lt 1
    
    use_backend beta_backend if is_beta_user or random_beta
    default_backend production_backend

backend production_backend
    server prod1 192.168.1.100:8080 check
    server prod2 192.168.1.101:8080 check

backend beta_backend
    server beta1 192.168.1.110:8080 check
    server beta2 192.168.1.111:8080 check

Management and Maintenance

# Check HAProxy status
sudo systemctl status haproxy

# Test configuration file
sudo haproxy -c -f /etc/haproxy/haproxy.cfg

# Reload configuration (zero-downtime)
sudo systemctl reload haproxy

# Management via stats socket
echo "show stat" | sudo socat stdio /run/haproxy/admin.sock

# Temporarily disable server
echo "disable server web_servers/web1" | sudo socat stdio /run/haproxy/admin.sock

# Enable server
echo "enable server web_servers/web1" | sudo socat stdio /run/haproxy/admin.sock

# Change server weight
echo "set weight web_servers/web1 50%" | sudo socat stdio /run/haproxy/admin.sock

# Check configuration
echo "show info" | sudo socat stdio /run/haproxy/admin.sock