NGINX - throttle requests to prevent abuse

The reason I want to do this is because users develop against our API with JavaScript, and some developers screw up and cause visitors to slam the server with AJAX requests. When this happens, I want to be able to throttle the API requests to perhaps 50 requests per minute, or something to that effect.

Note: (particularly DB intensive resources, so perhaps at a path level, rather than server-wide (e.g. throttle "/json_api/", but not "/static/").


Solution 1:

This can be done using the LimitReqModule with Nginx. However if this is for a reverse proxy you might want to try out the new rate limiting supported by HAProxy.

I found the nginx rate limiting to be a little bit confusing to get the exact rate you want.

But you basically have something like:

limit_req_zone  $binary_remote_addr  zone=default:10m   rate=50r/m;

in the http section and then something like the following in the location section within the server section:

limit_req zone=default burst=10 nodelay;

In order not to have it for a certain section like /static you would just make that a separate location and not include it the limit_req directive (or the inverse).