Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

use different rate-limiting for controllers #23

Closed
gabrieltong opened this issue Jun 22, 2016 · 2 comments
Closed

use different rate-limiting for controllers #23

gabrieltong opened this issue Jun 22, 2016 · 2 comments

Comments

@gabrieltong
Copy link

my web application has two parts, one for web, one for api.

I want to different interval rate-limiting for the them

api : use Rack::Throttle::Hourly, :max => 100 # requests
web : use Rack::Throttle::Interval, :min => 1.0 # seconds

@OscarBarrett
Copy link

You can create some custom middleware to do so.
For example (untested, though I've used something similar):

# app/middleware/throttlers.rb
module ThrottleHelper
  def path_starts_with?(path)
    path_info = (Rails.application.routes.recognize_path request.url rescue {}) || {}
    !path_info[:controller].nil? && path_info[:controller].start_with?(path)
  end
end

class ApiHourlyThrottler < Rack::Throttle::Hourly
  include ThrottleHelper

  def allowed?(request)
    if path_starts_with?('/api')
      super
    else
      true
    end
  end
end

class WebIntervalThrottler < Rack::Throttle::Interval
  include ThrottleHelper

  def allowed?(request)
    if !path_starts_with?('/api')
      super
    else
      true
    end
  end
end

Then in application.rb

config.middleware.use 'ApiHourlyThrottler',   max: 100, ...
config.middleware.use 'WebIntervalThrottler', min: 1.0, ...

Plenty you can do to make this suit your needs: matching on controllers, throttling only certain routes etc.

@FreekingDean
Copy link
Collaborator

@OscarBarrett has the correct approach. It seems you are looking to add middleware based on the path, which I do not believe is possible.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Development

No branches or pull requests

3 participants