In Rails 8.1's rate_limit macro, how do the by:, name: and scope: options change which requests share a counter?
answer
- key = rate-limit:scope:name:by
- by: picks the identity
- name: separates limits in one controller
- scope: shares limits across controllers
- scope: is new in 8.1
basics
~20 sEach option fills one part of the cache key rate-limit:<scope>:<name>:<by>: by: chooses the identity counted, name: lets one controller keep several limits apart, and scope:, new in 8.1, replaces controller_path so different controllers can share one counter.
solid answer
~40 s`rate_limit` counts in a cache key built as `rate-limit:<scope>:<name>:<by>`. `by:` is evaluated per request in the controller (a lambda, or since 8.1 a method name) and defaults to `request.remote_ip`; keying on `Current.user.id` or a normalised phone number changes who shares a counter. `name:` matters when one controller declares more than one limit: two unnamed limits would build the **same key** and increment the same counter twice per request, so give each a distinct name such as `"burst"` and `"hourly"`. `scope:` replaces the default `controller_path`; added in 8.1, it lets several controllers share one budget, for example a web and an API quotes controller both using `scope: :fare_quotes`. `store:` picks the backing cache, and `only:`/`except:` choose the actions.
code
ruby · 9 linesclass QuotesController < ApplicationController
rate_limit to: 3, within: 10.seconds, name: "burst", by: :rider_key, only: :create
rate_limit to: 60, within: 1.hour, name: "hourly", by: :rider_key, only: :create
private
def rider_key
Current.user&.id || request.remote_ip
end
endgo deeper
Recall that by: decides who is counted and that the default is the client IP.
Explain the rate-limit:scope:name:by key, why multiple limits need name:, and how 8.1's scope: lets controllers share one counter.
Pick identities that resist both evasion and targeted lockout, combine per-IP and per-account limits, and verify keys through the notification payload.
Define the limit budgets per product capability, not per controller, so new endpoints join an existing scope instead of opening a fresh budget.
## One key, four parts Everything about who shares a limit follows from one line in `ActionController::RateLimiting`: ```ruby cache_key = ["rate-limit", scope, name, by].compact.join(":") ``` `compact` drops a `nil` name, so an unnamed limit's key is `rate-limit:<scope>:<by>`. Two requests share a counter exactly when they build the same key against the same store. ## by: who is being counted `by:` is evaluated for every request inside the controller instance, so it can read `request`, `params`, `Current` attributes or helper methods. Since 8.1 it may also be a method name given as a symbol. Typical choices in a ride-hailing app: | Endpoint | `by:` | Why | |---|---|---| | Rider sign-in | default `request.remote_ip` | the attacker is not authenticated yet | | Fare quotes | `-> { Current.user.id }` | many riders share carrier IPs | | One-time-code SMS | `-> { params[:phone].to_s.gsub(/\D/, "") }` | cap messages per destination number | Keying on something the attacker controls has a cost: a per-phone or per-email limit can be exhausted by someone else to block the victim, so pair it with a per-IP limit. ## name: several limits in one controller A common pattern is a short burst limit plus a longer budget: ```ruby rate_limit to: 3, within: 10.seconds, name: "burst", only: :create rate_limit to: 60, within: 1.hour, name: "hourly", only: :create ``` Without `name:`, both declarations would build `rate-limit:quotes:<ip>`. Each request would increment the same counter twice, and with the memory and Redis stores the expiry would come from whichever limit created the counter. Naming them gives each its own key and window. ## scope: one budget across controllers By default the scope is `controller_path`, so `QuotesController` and `Api::V1::QuotesController` count separately and a client could use both budgets. Rails 8.1 added `scope:`: ```ruby class QuotesController < ApplicationController rate_limit to: 30, within: 1.minute, scope: :fare_quotes end class Api::V1::QuotesController < ActionController::API rate_limit to: 30, within: 1.minute, scope: :fare_quotes end ``` Both now increment `rate-limit:fare_quotes:<client IP>`. For the counters to meet, both declarations must also use the **same store** and the same `by:` value for the same client. ## The remaining options - `store:` replaces the controller's cache store, for example a dedicated store so limits survive a cache flush. - `with:` is the refusal: a lambda or method name, by default raising `ActionController::TooManyRequests`. - `only:` / `except:` and other filter options pass straight to `before_action`. ## Worked keys For a rider at `203.0.113.7` signed in as user 42, these declarations produce these keys: | Declaration | Key | |---|---| | `rate_limit to: 10, within: 3.minutes` in `SessionsController` | `rate-limit:sessions:203.0.113.7` | | `name: "burst", by: -> { Current.user.id }` in `QuotesController` | `rate-limit:quotes:burst:42` | | `scope: :fare_quotes` in `Api::V1::QuotesController` | `rate-limit:fare_quotes:203.0.113.7` | A symbol passed to `by:` or `with:` is called with `send`, so a private method works, which keeps the identity logic out of the public action list. ## Checking your keys The `rate_limit.action_controller` notification carries `cache_key`, `scope`, `name` and `by` in its payload, so logging it during a rollout shows exactly which counters exist. The steps: 1. Subscribe to the event in an initializer. 2. Trip each limit once in staging. 3. Confirm the keys are the ones you designed, not one shared by accident.
- What goes wrong if a controller declares two rate_limit lines without name:?Both build the same key, `rate-limit:<controller_path>:<by>`, so each request increments one counter twice, and with the memory and Redis stores its expiry comes from whichever limit created it. The burst and hourly limits stop meaning what they say. Giving each a distinct `name:` puts them in separate keys.
- Why might keying a login limit only on the submitted email address be a mistake?Anyone can submit someone else's address, so an attacker can exhaust the victim's counter and lock them out, while spraying many addresses from one IP stays under each per-email limit. Keep the default per-IP limit and add a per-account one with its own `name:`.
- Two unnamed limits in one controller keep separate counters
- scope: limits which actions the rate limit applies to
- by: is evaluated once when the class loads
- Controllers share a counter by default if their limits match
- Keying only on the email address is the safest login limit
Assumes Rails 8.1: scope: is new in 8.1.0, and by:/with: accept method names since 8.1.0; earlier releases always scoped by controller_path.