You should subclass one of the existing rack-throttle classes (probably either Rack::Throttle::Interval
or Rack::Throttle::TimeWindow
, whichever one more closely aligns with your needs) and override the #client_identifier
method.
#client_identifier
is passed one argument, request
, which is a Rack::Request instance containing information passed in the incoming HTTP request and can be used to get information such as HTTP headers, cookies, path, and possibly other info depending on your app. The default implementation looks like this:
# @param [Rack::Request] request
# @return [String]
def client_identifier(request)
request.ip.to_s
end
Here's an example of subclassing Rack::Throttle::Interval
to match requests on a query parameter such as ?user_id=<id>
:
class UserThrottle < Rack::Throttle::Interval
def client_identifier(request)
request['user_id']
end
end
which you could use
in a Rack application with:
use UserThrottle, :min => 100
Notice you can still pass options like :min
to the Rack use
statement, since it is just subclassing the existing throttle classes. And adopting this in a Rails app would just involve calling use
in your application.rb
file (see Rails on Rack).