Category guides

Rate limiting in Rails: the built-in rate_limit and Rack::Attack compared

Category guides · · Published 2026-11-14

A row of stainless-steel ticket turnstiles at the entrance of a metro station, with green arrows on each gate and a large orange disc on the wall behind
Turnstiles at Villa-Maria metro station, Montreal: each gate lets people through one at a time, whatever the size of the crowd.

Every public Rails app eventually meets a client that sends too many requests: a script trying passwords, a bot filling the signup form, an integration that polls your API every 200 milliseconds. Rate limiting answers with a counter and a ceiling: so many requests per key per period, then 429 Too Many Requests. Since Rails 7.2 the framework has its own tool for this, and Rack::Attack has done the job at the middleware level for more than a decade. They overlap, but they are not interchangeable.

Release figures are from RubyGems.org, November 2026. The current Rails line is 8.1.

Three decisions before any code

Rails' own rate_limit

rate_limit arrived in Rails 7.2 (August 2024) as part of Action Controller. It is a class method that installs a before_action, so it accepts only: and except: like any filter. The authentication generator in Rails 8 uses it on the sign-in action, and that line is the best short introduction:

class SessionsController < ApplicationController
  rate_limit to: 10, within: 3.minutes, only: :create,
    with: -> { redirect_to new_session_path, alert: "Try again later." }
end

to: is the number of requests allowed and within: the period. By default the key is request.remote_ip; pass by: a lambda, evaluated in the controller, to count by something else. Without with:, the behaviour depends on the version: Rails 7.2 and 8.0 answer head :too_many_requests, while Rails 8.1 raises ActionController::TooManyRequests, which Action Dispatch turns into a 429 response. If you rescue errors broadly in ApplicationController, check that you are not converting those 429s into something else after upgrading.

Two options came later. Rails 8.0 added name:, needed when one controller has several limits, for example a short burst limit and a longer one. Rails 8.1 added scope:: counts are normally separate for each controller, and a shared scope lets several controllers draw on the same allowance, which suits an API with many endpoints:

class Api::BaseController < ApplicationController
  rate_limit to: 300, within: 5.minutes, scope: :api,
    by: -> { current_api_client.id }
end

The implementation is short enough to read in a few minutes in the Rails source. Each check increments a cache key built from the scope, the name and the key value, with an expiry equal to within:; once the count passes to:, the with: handler runs and a rate_limit.action_controller notification is sent, which you can subscribe to for logging or alerts.

The cache store trap

That increment goes to config.action_controller.cache_store, which defaults to config.cache_store, and this is where most rate limits quietly fail. In the 8.1 templates, the test environment uses :null_store, whose increment returns nothing, so limits never trigger in tests. Development uses :memory_store, which works for a single process. A new Rails 8 app is set up with Solid Cache in production, which is shared through the database; but an older app that still runs the in-memory default in production gets one counter per Puma worker and per server.

The fix is to give limits a store that every process sees. The store: option takes any cache store, for example a Redis store reserved for counters, so that clearing the general cache does not reset them and a flood of increments does not evict your cached pages. In tests, set a MemoryStore on the controller under test, or in the test environment, for the tests that exercise limits. Our guide to testing Rails applications covers the frameworks.

Rack::Attack: limits before Rails starts

Rack::Attack (6.8.0, October 2025, MIT) is a Rack middleware, originally written at Kickstarter and now maintained under the rack organisation on GitHub. In a Rails app it is inserted automatically once the gem is in the Gemfile, but it does nothing until you write rules, usually in config/initializers/rack_attack.rb. It offers four kinds:

Rack::Attack.throttle("req/ip", limit: 300, period: 5.minutes) do |req|
  req.ip unless req.path.start_with?("/assets")
end

Rack::Attack.throttle("logins/email", limit: 6, period: 60) do |req|
  if req.path == "/session" && req.post?
    req.params.dig("email_address").to_s.downcase.strip.presence
  end
end

Rack::Attack.safelist("office") { |req| req.ip == "203.0.113.10" }
Rack::Attack.blocklist_ip("198.51.100.0/24")

A throttle's block returns the discriminator, the value to count by, or nil to skip the request. Safelists win over everything, blocklists answer 403, throttles answer 429, and track rules only emit notifications, which is a cheap way to measure a rule before enforcing it. Fail2Ban and Allow2Ban filters ban a client for a period after repeated suspicious requests, the classic case being scanners probing for /wp-login.php on a Rails app. The README makes two practical points: normalise values such as e-mail addresses exactly as your login code does, or attackers bypass the limit by changing case; and keep counters in a separate Redis or Memcached database, since an in-memory store gives each Ruby process its own count. Rack::Attack.throttled_response_retry_after_header = true adds a Retry-After header to throttled responses, and custom responders can send RateLimit-* headers to API clients.

Proxies: make sure you count the right IP

Behind a load balancer, a CDN or a platform router, the address that reaches Rails may be the proxy's, not the client's. Count by that and every visitor shares one allowance, so the first busy minute locks everyone out. Rails' request.remote_ip reads X-Forwarded-For only from proxies it trusts, configured with config.action_dispatch.trusted_proxies; Rack::Attack's req.ip is Rack's own calculation. Log both from a production request before writing your first rule, and limit login attempts by account as well as by IP, since botnets spread attempts across thousands of addresses.

Which one, and where

Using both is common and consistent: Rack::Attack as a coarse outer fence, rate_limit for the sensitive forms. As with any dependency, run Rack::Attack through our gem evaluation checklist; its quiet release history reflects a mature, stable API rather than neglect, but that is worth confirming for yourself.

Summary

OptionRunsCounts byStatus
rate_limitIn the controller, as a before_actionIP by default, any lambdaBuilt into Rails since 7.2; name: in 8.0, scope: and the 429 exception in 8.1
Rack::AttackRack middleware, before routingAny value from the request6.8.0, October 2025; adds blocklists, safelists and bans