How to add rate limiter in ruby on rails?

7.3k Views Asked by At

In my ruby on rails application I am facing certain performance issues. In certain forms more than 2500 request came from a same IP address at a time. So I used https://github.com/kickstarter/rack-attack to add rate limiter and track all the request from IP address and track them by storing it in Dynamic table. But for certain interval how can track them (i.e) within 5 seconds how many request came from the same IP address.

2

There are 2 best solutions below

0
On

You may use Rack::Attack.track and configure it to log the ip address only when certain amount of requests are made.

# Supports optional limit and period, triggers the notification only when the 10 requests are made under 5 seconds from same Ip(configurable).

Rack::Attack.track("Log request", limit: 10, period: 5.seconds) do |req|
  req.ip
end

# Track it using ActiveSupport::Notification
ActiveSupport::Notifications.subscribe("track.rack_attack") do |name, start, finish, request_id, payload|
  req = payload[:request]
  Rails.logger.info "special_agent: #{req.path}"
end
3
On

But for certain interval how can track them (i.e) within 5 seconds how many request came from the same ip address.

To limit the number to 10 requests every 5 seconds on a per IP basis, you'd use:

# config/initializers/rack_attack.rb

Rack::Attack.throttle('ip limit', limit: 10, period: 5) do |request|
  request.ip
end

If a single IP makes more than 10 requests within 5 seconds, it gets a "429 Too Many Requests" response.

Note that Rack Attack uses a "fixed window" approach which allows up to twice as many requests for the given duration. For example, with the above settings you could make 10 requests at the end of one window and another 10 at the beginning of the next, all within 5 seconds (or even less).