How to Rate Limit Requests in Rails 7.2

August 7, 2024

Track your progress

Sign in to track your progress and access subscription-only lessons.

Log In

Your Teachers

Hi, I'm Chris. I'm the creator of GoRails, Hatchbox.io and Jumpstart. I spend my time creating tutorials and tools to help Ruby on Rails developers build apps better and faster.

Kent Crutchfield

Hi, my name is Kent and in between answering Hatchbox support tickets I like to make videos.

About This Episode

Rails 7.2 introduced a new rate limit feature that uses the Rails cache for preventing abuse of routes in your applications.

Notes

👨‍💻 This episode is sponsored by Tuple. Use code GORAILS at checkout to get 50% off your first 3 months.

Rate Limiting in Rails 7.2

The new rate_limit feature of Rails controllers allows you to limit the amount of requests to your application.

To implement it, you add rate_limit and tell it how many requests within a given time period should be allowed.

For example, here in the Rails authentication generator, the rate limit is set to 10 login attempts within a 3 minute time period.

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

You can also customize the rate limit response using the with: option. In this example, the sessions controller redirects you to the login page rather than the default 429 too many requests response.

The by: option lets you choose how to group requests. By default, the remote IP address will be used, so rate limits are unique per IP address, but you could change this to rate limit by any other details.

class SignupsController < ApplicationController
  rate_limit to: 1000, within: 10.seconds,
  by: -> { request.domain }, with: -> { redirect_to busy_controller_url, alert: "Too many signups on domain!" }, only: :new
end

Rate limit also is customizable using the store: option where you can choose to use a different cache store other than the Rails default cache store.

class APIController < ApplicationController
  RATE_LIMIT_STORE = ActiveSupport::Cache::RedisCacheStore.new(url: ENV["REDIS_URL"])
  rate_limit to: 10, within: 3.minutes, store: RATE_LIMIT_STORE
end

Source code for this episode

Want to stay up-to-date with Ruby on Rails?

Join 86,796+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.