Backo
Backo

Reputation: 18871

How can/should I limit the amount of HTTP requests within a given period of time?

In order to avoid unwonted data storage I would like to limit the amount of HTTP requests that my server would accept in a given period of time, for example up to once per ten seconds. Practically speaking, I would like to make a my controller action to respond with an error message if there are too many HTTP requests per period. How can/should I do that? Should it be handled in middleware?


UPDATE

I am looking for a way to make a controller action to run for an incoming HTTP request. Then, within the controller action code, I would like to check if the last resource object has been accessed (through a HTTP request) in the last 10 seconds, and I would like to make that comparing the time when the last HTTP request has been performed with the "log-time" that it is stored in the database for that resource object.

The "log-time" is an attribute related to the mentioned resource object (a Ruby on Rails ActiveModel object) and it is intended to store the last time at which that object is accessed (through a HTTP request). So, if for that resource object have been performed too many HTTP requests per period then I would like to generate an error.

Upvotes: 0

Views: 624

Answers (1)

James Lim
James Lim

Reputation: 13054

This might be better handled by Nginx or Apache. Not every HTTP requests goes through your Rails application. For example, requests for static assets are often handled by Nginx/Apache directly. Moreover, as you scale your application, you might eventually have multiple Rails processes behind the same nginx server.

For nginx, the HttpLimitReqModule might be what you need. When the limit is exceeded, the server will respond with 503 Service Temporarily Unavailable. A custom error page can be created for this status code.

For apache, there is mod_ratelimit and mod_evasive.

(This might be obvious, but an additional advantage of handling rate limits in nginx/apache is that requests over the limit don't even go into your Rails processes. Nginx/Apache will cut them off immediately, potentially saving some CPU.)

Upvotes: 2

Related Questions