Rails Rate Limiting: Protect Your App From Abuse

Learn Rails rate limiting with rate_limit, cache stores, and Redis to protect logins, APIs, and forms from abuse.


By Jean Emmanuel Cadet • 27 min read

Rails Rate Limiting: Protect Your App from Abuse
Share with friends

Every public Rails application eventually meets traffic it did not plan for. Some of it is hostile: bots guessing passwords, scrapers walking through every page, scripts hammering a signup form. Some of it is harmless but still expensive: a mobile client stuck in a retry loop, a partner integration that polls too often, a customer who refreshes a heavy report ten times in a row.

Your server has finite resources: CPU, database connections, worker threads, third-party API quotas, and email sending limits. When one client consumes a disproportionate share, everyone else pays for it.

Rate limiting is one of the simplest and most effective controls for this problem. It does not replace authentication, authorization, input validation, or infrastructure protection, but it is a practical layer that every public-facing Rails app should consider. Since Rails 7.2, a built-in rate_limit method makes the first step easy.

In this guide, you will learn how Rails rate limiting works, how to configure and test it, where the built-in approach stops being enough, and how to build shared, production-ready limits with a shared cache store such as Redis.


What Is Rate Limiting?

Rate limiting controls how often a client can perform an action within a defined period of time. Four ideas show up in almost every implementation:

  • Request limit: the maximum number of requests allowed, for example 10.
  • Time window: the period the limit applies to, for example 3 minutes.
  • Request identity: how you decide who “a client” is, such as an IP address, a user ID, or an API key.
  • Throttling action: what happens once the limit is exceeded, such as rejecting the request with an error.

A rule like “10 login attempts per 3 minutes per IP address” combines all four. Each request increments a counter stored under a key built from the identity. If the counter passes the limit before the window expires, the app refuses further requests. When the window ends, the counter resets.

This is called a fixed-window counter. It is simple and fast, and it is what Rails’ built-in implementation uses. Its main quirk is that a client can send a full allowance at the end of one window and another at the start of the next. For most application-level protection that is acceptable, but you should know it exists.


Why Rate Limiting Matters in Rails

Rails apps tend to have a handful of endpoints that are far more sensitive or expensive than the rest. Rate limiting protects them.

  • Authentication endpoints: Login forms are the classic target for credential stuffing and brute-force guessing. Limiting attempts makes large-scale guessing slow and noisy.
  • Password reset and registration: These endpoints can be abused to flood users with email, enumerate accounts, or create thousands of fake accounts.
  • Contact forms: Without limits, a bot can fill your inbox or your database with spam.
  • Public APIs: One client with a runaway loop can degrade the experience for every other consumer.
  • Search pages: Searches often run expensive queries, and they are easy to hit repeatedly.
  • Expensive operations: Report exports, PDF generation, and endpoints that enqueue background jobs can exhaust workers and queues.

Notice that this is as much about resource protection as security. Rate limiting also helps with accidental spikes, such as a misconfigured client or a sudden burst from a marketing email.


Rate Limiting vs. Throttling

The terms are often used interchangeably, but there is a useful distinction.

Rate limiting is the policy: “this client may make N requests per period.” Throttling is the way you enforce it after the limit is reached. An application can respond in several ways:

  • Reject the request, typically with HTTP 429 Too Many Requests.
  • Delay the request, slowing the client down instead of refusing it.
  • Degrade the response, for example by returning cached or reduced results.
  • Challenge the client, for example with a CAPTCHA or Cloudflare Turnstile.

Rails’ built-in rate_limit rejects by default. Delaying requests inside a web process is usually a bad idea, because a sleeping request still occupies a Puma thread. Rejecting quickly and letting the client retry is usually cheaper than making it wait.


Built-in Rate Limiting in Rails

Rails ships a controller-level rate_limit method (added in Rails 7.2, available in Rails 8.1). It is implemented in Action Controller and uses your configured cache store to hold counters. The basic form looks like this:

class SessionsController < ApplicationController
rate_limit to: 10, within: 3.minutes, only: :create
end

The supported options are:

  • to: the maximum number of requests allowed in the window.
  • within: the length of the window, such as 3.minutes.
  • by: a lambda that returns the identity used to group requests. The default is request.remote_ip.
  • with: a lambda that runs when the limit is exceeded. By default Rails raises ActionController::TooManyRequests.
  • store: the cache store holding the counters. The default is the controller’s cache_store, which is normally Rails.cache.
  • name: a name that separates one limit from another. This option is available in current Rails 8 releases, so check your exact version if you are on an older one.

Because rate_limit is built on before_action, you can also pass standard filter options such as only:, except:, and if:.

Two details matter in practice. First, the counter key is built from the controller path, the optional name, and the value returned by by:. Two rate_limit calls in the same controller that share the same by: value and no name: would share a counter, which is why name: exists. Second, because the limit runs as a before_action, it is evaluated in the order you declare it relative to other callbacks. That ordering matters when your identity depends on an authenticated user.

You have probably already seen it in action. The authentication generator in Rails 8 (bin/rails generate authentication) adds a rate limit to the sessions controller, and the exact generated limits depend on your Rails version.

The cache store is the counter

Rails does not keep a separate rate-limit database. Counters live in whatever cache store you configure, and the limiter relies on that store’s atomic increment with an expiry. This has consequences:

  • Redis is not automatically required. A :memory_store, :redis_cache_store, or :mem_cache_store can all hold counters.
  • A :null_store never retains values, so rate limits will not trigger. This is the default in the test environment, and we will handle it later.
  • A :memory_store keeps counters inside one process. That is fine in development but breaks down in production, which we cover in the distributed section.
  • If you use the Rails 8 default of Solid Cache in production, check your version’s documentation for increment support before relying on it for counters, or point store: at a dedicated store.

Creating a Rate Limit in a Controller

Let’s protect a login endpoint. This is a realistic example whether you use the Rails 8 authentication generator, Devise with a custom controller, or your own solution.

# app/controllers/sessions_controller.rb
class SessionsController < ApplicationController
allow_unauthenticated_access only: %i[new create]

rate_limit to: 10,
within: 3.minutes,
only: :create,
name: "login",
with: -> { redirect_to new_session_url, alert: "Too many login attempts. Please try again later." }

def new
end

def create
if user = User.authenticate_by(params.permit(:email_address, :password))
start_new_session_for user
redirect_to after_authentication_url
else
redirect_to new_session_path, alert: "Try another email address or password."
end
end
end

The rate_limit line sits in app/controllers/sessions_controller.rb. Here is what it does:

  1. Before create runs, Rails builds a key from the controller path, the name login, and request.remote_ip.
  2. It increments that counter in the cache store and sets it to expire after 3 minutes.
  3. If the count is at most 10, the request continues normally.
  4. If the count exceeds 10, Rails runs the with: lambda, which here redirects back to the form with a message.

Without a with: option, Rails raises ActionController::TooManyRequests. Rails maps that exception to a 429 Too Many Requests response through its exception handling. If your app has a static public/429.html page, Rails can render it for that status, and otherwise the response body is minimal. For an HTML form, a friendly redirect is usually a better experience. For an API, you want a structured error, which comes next.

The numbers above are illustrative. The right limit depends on your traffic and your risk, and we will discuss that later.


Customizing the Rate Limit Response

A good rate-limit response does three things: it uses the right status code, it tells the client what happened, and it tells the client when to try again.

HTTP 429 Too Many Requests (defined in RFC 6585) is the correct status for “you have sent too many requests in a given amount of time.” A Retry-After header is optional but useful, because it tells well-behaved clients how long to wait. It can contain either a number of seconds or an HTTP date.

Let’s put the response logic in a concern so every controller returns consistent output:

# app/controllers/concerns/rate_limit_responses.rb
module RateLimitResponses
extend ActiveSupport::Concern

private

def render_rate_limited(retry_after:)
seconds = retry_after.to_i
response.set_header("Retry-After", seconds.to_s)

Rails.logger.warn(
"rate_limit_exceeded controller=#{controller_path} action=#{action_name}"
)

respond_to do |format|
format.json do
render json: {
error: {
code: "rate_limited",
message: "Too many requests. Please try again later.",
retry_after: seconds
}
}, status: :too_many_requests
end
format.any do
render plain: "Too many requests. Please try again later.", status: :too_many_requests
end
end
end
end

Include it in ApplicationController:

# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
include RateLimitResponses
end

Now a contact form can use it:

# app/controllers/contact_messages_controller.rb
class ContactMessagesController < ApplicationController
rate_limit to: 3,
within: 10.minutes,
only: :create,
name: "contact-form",
with: -> { render_rate_limited(retry_after: 10.minutes) }

def create
message = ContactMessage.new(params.expect(contact_message: %i[name email body]))

if message.save
redirect_to root_path, notice: "Thanks, we received your message."
else
render :new, status: :unprocessable_entity
end
end
end

The with: lambda runs inside the controller instance, so it can call private helper methods like render_rate_limited. Note that the built-in limiter does not expose the exact remaining time in the window. Using the full window length as Retry-After is a conservative upper bound: the client may wait slightly longer than strictly necessary, but it will not retry too early.


Choosing What to Rate Limit

Not every endpoint deserves the same limit. A login attempt, a search query, and a JSON API read have very different costs and risks. Think about two questions: how expensive is a request, and what is the harm if someone abuses it?

The numbers below are illustrative starting points, not universal recommendations. Tune them using real traffic data.

Endpoint

Concern

Illustrative approach

Login

Brute force, credential stuffing

Strict per-IP limit, plus a per-account limit

Password reset

Email flooding, account enumeration

Strict per-IP and per-email limits

Registration

Fake accounts, spam

Low per-IP limit over a longer window

Contact form

Spam, inbox flooding

Very low limit over a long window

Public API

Resource exhaustion

Per-key limits with a generous allowance

Search

Expensive queries, scraping

Moderate per-user or per-IP limit

Reports, exports, job triggers

Heavy CPU, queue flooding

Low limit per user

Here is a password reset example, with a limit per IP address and another per target email address:

# app/controllers/passwords_controller.rb
class PasswordsController < ApplicationController
allow_unauthenticated_access

rate_limit to: 5,
within: 15.minutes,
only: :create,
name: "password-reset-ip",
with: -> { render_rate_limited(retry_after: 15.minutes) }

rate_limit to: 3,
within: 1.hour,
only: :create,
name: "password-reset-email",
by: -> { Digest::SHA256.hexdigest(params[:email_address].to_s.strip.downcase) },
with: -> { render_rate_limited(retry_after: 1.hour) }

def create
if (user = User.find_by(email_address: params[:email_address]))
PasswordsMailer.reset(user).deliver_later
end

redirect_to new_session_path, notice: "If that account exists, reset instructions were sent."
end
end

The second limit uses the email address as the identity. That stops an attacker from flooding one victim’s inbox from many IP addresses. Hashing the email keeps raw addresses out of cache keys. The generic response message avoids revealing whether an account exists.

For expensive operations, combine rate limiting with background processing. If an endpoint enqueues a report job, a small per-user limit prevents queue flooding, and the job itself runs outside the request cycle. If you are new to that side of the problem, our Active Job in Rails beginner’s guide covers how background jobs work.

# app/controllers/reports_controller.rb
class ReportsController < ApplicationController
rate_limit to: 5,
within: 1.hour,
only: :create,
name: "report-export",
by: -> { "user:#{Current.user.id}" },
with: -> { render_rate_limited(retry_after: 1.hour) }

def create
ReportExportJob.perform_later(Current.user.id, params[:report_type])
head :accepted
end
end

Here Current.user is available because the authentication layer runs before the limit in the callback chain. If you use Devise, replace it with current_user.


Identifying Clients

The by: option decides who the limit applies to. Each identifier has trade-offs.

IP address. This is the default and the only option for anonymous traffic. It works without any account, but many unrelated users can share one IP (offices, schools, mobile carriers), and one attacker can rotate across many IPs. An IP is also personal data in some jurisdictions, so treat it accordingly.

Authenticated user ID. This is more precise and fair for logged-in users, and it follows users across networks. It only works after authentication, so it cannot protect the login endpoint itself.

API key or token. This is ideal for API clients, because each integration gets its own allowance. Never put raw keys into cache keys or logs. Use a digest instead.

Other identifiers. A targeted account (such as the email in a reset request) or a combination such as "#{ip}:#{email}" can defend a specific resource. Be careful with client-supplied values, since attackers can vary them freely to dodge limits.

A common pattern is to combine a user identity when available with an IP fallback:

# app/controllers/search_controller.rb
class SearchController < ApplicationController
allow_unauthenticated_access

rate_limit to: 120,
within: 1.minute,
name: "search",
by: -> { rate_limit_identity },
with: -> { render_rate_limited(retry_after: 1.minute) }

def index
@results = Article.search(params[:q]).limit(25)
end

private

def rate_limit_identity
if Current.user
"user:#{Current.user.id}"
else
"ip:#{request.remote_ip}"
end
end
end

If you want logged-in users to receive a larger allowance than anonymous visitors, declare two limits with different names and use if: to select which one applies:

rate_limit to: 30, within: 1.minute, name: "search-anon",
by: -> { request.remote_ip }, if: -> { Current.user.nil? },
with: -> { render_rate_limited(retry_after: 1.minute) }

rate_limit to: 120, within: 1.minute, name: "search-user",
by: -> { Current.user.id }, if: -> { Current.user.present? },
with: -> { render_rate_limited(retry_after: 1.minute) }

IP Address Considerations

IP-based limiting is only as good as your client IP detection, and that is where many apps go wrong.

In production, your Rails app usually sits behind a reverse proxy or load balancer such as Nginx, a cloud load balancer, or a CDN. The TCP connection to Rails comes from that proxy, so the raw socket address is the proxy’s IP, not the user’s. If you naively rate limit on it, every user looks like one client and a single noisy visitor can lock everyone out.

Proxies pass the original address along in headers such as X-Forwarded-For. Rails reads these through ActionDispatch::RemoteIp, which is what powers request.remote_ip. The important part is that X-Forwarded-For is a header, and any client can send a fake one. Rails protects you by only trusting forwarded addresses that arrive through proxies it recognizes as trusted. By default, those are loopback and private network ranges.

If your proxy or load balancer lives on public address ranges, you must tell Rails about it:

# config/environments/production.rb
Rails.application.configure do
config.action_dispatch.trusted_proxies =
ActionDispatch::RemoteIp::TRUSTED_PROXIES + [
IPAddr.new("203.0.113.0/24") # example: your load balancer range
]
end

Appending to TRUSTED_PROXIES keeps the defaults. Replacing the list outright removes them, which can accidentally break private network setups.

A few rules of thumb:

  • Never read request.headers["X-Forwarded-For"] yourself and use it as an identity. Use request.remote_ip.
  • Never trust arbitrary forwarded headers from the open internet. If an attacker can set the header and your app believes it, they can pick a new “IP” on every request, which makes IP limits useless.
  • If you use a CDN such as Cloudflare, configure your app to trust only that provider’s published ranges, and consider restricting direct access to your origin.
  • After deploying, verify what request.remote_ip returns for a real request. A quick log line during setup can save you from a limit that quietly applies to your load balancer.

Even with correct detection, an IP address is not a perfect identifier. It is a useful signal, not a guarantee.


Distributed Rate Limiting

Rate-limit counters need a single source of truth. If each application process keeps its own counter, your limits are effectively multiplied.

Imagine a limit of 10 login attempts per 3 minutes, with a :memory_store. Production typically runs multiple Puma workers (separate processes), and often multiple servers. A :memory_store is local to a single process. If requests are spread across 4 processes, an attacker can make up to 40 attempts before any one counter trips, and the real number is unpredictable. Restarts and deploys also reset counters.

The solution is a shared store that all processes and servers talk to:

  • Redis (or a compatible server): fast, supports atomic counters, and expires keys natively. It is the most common choice for rate limiting.
  • Memcached: also fast and supports atomic increments.
  • Database-backed counters: workable for low-volume cases, but each request adds database load, and correctness depends on atomic SQL updates or row locks. If you go this route, a unique index on the counter key and a single atomic upsert or update statement avoids race conditions. Our Rails transactions guide explains the concurrency concepts behind this.

A shared store means every instance increments the same key, so the limit applies to the client regardless of which server handled the request. For many apps, the simplest path is to use Redis as the Rails cache store, which the built-in rate_limit then uses automatically:

# config/environments/production.rb
config.cache_store = :redis_cache_store, {
url: ENV.fetch("REDIS_URL"),
connect_timeout: 1,
read_timeout: 0.5,
write_timeout: 0.5,
reconnect_attempts: 1,
error_handler: ->(method:, returning:, exception:) {
Rails.logger.error("Redis cache error in #{method}: #{exception.class}")
}
}

The URL comes from an environment variable, so no credentials live in code. Short timeouts keep a slow Redis from stalling your web workers.

If you do not want rate-limit counters competing with general cache data, give the limiter its own store through store::

# config/initializers/rate_limit_store.rb
RATE_LIMIT_STORE = ActiveSupport::Cache::RedisCacheStore.new(
url: ENV.fetch("RATE_LIMIT_REDIS_URL"),
namespace: "rate-limit"
)
rate_limit to: 10, within: 3.minutes, only: :create, store: RATE_LIMIT_STORE

This is useful because a general cache is often configured with an eviction policy that may drop keys under memory pressure. A dedicated instance (or database) lets you tune eviction for counters separately.


Rate Limiting with Redis

Sometimes the built-in approach is not enough. You may want to use Redis directly, apply limits outside controllers, return the exact retry time, or share the same logic between a Rack middleware and background code. In those cases, you can write a small service backed by Redis.

The key concern is atomicity. A tempting implementation looks like this:

# Race-prone: do not use this in production
count = redis.incr(key)
redis.expire(key, window) if count == 1

Between INCR and EXPIRE, the process can crash or lose its connection. The key then exists without an expiry and the client stays blocked, or counts, forever. Under concurrency, other subtle races are also possible. The fix is to run both operations atomically, and a short Lua script does that, because Redis executes a script as a single unit:

# lib/rate_limiting/redis_rate_limiter.rb
module RateLimiting
class RedisRateLimiter
Result = Data.define(:allowed, :count, :retry_after)

SCRIPT = <<~LUA
local current = redis.call("INCR", KEYS[1])
if current == 1 then
redis.call("EXPIRE", KEYS[1], ARGV[1])
end
local ttl = redis.call("TTL", KEYS[1])
return { current, ttl }
LUA

def initialize(redis: RATE_LIMIT_REDIS)
@redis = redis
end

def check(key:, limit:, window:)
count, ttl = @redis.call("EVAL", SCRIPT, 1, "rate-limit:#{key}", window.to_i)
Result.new(allowed: count <= limit, count: count, retry_after: [ttl, 1].max)
rescue RedisClient::Error => error
Rails.logger.error("Rate limiter unavailable: #{error.class}")
Result.new(allowed: true, count: 0, retry_after: 0) # fail open
end
end
end

The Redis connection can be set up in an initializer using the redis-client gem:

# config/initializers/rate_limit_redis.rb
RATE_LIMIT_REDIS = RedisClient.config(
url: ENV.fetch("RATE_LIMIT_REDIS_URL"),
timeout: 0.5
).new_pool(size: 5)

A few design points are worth understanding:

  • Atomic increment and expiry: the script sets the TTL only when the key is first created, so the window starts at the first request and cannot be extended by later ones.
  • Returning the TTL: the limiter can report an accurate Retry-After value.
  • Fail open vs. fail closed: this example fails open, so a Redis outage does not take your whole site down. For a highly sensitive endpoint such as login, you might choose to fail closed or fall back to a stricter local limit. Make the decision deliberately.
  • No secrets in code: the connection URL comes from the environment, and your Redis instance should use authentication and private networking in production.

Remember that this is a custom implementation. It is different from the built-in rate_limit, which delegates counting to the Rails cache store.


Implementing Custom Rate Limiting

Rails’ controller-level rate_limit runs after routing, inside the controller, which is a good fit for most application behavior. A custom Rack middleware makes sense when you want to:

  • Reject traffic before it reaches the Rails controller stack, saving resources.
  • Apply rules by path pattern, such as everything under /api/.
  • Enforce one global policy without editing many controllers.

The trade-off is that middleware has less context. It does not know your controller, your current user, or your format negotiation, unless you recreate them. Use the built-in limiter for endpoint-specific rules and middleware for broad, cheap checks.

Here is a focused example that limits API traffic by IP, reusing the Redis limiter above:

# lib/rate_limiting/api_rate_limit_middleware.rb
module RateLimiting
class ApiRateLimitMiddleware
def initialize(app, limiter: RedisRateLimiter.new, limit: 600, window: 60)
@app = app
@limiter = limiter
@limit = limit
@window = window
end

def call(env)
request = ActionDispatch::Request.new(env)
return @app.call(env) unless request.path.start_with?("/api/")

result = @limiter.check(key: "api-ip:#{request.remote_ip}", limit: @limit, window: @window)
return @app.call(env) if result.allowed

body = { error: { code: "rate_limited", retry_after: result.retry_after } }.to_json
[
429,
{ "content-type" => "application/json", "retry-after" => result.retry_after.to_s },
[body]
]
end
end
end

Register it so it runs after ActionDispatch::RemoteIp. That is what makes request.remote_ip correct:

# config/application.rb
require_relative "../lib/rate_limiting/redis_rate_limiter"
require_relative "../lib/rate_limiting/api_rate_limit_middleware"

module MyApp
class Application < Rails::Application
config.middleware.insert_after ActionDispatch::RemoteIp, RateLimiting::ApiRateLimitMiddleware
end
end

Middleware is built early in boot, so files referenced here are required explicitly instead of relying on autoloading. Rack 3 expects lowercase header names, which is why the example uses content-type and retry-after.

If you would rather not maintain this yourself, the community gem rack-attack provides a mature middleware-based throttling and blocking toolkit. It is a separate project from Rails’ built-in rate_limit, and it is worth evaluating when your rules grow complex.


Rate Limiting APIs

APIs usually need more nuance than HTML forms. Clients are programs, so clear and consistent responses matter even more.

A common design uses layered limits:

  1. A loose per-IP limit for unauthenticated traffic.
  2. A per-API-key (or per-user) limit once the client is identified.
  3. Stricter limits on expensive endpoints.
# app/controllers/api/v1/base_controller.rb
module Api
module V1
class BaseController < ActionController::API
include RateLimitResponses

rate_limit to: 300,
within: 1.minute,
name: "api-ip",
by: -> { request.remote_ip },
with: -> { render_rate_limited(retry_after: 1.minute) }

before_action :authenticate_api_client!

rate_limit to: 1_000,
within: 1.minute,
name: "api-key",
by: -> { @api_client.rate_limit_id },
with: -> { render_rate_limited(retry_after: 1.minute) }

private

def authenticate_api_client!
token = request.authorization.to_s.delete_prefix("Bearer ")
@api_client = ApiClient.find_by_token(token)
head :unauthorized unless @api_client
end
end
end
end

The order here is intentional. The IP limit runs first, so unauthenticated floods are cheap to reject. The key-based limit is declared after authentication, so @api_client exists. Here rate_limit_id stands for a stable, non-secret identifier such as a database ID or a digest of the key, never the raw token.

Keep your error format consistent. The render_rate_limited concern returns the same JSON shape for every API controller. For responses, follow HTTP conventions:

  • Use 429 Too Many Requests for exceeded limits.
  • Include Retry-After so clients know when to retry.
  • Consider informational headers such as a limit and remaining count. Several APIs expose names like X-RateLimit-Limit and X-RateLimit-Remaining, though these are conventions rather than a single formal standard, so document whichever you choose. The built-in rate_limit does not expose remaining counts, so this typically calls for a custom limiter.

Do not use 403 Forbidden for rate limits. A 403 suggests the client lacks permission and that retrying will not help, while a 429 tells them the same request may work later.


Handling Legitimate Traffic

The best rate limit blocks abuse without annoying real people. These are the common ways limits hurt legitimate users:

  • Shared IPs and NAT: a university, office, or mobile carrier can put hundreds of people behind one address. A tight per-IP limit on a search page can block an entire building. Prefer user-based identities once users are logged in, and use more generous IP limits for read-heavy endpoints.
  • Mobile networks: carrier-grade NAT means many subscribers share addresses, and a single user’s address may change often.
  • Traffic spikes: a launch, a newsletter, or a viral post can look a lot like an attack. Limits should be generous enough for realistic bursts on cheap endpoints.
  • Retries and automation: well-behaved clients retry. Provide Retry-After so they can back off properly.

To pick sensible values, start from data. Look at your logs for typical requests per minute per user on each endpoint, add comfortable headroom, and apply strict limits only where the cost of a single request, or of a successful attack, is high. Roll out new limits cautiously: log what would have been blocked first, adjust, and then enforce. Be especially careful with login limits keyed only by account, since an attacker could use them to lock a real user out deliberately. Pair them with IP-based limits and give users a recovery path.


Rate Limiting and Other Security Measures

Rate limiting is a layer, not a complete defense. It works best alongside other controls:

  • Authentication and authorization: rate limiting slows guessing, but it does not decide who may see what. Whether you use Devise, the Rails 8 authentication generator, or another solution, access control still has to be correct.
  • CAPTCHA or Cloudflare Turnstile: challenge suspicious clients on signup, contact, and login forms. A limit tells you “too many”; a challenge tells you “human or not.”
  • Request validation: strong parameters, validations, and size limits keep individual requests from being abusive, even when they are within the rate limit. Browser-side protections such as a Content Security Policy address a different class of problems than request volume.
  • Logging and monitoring: limits are far more useful when you can see who is hitting them.
  • CDN, WAF, and infrastructure protection: application-level rate limiting runs inside your app, after the traffic has already reached your servers. It is not a DDoS defense. Large volumetric attacks need to be absorbed upstream by a CDN, a WAF, or your hosting provider’s network protections.

It is also worth being honest about what limits cannot do. A distributed attacker using thousands of IP addresses can stay under per-IP limits. A scraper that behaves politely can still collect your data over time. Rate limiting raises the cost of abuse and protects capacity, and it does not eliminate abuse.


Monitoring and Observability

A rate limit you cannot observe is a rate limit you cannot tune. At minimum, log when limits fire, and watch for patterns.

The with: lambda is a convenient place to record events, as in the concern above. Include the controller, the action, and a safe identifier. Useful signals include:

  • Which endpoints trigger limits most often.
  • Whether the same identity hits a limit repeatedly across windows.
  • Sudden growth in 429 responses after a deploy, which can indicate a limit that is too tight or a client bug.
  • A spike of limits across many identities, which can indicate a coordinated attempt.

Send these events to whichever tools you already use, such as your log aggregator, error tracker, or metrics system, and alert on unusual volumes of 429 responses.

Be careful about what you write down. Do not log passwords, tokens, reset links, API keys, or full request bodies. Treat IP addresses and email addresses as personal data, apply your retention policy, and prefer hashed or truncated identifiers where you do not need the raw value. A log designed to catch abuse should not become a new source of sensitive data.


Testing Rate Limits

Because limits protect critical endpoints, they deserve tests. Integration tests are a natural fit, since they exercise the full request cycle.

There is one gotcha. The Rails test environment typically uses :null_store for caching, which never retains counters, so a rate limit will never trip. Use a real store in tests:

# config/environments/test.rb
config.cache_store = :memory_store

Because that store is shared across tests in a process, clear it before each test so counters do not leak between them:

# test/integration/rate_limiting_test.rb
require "test_helper"

class RateLimitingTest < ActionDispatch::IntegrationTest
setup { Rails.cache.clear }

def submit_contact_form(ip: "203.0.113.10")
post contact_messages_path,
params: { contact_message: { name: "Ada", email: "[email protected]", body: "Hello" } },
env: { "REMOTE_ADDR" => ip }
end

test "allows requests under the limit" do
3.times do
submit_contact_form
assert_not_equal 429, response.status
end
end

test "returns 429 with Retry-After when the limit is exceeded" do
3.times { submit_contact_form }

submit_contact_form

assert_response :too_many_requests
assert_equal "600", response.headers["Retry-After"]
end

test "tracks different IP addresses separately" do
3.times { submit_contact_form(ip: "203.0.113.10") }

submit_contact_form(ip: "203.0.113.20")

assert_not_equal 429, response.status
end

test "allows requests again after the window passes" do
3.times { submit_contact_form }
submit_contact_form
assert_response :too_many_requests

travel 11.minutes do
submit_contact_form
assert_not_equal 429, response.status
end
end

test "login shows a friendly message when throttled" do
10.times { post session_path, params: { email_address: "[email protected]", password: "wrong" } }

post session_path, params: { email_address: "[email protected]", password: "wrong" }

assert_redirected_to new_session_url
assert_equal "Too many login attempts. Please try again later.", flash[:alert]
end
end

Each test is aimed at one behavior: requests under the limit pass, the first request over the limit gets a 429 and the expected Retry-After header, different IPs are counted separately, the window resets, and custom with: behavior works. The env: { "REMOTE_ADDR" => ... } option simulates different clients in integration tests. The travel helper works here because the in-memory store checks the current time when evaluating expiry.

Keep the thresholds in your tests small and, where possible, reference constants or configuration shared with your controllers so tests do not silently drift out of sync with production values.


Common Mistakes

These are the pitfalls that show up most often in real applications:

  • Relying on in-memory counters in multi-process or multi-server deployments. Limits get multiplied and reset on every restart.
  • Trusting unverified forwarded IP headers. Reading X-Forwarded-For directly lets an attacker choose their identity.
  • Behind a proxy without trusted proxy configuration. Every user may appear to share the proxy’s address.
  • Applying one limit to every endpoint. A number that is safe for login is far too strict for a read-only API.
  • Setting thresholds that are too restrictive. Real users get blocked, support tickets pile up, and the team disables the protection.
  • Forgetting that tests use a null cache store. Limits appear untestable, so they go untested.
  • Colliding counters. Without name:, two limits with the same identity in one controller can interfere with each other.
  • Raw secrets in keys or logs. API keys, tokens, and emails should be hashed.
  • Assuming rate limiting replaces other controls. It is one layer, and authentication, authorization, validation, and infrastructure protection still matter.
  • Never revisiting the numbers. Traffic grows and abuse patterns change, so limits need maintenance.

Best Practices

Use this checklist when adding or reviewing rate limits in a production Rails app:

  • Start with your most sensitive and most expensive endpoints: login, password reset, registration, contact forms, search, exports, and API entry points.
  • Choose limits from real traffic data, and treat example numbers as starting points only.
  • Use different limits for different endpoints, and different identities for different clients.
  • Configure a shared cache store (such as Redis) so all processes and servers see the same counters.
  • Consider a dedicated store for counters if your cache has eviction policies that could drop them.
  • Give each limit a distinct name: when multiple limits share a controller.
  • Configure trusted_proxies correctly and verify what request.remote_ip returns in production.
  • Never trust raw forwarded headers, and never put secrets or raw tokens into keys or logs.
  • Return 429 Too Many Requests with a clear body, and add Retry-After where useful.
  • Keep API error formats consistent across endpoints.
  • Make sure Redis timeouts, failure behavior (fail open or closed), and authentication are deliberate choices.
  • Log limit events, watch for repeated violations, and alert on unusual 429 volume.
  • Write integration tests for allowed requests, exceeded limits, status codes, headers, and custom behavior.
  • Combine rate limiting with authentication, authorization, CAPTCHA or Turnstile, validation, and upstream protections such as a CDN or WAF.
  • Review limits periodically as traffic and threats change.

Conclusion

Rails gives you a practical starting point for protecting your application from excessive requests. The built-in rate_limit method lets you declare a limit, a window, an identity, and a custom response in a few lines. It stores counters in your configured cache store, so the real work is choosing the right store, the right identity, and the right numbers.

For production, remember the essentials. Use a shared store such as Redis so limits hold across Puma processes and servers. Configure trusted proxies so IP-based limits apply to real clients. Return clear 429 responses with Retry-After. Test the behavior, and monitor it. When your needs go beyond the controller layer, a custom Redis-backed limiter or Rack middleware can fill the gap, as long as you keep counters atomic.

Above all, treat rate limiting as one layer in a broader defense. Used thoughtfully, it protects your resources and your users without getting in the way of the people your app is built for.

Jean Emmanuel Cadet
Written by Jean Emmanuel Cadet
Jean Emmanuel is a Full-Stack Software Engineer specializing in Ruby on Rails and the modern Rails ecosystem. He builds scalable, maintainable web applications using Rails, Hotwire (Turbo & Stimulus), PostgreSQL, and SQLite, with a focus on fast, dynamic user experiences. Through CodeCurious, he shares practical lessons, development insights, and real-world solutions for modern developers.

Code. Learn. Grow.

A friendly newsletter sharing dev tips, lessons, and wins from my journey.