module ActionController::RateLimiting::ClassMethods
def rate_limit(to:, within:, by: -> { request.remote_ip }, with: -> { head :too_many_requests }, store: cache_store, name: nil, **options)
rate_limit to: 10, within: 5.minutes, name: "long-term"
rate_limit to: 3, within: 2.seconds, name: "short-term"
class SessionsController < ApplicationController
end
rate_limit to: 10, within: 3.minutes, store: RATE_LIMIT_STORE
RATE_LIMIT_STORE = ActiveSupport::Cache::RedisCacheStore.new(url: ENV["REDIS_URL"])
class APIController < ApplicationController
end
by: -> { request.domain }, with: -> { redirect_to busy_controller_url, alert: "Too many signups on domain!" }, only: :new
rate_limit to: 1000, within: 10.seconds,
class SignupsController < ApplicationController
end
rate_limit to: 10, within: 3.minutes, only: :create
class SessionsController < ApplicationController
Examples:
them an explicit name via the `name:` option.
If you want to use multiple rate limits per controller, you need to give each of
parameter.
datastore as your general caches, you can pass a custom store in the `store`
`config.cache_store`. If you don't want to store rate limits in the same
`config.action_controller.cache_store`, which itself defaults to the global
Rate limiting relies on a backing `ActiveSupport::Cache` store and defaults to
request.
parameter. It's evaluated within the context of the controller processing the
response. You can specialize this by passing a callable in the `with:`
Requests that exceed the rate limit are refused with a `429 Too Many Requests`
request.
parameter. It's evaluated within the context of the controller processing the
you can provide your own identity function by passing a callable in the `by:`
Rate limits are by default unique to the ip address making the request, but
the window of time given by `within:`.
The maximum number of requests allowed is specified `to:` and constrained to
`before_action` filters with `only:` and `except:`.
Applies a rate limit to all actions or those specified by the normal
def rate_limit(to:, within:, by: -> { request.remote_ip }, with: -> { head :too_many_requests }, store: cache_store, name: nil, **options) before_action -> { rate_limiting(to: to, within: within, by: by, with: with, store: store, name: name) }, **options end