TExcelTAD

The Runtime API

Most proxies change only by editing a file and reloading. HAProxy also has a Runtime API: a command interface on a UNIX (or TCP) socket that changes a running process. You can drain a server for maintenance, change weights for a canary, add a server, edit a routing map, inspect and clear stick tables, all without a reload and without losing any counters. Deployment tools and orchestrators use it constantly.

text
global
  stats socket /run/haproxy/admin.sock mode 660 level admin expose-fd listeners

level admin allows changes (operator and user are read-only levels); expose-fd listeners lets a reloading process take over the sockets. On a server you talk to it with socat:

bash
# Sample session (real server)
$ echo "show servers state be_app" | sudo socat stdio /run/haproxy/admin.sock
$ echo "set server be_app/web1 state drain" | sudo socat stdio /run/haproxy/admin.sock

The sandbox has no socat, so the sessions use a three-line Python client (hap) that does the same: connect, send one command line, print the answer.

Draining, maintenance and weights

Command Effect
set server B/S state drain no new traffic (existing connections and sticky sessions finish); health checks continue
set server B/S state maint out of rotation completely, checks stop: for deploys and repairs
set server B/S state ready back in rotation
set server B/S weight 10% absolute (weight 5) or relative to the configured weight
show servers state [B] one line per server: state, weights, check status
show stat the CSV behind the stats page
show info process info: version, uptime, connection counts

A canary release with weights, then a deploy with drain/maint, against three backends:

bash · try it yourself
cat > app.py <<'EOF'
import sys
from http.server import BaseHTTPRequestHandler, HTTPServer
class H(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200); self.end_headers(); self.wfile.write(f"{sys.argv[2]}\n".encode())
    def log_message(self, *a): pass
HTTPServer(("127.0.0.1", int(sys.argv[1])), H).serve_forever()
EOF
python3 app.py 9001 v1-a & python3 app.py 9002 v1-b & python3 app.py 9003 v2-canary &
for p in 9001 9002 9003; do for i in $(seq 50); do curl -s 127.0.0.1:$p/ > /dev/null && break; sleep 0.1; done; done
cat > haproxy.cfg <<'EOF'
global
  pidfile haproxy.pid
  stats socket "${HOME}/admin.sock" mode 600 level admin
defaults
  mode http
  timeout connect 2s
  timeout client 10s
  timeout server 10s
frontend fe
  bind 127.0.0.1:8080
  default_backend be_app
backend be_app
  balance roundrobin
  server a 127.0.0.1:9001 weight 100
  server b 127.0.0.1:9002 weight 100
  server canary 127.0.0.1:9003 weight 0
EOF
haproxy -c -f haproxy.cfg && haproxy -D -f haproxy.cfg
hap() { python3 -c 'import socket,sys; s=socket.socket(socket.AF_UNIX); s.connect("admin.sock"); s.sendall((sys.argv[1]+"\n").encode()); r=s.makefile().read().strip(); r and print(r)' "$1"; }
mix() { for i in $(seq $1); do curl -s 127.0.0.1:8080/; done | sort | uniq -c | xargs; }
echo "weight 0 for the canary:     $(mix 20)"
hap "set server be_app/canary weight 25"
echo "canary at weight 25:         $(mix 45)"
hap "set server be_app/a state drain"
echo "a draining:                  $(mix 45)"
hap "set server be_app/a state maint"
hap "show servers state be_app" | awk 'NR>2 && NF {print "  " $4 ": op_state=" $6 " admin_state=" $7 " weight=" $8}'
hap "set server be_app/a state ready"
echo "a back:                      $(mix 45)"
hap "show info" | grep -E '^(Version|CurrConns|CumReq):'
kill $(cat haproxy.pid) %1 %2 %3
Configuration file is valid
weight 0 for the canary:     10 v1-a 10 v1-b
canary at weight 25:         20 v1-a 20 v1-b 5 v2-canary
a draining:                  37 v1-b 8 v2-canary
  a: op_state=0 admin_state=1 weight=100
  b: op_state=2 admin_state=0 weight=100
  canary: op_state=2 admin_state=0 weight=25
a back:                      20 v1-a 20 v1-b 5 v2-canary
Version: 2.8.16-0ubuntu0.24.04.3
CurrConns: 0
CumReq: 161
  • Weight 0 keeps a server configured, health-checked and ready, but sends it nothing: the canary started dark. At weight 25 next to two servers of 100 it got 25 / 225 of the traffic (5 of 45 requests).
  • The numbers in show servers state: op_state 2 is running, 0 stopped; admin_state 1 is maintenance (forced), 8 is drain. These are bit flags, documented in the management guide.
  • The changes are not written to the config file: a reload or restart forgets them unless you save them with server-state-file (HAProxy then reloads the runtime state at start, load-server-state-from-file global) or your tooling updates the file too.

Adding servers and editing maps

Since HAProxy 2.4, servers can be added and removed at runtime (add server, del server), which is how service-discovery tools keep a backend in sync with an autoscaling group. Map files used for routing can be changed the same way:

bash · try it yourself
cat > app.py <<'EOF'
import sys
from http.server import BaseHTTPRequestHandler, HTTPServer
class H(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200); self.end_headers(); self.wfile.write(f"{sys.argv[2]}\n".encode())
    def log_message(self, *a): pass
HTTPServer(("127.0.0.1", int(sys.argv[1])), H).serve_forever()
EOF
python3 app.py 9001 shop & python3 app.py 9002 blog & python3 app.py 9003 shop-new &
for p in 9001 9002 9003; do for i in $(seq 50); do curl -s 127.0.0.1:$p/ > /dev/null && break; sleep 0.1; done; done
printf 'shop.test be_shop\n' > hosts.map
cat > haproxy.cfg <<'EOF'
global
  pidfile haproxy.pid
  stats socket "${HOME}/admin.sock" mode 600 level admin
defaults
  mode http
  timeout connect 2s
  timeout client 10s
  timeout server 10s
frontend fe
  bind 127.0.0.1:8080
  use_backend %[req.hdr(host),field(1,:),lower,map("${HOME}/hosts.map",be_default)]
backend be_shop
  balance roundrobin
  server shop1 127.0.0.1:9001
backend be_blog
  server blog1 127.0.0.1:9002
backend be_default
  http-request return status 404 content-type text/plain string "no such site\n"
EOF
haproxy -c -f haproxy.cfg && haproxy -D -f haproxy.cfg
hap() { python3 -c 'import socket,sys; s=socket.socket(socket.AF_UNIX); s.connect("admin.sock"); s.sendall((sys.argv[1]+"\n").encode()); r=s.makefile().read().strip(); r and print(r)' "$1"; }
get() { curl -s -H "Host: $1" 127.0.0.1:8080/; }
echo "blog.test before:  $(get blog.test)"
hap "add map ${HOME}/hosts.map blog.test be_blog"
echo "blog.test after:   $(get blog.test)"
hap "show map ${HOME}/hosts.map" | awk '{print "  map entry: " $2 " -> " $3}'
hap "add server be_shop/shop2 127.0.0.1:9003"
hap "enable server be_shop/shop2"
echo "shop.test x4:      $(for i in 1 2 3 4; do get shop.test; done | tr '\n' ' ')"
hap "set server be_shop/shop1 state maint"
hap "del server be_shop/shop1"
echo "shop.test x2:      $(for i in 1 2; do get shop.test; done | tr '\n' ' ')"
kill $(cat haproxy.pid) %1 %2 %3
Configuration file is valid
blog.test before:  no such site
blog.test after:   blog
  map entry: shop.test -> be_shop
  map entry: blog.test -> be_blog
New server registered.
shop.test x4:      shop shop-new shop shop-new
Server deleted.
shop.test x2:      shop-new shop-new

A new site and a replaced server, with no reload. add server creates servers in maintenance, so they need enable server before taking traffic, and del server only works on a server in maintenance with no connections left: the API enforces a safe order. Map changes made through the API live in memory only; write the same change to the map file (or regenerate it) so a restart doesn't undo it.

Other useful commands

Command Use
show table / clear table T key K inspect stick tables, unblock a client (Stick Tables)
show sess current sessions (careful: long on busy servers)
show errors the last invalid requests/responses HAProxy rejected, with the bytes around the error: invaluable for "502 but the backend says it answered"
set maxconn server B/S 20 change a server's concurrency limit
show ssl cert / set ssl cert + commit ssl cert inspect and hot-swap certificates without a reload
help everything your version supports

The Data Plane API (a separate HAProxy Technologies program) wraps all of this, plus config-file editing, in a REST API for tools that prefer HTTP.

Test yourself

What is the difference between state drain and state maint?

  1. None
  2. drain stops new traffic but lets existing connections finish and keeps checks running; maint takes the server out completely
  3. maint is gentler
  4. drain deletes the server

You set a weight through the Runtime API, then reload HAProxy. What happens to the weight?

  1. It is kept automatically
  2. It is lost unless runtime state is saved with server-state-file or the config file is updated
  3. HAProxy refuses to reload
  4. It doubles

Why does add server leave the new server in maintenance?

  1. A bug
  2. So you can finish configuring it (checks, weight) and enable it deliberately before it takes traffic
  3. It is required by HTTP
  4. Servers can't be added at runtime