Limit HTTP requests per day
A fixed window request limit restricts the number of requests that can be issued during some fixed period of time, such as a calendar day.
In this example, we configure a limit of 1000 HTTP requests during a calendar day. The http_req_cnt
counter is used to count requests during the day, and we use the Runtime API to clear all records at midnight every night.
-
In the frontend, add a stick table that stores the HTTP request count.
frontend website bind :80 stick-table type ipv6 size 100k expire 24h store http_req_cnt default_backend servers
-
Add an
http-request track
directive to store the client's IP address with their request count in the stick table.frontend website bind :80 stick-table type ipv6 size 100k expire 24h store http_req_cnt http-request track-sc0 src default_backend servers
-
Add an
http-request deny
directive to deny requests for clients that exceed the limit.frontend website bind :80 stick-table type ipv6 size 100k expire 24h store http_req_cnt http-request track-sc0 src http-request deny deny_status 429 if { sc_http_req_cnt(0) gt 1000 } default_backend servers
This configuration causes every request after 1000 to be denied, but we need that restriction to be reset at midnight. To reset the counter, we need to use the Runtime API.
Here is how to reset the counter manually.
-
Add a
stats socket
directive to theglobal
section:global stats socket
/var/run/hapee-2.7/hapee-lb.sockuser hapee-lb group hapee mode 660 level admin -
Install the
socat
utility and use it to invoke theclear table
Runtime API command to clear all records from the stick table:$ echo "clear table website" |\ sudo socat stdio unix-connect:/var/run/hapee-2.7/hapee-lb.sock
To reset the counter automatically, you could set up a daily
cron
job. -
To clear a single record as a one-off, include the client's IP address:
$ echo "clear table website key 192.168.50.10" |\ sudo socat stdio unix-connect:/var/run/hapee-2.7/hapee-lb.sock
Next up
Rate limit HTTP requests