Skip to content

Instantly share code, notes, and snippets.

@mshafiee
Last active June 13, 2022 10:34
Show Gist options
  • Save mshafiee/e582eb5c2f02ab0f9f297192b60ee257 to your computer and use it in GitHub Desktop.
Save mshafiee/e582eb5c2f02ab0f9f297192b60ee257 to your computer and use it in GitHub Desktop.
Sample of HAProxy active-active peers rate limiting by counting a custom header
global
localpeer haproxy-1
defaults
timeout connect 5s
timeout client 1m
timeout server 1m
peers haproxy-peers
# peers will receive sync traffic over the bound port
peer haproxy-1 192.168.10.1:10000
peer haproxy-2 192.168.10.2:10000
peer haproxy-3 192.168.10.3:10000
# create shared stick-table
table sticktable_appid_1m type string size 500k expire 1m store http_req_rate(1m)
table sticktable_appid_60m type string size 10m expire 60m store http_req_rate(60m)
frontend website
mode http
bind :80
# -----------------------------------------------------------------
# Limit the number of user requests based on the X-AppId header
# -----------------------------------------------------------------
# check for X-AppId header parameter
acl has_appid hdr(X-AppId) -m found
# check if X-AppId header value is 'N' or 'N+'
acl appid_is_N hdr(X-AppId) -m str 'N'
acl appid_is_N hdr(X-AppId) -m str 'N+'
# check if exceeds limit
acl exceeds_appid_1m_limit hdr(X-AppId),table_http_req_rate(haproxy-peers/sticktable_appid_1m) gt 50
acl exceeds_appid_60m_limit hdr(X-AppId),table_http_req_rate(haproxy-peers/sticktable_appid_60m) gt 250
# start tracking based on X-AppId header parameter
http-request track-sc0 hdr(X-AppId) table haproxy-peers/sticktable_appid_1m if !exceeds_appid_1m_limit !exceeds_appid_60m_limit
http-request track-sc1 hdr(X-AppId) table haproxy-peers/sticktable_appid_60m if !exceeds_appid_1m_limit !exceeds_appid_60m_limit
# Deny if missing X-AppId header or exceeds limit
http-request deny deny_status 429 if has_appid exceeds_appid_1m_limit !appid_is_N
http-request deny deny_status 429 if has_appid exceeds_appid_60m_limit !appid_is_N
# -----------------------------------------------------------------
default_backend servers
backend servers
mode http
server s1 192.168.10.15:80 check maxconn 1000
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment