Skip to content

Instantly share code, notes, and snippets.

@stiller
Created June 13, 2012 13:20
Show Gist options
  • Save stiller/2923987 to your computer and use it in GitHub Desktop.
Save stiller/2923987 to your computer and use it in GitHub Desktop.
Rate limiting specific Rails routes
class RateConstraint
def matches?(request)
last_request = request.session[:request_time]
request.session[:request_time] = Time.now
!(last_request and (Time.now - last_request < 2.second))
end
end
Application.routes.draw do
constraints RateConstraint.new do
# Routes within this constraint will fail if the requests occur within 2 seconds of each other.
# This should be faster than rate limiting using the controllers and models.
# Rack middleware would probably be faster still, but I prefer the routes approach.
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment