skip to content

In a Rails 8.1 app, what can the rate_limit macro not protect that a Rack middleware limiter can, and what does each layer know about the request?

level: seniorimportance: nice to knowfreq 20%

answer

  1. macro runs after routing
  2. only controllers that declare it
  3. middleware sees every request
  4. controller context: Current.user
  5. cost of reaching the controller

basics

~20 s

rate_limit is a before_action, so it guards only actions that declare it, after middleware, routing and controller setup; a Rack middleware limiter sees every request earlier and more cheaply, but without the controller's knowledge of the user.

solid answer

~50 s

`rate_limit` is a controller filter. A request reaches it only after the whole middleware stack, routing, controller instantiation and any earlier `before_action`s have run, and only actions that declare a limit are covered. It cannot see requests that never reach a controller: unmatched routes, static files, engines mounted as Rack apps, or Action Cable's connection requests. Its strengths are context: `by:` can use `Current.user`, `params` or a helper, and `with:` can redirect with a flash. A Rack middleware limiter, either a gem or your own class inserted with `config.middleware`, runs before routing for every request, so it can absorb floods cheaply and apply app-wide ceilings, but it only knows the Rack env: IP, path, headers, perhaps a decoded token. Many apps use both: a coarse per-IP ceiling in middleware or at the proxy, and per-action, per-user limits with `rate_limit`.

go deeper

for a junior

Know that rate_limit runs inside controllers on the actions that declare it, not on every request.

for a middle

Contrast the macro and a Rack middleware limiter by position, coverage and available context, and name requests the macro never sees.

for a senior

Design layered limits: a cheap per-IP ceiling before routing and precise per-user limits in controllers, with consistent refusal responses.

for a principal

Decide which layer owns which abuse case, edge, middleware or controller, so limits do not overlap confusingly or leave gaps.

## Where each limiter runs A request to a Rails app passes, in order, through the proxy or load balancer, the Rack middleware stack Rails builds, the router, the controller's callbacks, and finally the action. `rate_limit` lives near the end of that path: it is a `before_action` registered by the macro, so it runs after any `before_action` declared above it. A Rack middleware limiter sits in the middleware stack, before the router. | | `rate_limit` | Rack middleware limiter | |---|---|---| | Runs | in the controller, as a filter | before routing | | Covers | actions that declare it | every request through the stack | | Knows | `params`, `Current.user`, helpers, the action | Rack env: IP, path, headers | | Cost of a refused request | middleware, routing, controller setup | almost nothing past the limiter | | Response | `with:` can redirect, flash or render | a Rack response you construct | | State | the controller's cache store or `store:` | whatever the middleware is configured with | ## What the macro cannot see Because it needs a controller, `rate_limit` misses: 1. **Unmatched paths**: a scanner hammering random URLs gets 404s from routing and never reaches a controller. 2. **Static files** served by `ActionDispatch::Static` or the proxy. 3. **Mounted Rack apps and engines** that do not go through your controllers. 4. **Action Cable** connection requests, which are handled by the cable server rather than an action. 5. **Actions that forgot the macro**: protection is opt-in per controller. It also pays the full cost of getting there for every refused request. Under a flood, a limiter that refuses at the controller still spends routing and controller setup on each request. ## What the macro does better - **User identity**: the ride-hailing app's quote endpoint keys on `Current.user.id`, which is only known after authentication runs in the controller. - **Per-action budgets**: sign-in, password reset and quotes get different limits in one line each. - **Friendly refusals**: the generated sign-in controller redirects back with "Try again later." instead of a bare 429. - **No extra dependency**: it uses the cache store the app already has. ## Combining them A practical layout for the ride-hailing app: - At the proxy or in middleware: a generous per-IP ceiling across all paths, to absorb floods and scanners cheaply. - In controllers with `rate_limit`: tight, named limits on sign-in, password reset and one-time codes per IP, and on quotes per rider. - In `rescue_from ActionController::TooManyRequests`: one consistent API response for every per-action limit. With a gem limiter, read its own documentation for configuration; the Rails side is only where it is inserted, with `config.middleware.use` or `insert_before`, and that it should run after `ActionDispatch::RemoteIp` if it relies on `request.remote_ip`, since before that middleware `remote_ip` falls back to Rack's own address logic. ## Inserting a middleware limiter Rails builds the middleware stack from `config.middleware`, so a limiter is added in `config/application.rb`: ```ruby config.middleware.insert_after ActionDispatch::RemoteIp, QuoteFloodGuard ``` `bin/rails middleware` prints the resulting order, which is the quickest way to confirm the limiter sits where you think. A refusal there returns a plain Rack response, so it will not run `rescue_from` handlers or controller layouts, and it bypasses `rate_limit.action_controller` notifications; give it its own logging. ## Rails 8.1 details that matter here - `ActionController::API` includes `RateLimiting`, so API-only apps get the macro too. - The default refusal raises `ActionController::TooManyRequests`, mapped to 429, so a single `rescue_from` can shape every limit's response. - Exceeded limits publish `rate_limit.action_controller`, which a middleware limiter would need its own instrumentation for.

  • A scanner sends thousands of requests to random paths. Why does rate_limit not slow it down?
    Random paths never match a route, so routing answers 404 before any controller runs, and `rate_limit` only runs as a controller filter. Throttle that traffic at the proxy or with a Rack middleware limiter placed before the router, which sees every request regardless of routing.
  • Where should a middleware limiter sit if it keys on the client IP?
    After `ActionDispatch::RemoteIp`, so `request.remote_ip` reflects `config.action_dispatch.trusted_proxies`. Placed earlier, `remote_ip` falls back to Rack's own `Request#ip`, which returns `REMOTE_ADDR` whenever that address is not a proxy Rack trusts; behind a public-address balancer that is the balancer, for every client.

  • rate_limit also throttles requests to unmatched routes
  • A Rack middleware can key on Current.user like a controller
  • Refusing in the controller costs nothing under a flood
  • rate_limit in one controller also counts requests to its sibling controllers
  • API-only apps cannot use rate_limit