In my ruby on rails application i am facing ceratin 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.
Asked
Active
Viewed 5,755 times
3
-
Your question is unclear ro me. What is your question? How to implement a [limit on the number of requests](https://github.com/kickstarter/rack-attack#throttlename-options-block) using Rack::Attack or how to [log data when someone gets blocked](https://github.com/kickstarter/rack-attack#logging--instrumentation)? – spickermann May 13 '20 at 06:31
-
Your question's title does not seem to be what you are actually asking. Please edit the title to reflect what you actually want to ask. – Tom Lord May 13 '20 at 09:38
2 Answers
0
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).

Stefan
- 109,145
- 14
- 143
- 218
-
-
Because it prompts that Unexpected error while processing request: wrong constant name ::Redis::Store if i refresh the page. – Harish Jams May 21 '20 at 05:29
-
Rack Attack uses `Rails.cache` by default. The rules and stores are independent of each other. – Stefan May 21 '20 at 17:45
0
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

Ayush Billore
- 109
- 5