Skip to content

Instantly share code, notes, and snippets.

@haproxytechblog
Last active June 18, 2022 21:32
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save haproxytechblog/4aa75c1ca498138ca50841f723fa521f to your computer and use it in GitHub Desktop.
Save haproxytechblog/4aa75c1ca498138ca50841f723fa521f to your computer and use it in GitHub Desktop.
Using HAProxy as an API Gateway, Part 1
frontend api_gateway
bind :443 ssl crt /etc/hapee-1.8/certs/cert.pem
acl PATH_cart path_beg -i /cart
acl PATH_catalog path_beg -i /catalog
use_backend be_cart if PATH_cart
use_backend be_catalog if PATH_catalog
backend be_cart
server s1 10.0.0.3:80
backend be_catalog
server s1 10.0.0.5:80
frontend api_gateway
bind :443 ssl crt /etc/hapee-1.8/certs/cert.pem
acl VHOST_publicapi req.hdr(Host) -i -m dom api.haproxy.com api.haproxy.fr
acl VHOST_partnersapi req.hdr(Host) -i -m dom partner.haproxy.com partner.haproxy.fr
acl PATH_catalog path_beg -i /catalog
acl PATH_cart path_beg -i /cart
acl PATH_inventory path_beg -i /inventory
use_backend be_cart if VHOST_publicapi PATH_cart
use_backend be_catalog if VHOST_publicapi PATH_catalog
use_backend be_inventory if VHOST_partnersapi PATH_inventory
backend be_cart
server s1 10.0.0.3:80
backend be_catalog
server s1 10.0.0.5:80
backend be_inventory
server s1 10.0.0.7
# endpoint backend name
api.haproxy.com/catalog/ be_catalog
api.haproxy.fr/catalog/ be_catalog
api.haproxy.com/cart/ be_cart
api.haproxy.fr/cart/ be_cart
partner.haproxy.com/inventory/ be_inventory
partner.haproxy.fr/inventory/ be_inventory
frontend api_gateway
# …
use_backend %[base,map_beg(“/etc/hapee-1.8/routing.map”)]
backend mobile_api
balance roundrobin
server s1 10.0.0.3:80
server s2 10.0.0.4:80
backend mobile_api
balance roundrobin
option httpchk GET /health
server s1 10.0.0.3:80 check
server s2 10.0.0.4:80 check
backend mobile_api
balance roundrobin
server s1 10.0.0.3:80 maxconn 100
server s2 10.0.0.4:80 maxconn 100
frontend api_gateway
bind :443 ssl crt /etc/hapee-1.8/certs/cert.pem
stick-table type string size 1m expire 24h store http_req_cnt
acl exceeds_limit url_param(apitoken),table_http_req_cnt(api_gateway) gt 1000
http-request track-sc0 url_param(apitoken) unless exceeds_limit
http-request deny deny_status 429 if exceeds_limit
root@server1:~$ echo "show table api_gateway" | socat UNIX-CONNECT:/var/run/haproxy.sock stdio
# table: api_gateway, type: string, size:1048576, used:1
0x55bd73392fa4: key=abcdefg use=0 exp=86396974 http_req_cnt=12
frontend api_gateway
bind :443 ssl crt /etc/hapee-1.8/certs/cert.pem
stick-table type string size 1m expire 24h store http_req_rate(10s)
acl rate_abuse url_param(apitoken),table_http_req_rate(api_gateway) gt 10
http-request track-sc0 url_param(apitoken) unless rate_abuse
http-request deny deny_status 429 if rate_abuse
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment