Operations 28 min read

Master HAProxy: Build High‑Performance L7/L4 Load Balancers and HA Clusters

This comprehensive guide explains what HAProxy is, its core features and performance, how to install and configure it for L7 and L4 load balancing, implement health checks, session persistence, monitoring, and achieve high availability with Keepalived on Linux systems.

Open Source Linux
Open Source Linux
Open Source Linux
Master HAProxy: Build High‑Performance L7/L4 Load Balancers and HA Clusters

What is HAProxy

HAProxy is a free, open‑source load‑balancing software that runs on most mainstream Linux distributions. It supports L4 (TCP) and L7 (HTTP) balancing, offers rich features, and delivers performance and stability comparable to commercial appliances.

Core Functions

Load balancing: L4 and L7 modes with algorithms such as round‑robin, static‑RR, least‑connection, IP‑hash, URI‑hash, header‑hash, etc.

Health checking: TCP and HTTP health checks.

Session persistence: Insert/Rewrite/Prefix cookies and various hash methods.

SSL termination: Decrypt HTTPS and forward plain HTTP to back‑ends.

HTTP request rewriting and redirection.

Monitoring & statistics: Web‑based stats page for health and traffic data.

Key Characteristics

Performance

Single‑threaded, event‑driven, non‑blocking model processes hundreds of requests within 1 ms, using only a few kilobytes per session.

O(1) event checkers, zero‑copy forwarding and other kernel‑leveraging optimizations keep CPU usage low.

Typical CPU usage is about 15 % of total processing time; the kernel handles the rest.

In 2009 a test showed >100 k requests/second and full 10 Gbps line utilization.

Stability

Running HAProxy as a single process yields exceptional stability; the author reports no crash‑inducing bugs over 13 years. Stability largely depends on the underlying Linux kernel (2.6 or 3.x) and proper sysctl tuning.

Recommendations:

Use a Linux kernel 3.x or newer.

Dedicate the host to HAProxy to avoid resource contention.

Provide a standby node for hardware or power failures.

Apply a baseline sysctl configuration (see code block below).

net.ipv4.tcp_tw_reuse = 1
net.ipv4.ip_local_port_range = 1024 65023
net.ipv4.tcp_max_syn_backlog = 10240
net.ipv4.tcp_max_tw_buckets = 400000
net.ipv4.tcp_max_orphans = 60000
net.ipv4.tcp_synack_retries = 3
net.core.somaxconn = 10000

Installation & Running on CentOS 7

Create a dedicated user/group (e.g., "ha"). Download, extract, compile and install HAProxy:

wget http://www.haproxy.org/download/1.7/src/haproxy-1.7.2.tar.gz
tar -xzf haproxy-1.7.2.tar.gz
make PREFIX=/home/ha/haproxy TARGET=linux2628
make install PREFIX=/home/ha/haproxy

Specify the installation prefix with

PREFIX

and choose the appropriate

TARGET

for your kernel (e.g.,

linux2628

for kernel 3.10).

Configuration File Example

global
    daemon
    maxconn 256
    pidfile /home/ha/haproxy/conf/haproxy.pid

defaults
    mode http
    timeout connect 5000ms
    timeout client 50000ms
    timeout server 50000ms

frontend http-in
    bind *:8080
    default_backend servers

backend servers
    server server1 127.0.0.1:8000 maxconn 32

Ensure

ulimit -n

is greater than

maxconn*2+18

when increasing

maxconn

.

L7 Load Balancer Setup

Define front‑end ACLs to route based on URI prefixes, enable session‑sticky cookies, health checks, and a web‑based stats page:

global
    daemon
    maxconn 30000
    user ha
    pidfile /home/ha/haproxy/conf/haproxy.pid
    log 127.0.0.1 local0 info
    log 127.0.0.1 local1 warning

defaults
    mode http
    log global
    option http-keep-alive
    option forwardfor
    option httplog
    timeout connect 5000ms
    timeout client 10000ms
    timeout server 50000ms
    option httpchk GET /healthCheck.html

frontend http-in
    bind *:9001
    acl url_ms1 path_beg -i /ms1/
    acl url_ms2 path_beg -i /ms2/
    use_backend ms1 if url_ms1
    use_backend ms2 if url_ms2
    default_backend default_servers

backend ms1
    balance roundrobin
    cookie HA_STICKY_ms1 insert indirect nocache
    server ms1.srv1 192.168.8.111:8080 cookie ms1.srv1 maxconn 300 check inter 2000ms rise 2 fall 3
    server ms1.srv2 192.168.8.112:8080 cookie ms1.srv2 maxconn 300 check

backend ms2
    balance roundrobin
    cookie HA_STICKY_ms2 insert indirect nocache
    server ms2.srv1 192.168.8.111:8081 cookie ms2.srv1 maxconn 300 check
    server ms2.srv2 192.168.8.112:8081 cookie ms2.srv2 maxconn 300 check

backend default_servers
    balance roundrobin
    cookie HA_STICKY_def insert indirect nocache
    server def.srv1 192.168.8.111:8082 cookie def.srv1 maxconn 300 check
    server def.srv2 192.168.8.112:8082 cookie def.srv2 maxconn 300 check

listen stats
    bind *:1080
    stats refresh 30s
    stats uri /stats
    stats realm "HAProxy Stats"
    stats auth admin:admin

After editing, start HAProxy with

service haproxy start

. The stats page (e.g.,

http://192.168.8.110:1080/stats

) shows health, connections, session rates, and traffic for each frontend/backend.

Health Checks

The stats page displays the status of each back‑end server. Renaming a health‑check file triggers a DOWN state, which returns to UP once the file is restored.

URI‑Based Routing

Requests such as

http://192.168.8.110:9001/ms1/demo.html

are routed to the appropriate back‑end group based on the defined ACLs.

Load Balancing & Sticky Sessions

HAProxy inserts cookies (e.g.,

HA_STICKY_ms1

) to keep a client bound to the same server. Deleting the cookie forces HAProxy to reassign a server.

L4 Load Balancer Setup

Switch

mode

to

tcp

for pure transport‑layer balancing. Example configuration:

global
    daemon
    maxconn 30000
    user ha
    pidfile /home/ha/haproxy/conf/haproxy.pid
    log 127.0.0.1 local0 info
    log 127.0.0.1 local1 warning

defaults
    mode tcp
    log global
    option tcplog
    timeout connect 5000ms
    timeout client 10000ms
    timeout server 10000ms
    option httpchk GET /healthCheck.html

frontend http-in
    bind *:9002
    default_backend default_servers

backend default_servers
    balance roundrobin
    server def.srv1 192.168.8.111:8082 maxconn 300 check
    server def.srv2 192.168.8.112:8082 maxconn 300 check

In TCP mode, session persistence can be achieved with

balance source

(IP‑based) or advanced stick‑tables.

Key Configuration Details

HAProxy configuration consists of five sections:

global : process‑wide settings (daemon, user, log, maxconn, etc.).

defaults : default parameters applied to all frontends and backends.

frontend : defines listening sockets, ACLs, and routing rules.

backend : defines server pools, load‑balancing algorithms, health checks, and cookie‑based persistence.

listen : combines frontend and backend in a single block.

Important directives include

acl

,

bind

,

use_backend

,

balance

,

cookie

,

option httpchk

, and various timeout settings.

High Availability with Keepalived

To protect HAProxy from host or network failures, run Keepalived on two machines. Both instances compete for a virtual IP; the one with the highest weight becomes MASTER. Keepalived monitors HAProxy via a script (

killall -0 haproxy

) and adjusts the weight accordingly.

global_defs {
    router_id LVS_DEVEL
}

vrrp_script chk_haproxy {
    script "killall -0 haproxy"
    interval 2
    weight 2
}

vrrp_instance VI_1 {
    state MASTER
    interface enp0s25
    virtual_router_id 51
    priority 101
    advert_int 1
    virtual_ipaddress {
        192.168.8.201
    }
    track_script {
        chk_haproxy
    }
}

Install Keepalived, register it as a service, and start it on both nodes. The virtual IP (e.g.,

192.168.8.201

) will float between the nodes; when the MASTER HAProxy stops, the BACKUP node automatically takes over traffic.

Source: https://blog.csdn.net/xiaoxiaole0313/article/details/113977071
HAProxy architecture diagram
HAProxy architecture diagram
high availabilityLoad BalancingLinuxHAProxyL7L4
Open Source Linux
Written by

Open Source Linux

Focused on sharing Linux/Unix content, covering fundamentals, system development, network programming, automation/operations, cloud computing, and related professional knowledge.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.