Stick Tables: Rate Limits & Persistence
A stick table is an in-memory key-value store inside HAProxy. Keys are client addresses, API keys, session ids or any other sample; values are counters (requests, request rates, errors, bytes, concurrent connections) or the server a client is stuck to. Rules read the counters, so one mechanism gives you rate limiting, abuse detection, and session persistence. Tables can even be synchronised between HAProxy nodes with peers.
Declaring and tracking
backend st_api_keys # a dummy backend that only holds the table
stick-table type string len 64 size 100k expire 60s store http_req_rate(10s),http_err_rate(10s),conn_cur
frontend fe_api
http-request track-sc0 req.hdr(x-api-key) table st_api_keys
http-request deny deny_status 429 if { sc_http_req_rate(0) gt 5 }| Piece | Meaning |
|---|---|
type ip / ipv6 / string len N / integer |
the key type |
size 100k |
maximum entries (the oldest are evicted) |
expire 60s |
entries unused for this long are removed |
store http_req_rate(10s) |
requests per 10-second sliding window; also http_req_cnt, http_err_rate, conn_cur, conn_rate, bytes_out_rate, gpc0 (general purpose counter), server_id |
http-request track-sc0 KEY [table T] |
count this request under KEY in sticky counter slot 0 (slots 0–2 by default) |
sc_http_req_rate(0) |
read the tracked rate back for the current request |
Rate limiting per API key
The session limits each API key to 5 requests per 10 seconds, independently, and inspects the table through the stats socket:
cat > app.py <<'EOF'
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
class H(BaseHTTPRequestHandler):
def do_GET(self):
code = 404 if self.path.startswith("/nope") else 200
self.send_response(code); self.end_headers(); self.wfile.write(b"ok\n")
def log_message(self, *a): pass
ThreadingHTTPServer(("127.0.0.1", 9000), H).serve_forever()
EOF
python3 app.py &
for i in $(seq 50); do curl -s 127.0.0.1:9000/ > /dev/null && break; sleep 0.1; 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
backend st_keys
stick-table type string len 64 size 10k expire 60s store http_req_rate(10s),http_err_rate(10s)
frontend fe_api
bind 127.0.0.1:8080
http-request deny deny_status 401 unless { req.hdr(x-api-key) -m found }
http-request track-sc0 req.hdr(x-api-key) table st_keys
http-request deny deny_status 429 if { sc_http_req_rate(0) gt 5 }
http-request deny deny_status 403 if { sc_http_err_rate(0) gt 3 } # key that keeps probing missing URLs
default_backend be_app
backend be_app
server app 127.0.0.1:9000
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()); print(s.makefile().read(), end="")' "$1"; }
codes() { for i in $(seq $2); do curl -s -o /dev/null -w '%{http_code} ' -H "X-API-Key: $1" 127.0.0.1:8080$3; done; echo; }
echo "no key: $(curl -s -o /dev/null -w '%{http_code}' 127.0.0.1:8080/)"
echo "key alice x8: $(codes alice 8 /)"
echo "key bob x3: $(codes bob 3 /)"
echo "key mallory x6: $(codes mallory 6 /nope)"
hap "show table st_keys" | sed -E 's/^0x[0-9a-f]+: //; s/ use=[0-9]+ exp=[0-9]+//' | sort
kill $(cat haproxy.pid) %1Configuration file is valid
no key: 401
key alice x8: 200 200 200 200 200 429 429 429
key bob x3: 200 200 200
key mallory x6: 404 404 404 404 403 429
# table: st_keys, type: string, size:10240, used:3
key=alice shard=0 http_req_rate(10000)=8 http_err_rate(10000)=3
key=bob shard=0 http_req_rate(10000)=3 http_err_rate(10000)=0
key=mallory shard=0 http_req_rate(10000)=6 http_err_rate(10000)=6
alicehit 429 after 5 requests in the window, whilebobwas unaffected: the limit is per key, not global.mallorycollected 404s; once her error rate passed 3, her fifth request was refused with 403 although she was still under the request limit (the sixth then also exceeded the rate: 429). Note thathttp_err_ratecounts every 4xx answer, including HAProxy's own denials:alice's three 429s show up as errors too, so order the rules so the one you want to report fires first. The same pattern catches credential stuffing (count 401s per source) or scanners (count 404s).- Denied requests are still counted (tracking happens before the deny rules), so a client that keeps hammering stays blocked until its rate drops. Count only accepted requests by tracking after the rate check, if that is the policy you want.
show tableshows each key with its counters;clear table st_keys key aliceunblocks one key at runtime.
For per-IP limiting use type ip and track-sc0 src. Behind another proxy, track the real client address (PROXY protocol, or req.hdr_ip(x-forwarded-for,-1) from trusted proxies only).
Session persistence
Some applications keep session state in memory, so a user must keep hitting the same server. HAProxy has two methods:
| Method | How | Survives |
|---|---|---|
| cookie insertion | cookie SRV insert indirect nocache + server web1 … cookie w1: HAProxy adds Set-Cookie: SRV=w1 and routes by it |
HAProxy restarts and multiple HAProxy nodes (the state is in the client) |
| stick table | stick-table type ip … + stick on src: the table remembers client → server |
needs peers to share between nodes |
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 web1 & python3 app.py 9002 web2 &
for p in 9001 9002; 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
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
cookie SRV insert indirect nocache httponly
server web1 127.0.0.1:9001 cookie w1
server web2 127.0.0.1:9002 cookie w2
EOF
haproxy -c -f haproxy.cfg && haproxy -D -f haproxy.cfg
echo "without cookie: $(for i in 1 2 3 4; do curl -s 127.0.0.1:8080/; done | tr '\n' ' ')"
curl -s -c jar.txt -D - -o /dev/null 127.0.0.1:8080/ | grep -i '^set-cookie' | tr -d '\r'
echo "with cookie: $(for i in 1 2 3 4; do curl -s -b jar.txt 127.0.0.1:8080/; done | tr '\n' ' ')"
echo "forged w2: $(curl -s -b 'SRV=w2' 127.0.0.1:8080/)"
kill $(cat haproxy.pid) %1 %2Configuration file is valid
without cookie: web1 web2 web1 web2
set-cookie: SRV=w1; path=/; HttpOnly
with cookie: web1 web1 web1 web1
forged w2: web2
indirect keeps the cookie between HAProxy and the client (the application never sees it), nocache marks responses that set it as uncacheable so a shared cache can't hand one user's server cookie to everyone, and httponly hides it from JavaScript. If the server in the cookie goes down, HAProxy picks another one (with option redispatch) and replaces the cookie.
Persistence is a crutch: it unbalances load and loses sessions when a server dies. Prefer keeping session state in a shared store (Redis, the database) or in signed cookies, so that any server can handle any request.
Test yourself
What does http-request track-sc0 src do?
- Blocks the client
- Counts the request in the stick table under the client's address, in sticky counter slot 0, so rules can read its counters
- Logs the address
- Sends the address to the backend
Which persistence method works across several HAProxy nodes without extra configuration?
- stick on src
- Cookie insertion: the chosen server is stored in the client's cookie
- balance roundrobin
- leastconn
In the session, why was mallory refused with 403 although she sent only 6 requests?
- Her key was invalid
- Her error rate (404s) passed the threshold of 3 per 10 seconds
- She exceeded 5 requests
- HAProxy blocks unknown names