Your Teachers
Chris Oliver
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.
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