Rate limit HTTP requests
In traffic policing, you can limit the number of HTTP requests a user can make within a certain period of time. When this period of time is the interval immediately following each request, this limit is called a sliding window rate limit.
Follow these steps to create a sliding window limit that allows a client to issue no more than 20 requests in a 10-second window.
-
Add a
stick-table
directive to the frontend. The table stores and aggregates each client's HTTP request rate.frontend website bind :80 stick-table type ipv6 size 100k expire 30s store http_req_rate(10s) default_backend servers
To conserve space, the stick table is limited to the 100,000 most recent IP records. Also, records expire and are removed if they are inactive for 30 seconds.
-
Add an
http-request track
directive to store the client's IP address with their request rate in the stick table. Counters for the IP address record begin incrementing as soon as the record is added.frontend website bind :80 stick-table type ipv6 size 100k expire 30s store http_req_rate(10s) 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 30s store http_req_rate(10s) http-request track-sc0 src http-request deny deny_status 429 if { sc_http_req_rate(0) gt 20 } default_backend servers
In the
http-request deny
directive, theif
expression determines whether the client's current request rate has exceeded the allowed number of requests, in this case 20. If so, the current request is denied with a429 Too Many Requests
response. When the count of requests during the preceding 10 seconds is again below 20, requests are accepted.
You can adjust any part of this example to suit your needs.
To change the test interval, change the time specified in the
http_req_rate
fetch in thestick-table
directive.To change the number of allowable requests in the interval, change the
gt
test value specified in thehttp-request deny
directive.Instead of denying requests that exceed the limit, you could show a reCAPTCHA or silently drop the connection. For more information, see Response Policies.
Next up
Rate limit HTTP requests by URL