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

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
- What to count by. The client's IP address is the default everywhere, but a login form is better limited by the account being targeted, and an API by its token. Often you want both.
- Where the counters live. Both tools increment a key in an
ActiveSupport::Cachestore. If that store is not shared by every process that serves requests, the limit is multiplied by the number of processes, or does nothing at all. - Where the check runs. In a controller, after routing and your own filters, with access to the current user; or in Rack middleware, before Rails does any work, with only the raw request.
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
- Per-action limits:
rate_limit. Sign-in, signup, password reset, invitation and contact forms are one line each, live next to the code they protect, and can usecurrent_useror an account. It pairs naturally with the generator described in our guide to authentication in Rails. - Application-wide rules: Rack::Attack. A global ceiling per IP, blocklists, safelists for your monitoring, bans for scanners, all evaluated before routing, sessions or database queries.
- API quotas: either, keyed by token rather than IP. If clients pay for a quota, record usage in your own tables instead; a cache entry that can be evicted is not a billing system. See our comparison of JSON serializers for Rails APIs for the rest of the stack.
- Floods: neither. Volumetric attacks are better stopped at the CDN, the load balancer or the web server (nginx's
limit_req, for instance), before they reach Ruby at all.
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
| Option | Runs | Counts by | Status |
|---|---|---|---|
rate_limit | In the controller, as a before_action | IP by default, any lambda | Built into Rails since 7.2; name: in 8.0, scope: and the 429 exception in 8.1 |
| Rack::Attack | Rack middleware, before routing | Any value from the request | 6.8.0, October 2025; adds blocklists, safelists and bans |
Category guidesAuthentication
Comparing Rails authentication options in 2026: the Rails 8 authentication generator, Devise, Rodauth, Authlogic, Clearance and Sorcery, plus OmniAuth for social login.
Category guidesJSON serializers
Which gem should render JSON in a Rails API? as_json, Jbuilder, Alba, Blueprinter, ActiveModelSerializers and jsonapi-serializer compared on design, maintenance and fit.
Category guidesFeature flags
Merge code switched off, then enable it for staff, a group or 5% of users. Flipper, Rollout 3 and Unleash compared, with the clean-up nobody plans for.