class Rack::Attack throttle('req/ip', limit: 5, period: 1.minute) do |req| req.ip end end
Rack::Attack returns HTTP 429 status code when the request limit is exceeded, signaling the client to slow down.
Rack::Attack's block receives a Rack::Request object, which has access to params. Using req.params[:user_id] correctly extracts the user ID for throttling.
class Rack::Attack throttle('logins/ip', limit: 5, period: 20.seconds) do |req| if req.path == '/login' && req.post? req.ip end end end
If the block returns nil, Rack::Attack ignores that request for throttling. Returning nil for non-login requests is expected and does not cause counting issues. However, if the condition is incorrect or the path check is wrong, it might cause unexpected behavior.
Redis is a fast in-memory store that allows multiple app instances to share request count data, enabling consistent rate limiting across servers.
class Rack::Attack throttle('logins/ip', limit: 5, period: 60.seconds) do |req| req.ip if req.path == '/login' && req.post? end end
Each POST request to '/login' from the same IP increments the counter by 1. After 3 such requests, the counter value is 3.