๐๏ธRate Limiting
Implementing Rate Limiting in Your Ruby on Rails App with rack-attack
Step 1: Add the rack-attack Gem
gem 'rack-attack'bundle installStep 2: Configure rack-attack
touch config/initializers/rack_attack.rbclass Rack::Attack
# Throttle requests from the same IP address to 5 requests per second
throttle('req/ip', limit: 5, period: 1.second) do |req|
req.ip
end
# Block IPs that fail authentication too many times
Rack::Attack.blocklist('block bad IPs') do |req|
Rack::Attack::Fail2Ban.filter("bad-ips", maxretry: 5, findtime: 1.minute, bantime: 5.minutes) do
req.ip if req.path == "users/sign_in" || "users/sign_up" && req.post?
end
end
# Allow whitelisted IPs to bypass rate limits
safelist('allow from localhost') do |req|
'127.0.0.1' == req.ip
end
# Log blocked requests
ActiveSupport::Notifications.subscribe("rack.attack") do |name, start, finish, request_id, payload|
Rails.logger.info "[Rack::Attack] Throttled: #{payload[:request].ip}" if payload[:request]
end
endStep 3: Test Your Configuration
Step 4: Deploy and Monitor
Final Thoughts
Last updated