开发者

Throttling requests to a Ruby on Rails API

开发者 https://www.devze.com 2022-12-22 17:01 出处:网络
Trying to Google around for an a Rails plugin that will allow for throttling the amount of requests a particular resource gets consumed. Django\'s Piston has some open source code for this. Is there s

Trying to Google around for an a Rails plugin that will allow for throttling the amount of requests a particular resource gets consumed. Django's Piston has some open source code for this. Is there something available out of the box for Rails or is it sa开发者_JAVA技巧fe to assume that looking at how Piston does it and porting it as a Rails plugin is something that can be worked on?


Here's some rack middleware that accomplishes what you're after: http://github.com/dambalah/api-throttling

and here's a blog post about the development of that middleware: http://blog.messagepub.com/2009/05/05/how-to-rack-middleware-for-api-throttling/


Rack::Defense is a rack middleware for request throttling and filtering. It is easy to set up, has a small footprint and has only two dependencies (rack and redis). You can filter on virtually any criteria: ip, api token, user name etc.

Here is an example how you would throttle POST requests for path /login with a maximum rate of 20 request per minute per IP:

Rack::Defense.setup do |config|
  config.throttle('login', 20, 60 * 1000) do |req|
    req.ip if req.path == '/login' && req.post?
  end
end

Another example on how to throttle GET requests for path /api/* with a maximum rate of 50 request per second per API token:

Rack::Defense.setup do |config|
  config.throttle('api', 50, 1000) do |req|
    req.env['HTTP_AUTHORIZATION'] if %r{^/api/} =~ req.path
  end 
end

disclamer: I am the Rack::Defense gem maintainer.


There's a SO thread here about why you might want to rate limit outside your application. Food for thought, at least. I'm looking for this solution myself, and am up in the air whether I want to do it in the application layer.

0

精彩评论

暂无评论...
验证码 换一张
取 消