31

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/").

1 Answer 1

39

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).

6
  • 1
    thanks. Can you explain what those things are doing (zone, burst, nodelay)? And, did you mean to put zone=limit_req_zone, instead?
    – orokusaki
    Sep 9, 2010 at 19:59
  • Honestly I can't explain them that well which is why I feel it is just to confusing. Michael's explanation in the link I provided sounds like it might be feasible. I don't believe I have any typos as far as your second question goes... The module documentation I linked to has an example that might help. Sep 9, 2010 at 20:08
  • 2
    zone, burst and nodelay are documented on the Nginx wiki page about the rate limiting module, linked to already from the answer above. May 25, 2012 at 20:13
  • Kyle, do you know if there is a way to combine the rate limit per location with another trigger (e.g. Authorization-Header). In my case I may want to throttle the rate of a specific user.
    – Nils
    May 9, 2014 at 9:54
  • 1
    @Nils AFAICS you could use the $http_authorization variable to define a new zone where the key is such header rather than the IP address, i.e., limit_req_zone $http_authorization zone = per_user : 10m rate = 5r/s, and then use the per_user zone in the location sections where you want to do the per-user rate limiting. Untested, I only just read the documentation and the list of nginx variables... let me know if you try this out!
    – nicolagi
    Nov 3, 2014 at 7:46

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .