DEV Community

Cover image for New Rails 7.2: Added Rate Limiting
JetThoughts Dev for JetThoughts

Posted on • Edited on • Originally published at jetthoughts.com

New Rails 7.2: Added Rate Limiting

Ruby on Rails 7.2 added rate limiting to Action Controller. It's cool and easy to use.

rate_limit in Rails 7.2

What's New?

Rails now offer built-in rate limiting using Redis and Kredis. This empowers you to control how often a user can act within a given time, putting you in the driver's seat.

Before:

# Manually implemented rate limiting
Enter fullscreen mode Exit fullscreen mode

After:

class SessionsController < ApplicationController

  rate_limit to: 10, within: 3.minutes, only: :create

end

class SignupsController < ApplicationController

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

end
Enter fullscreen mode Exit fullscreen mode

How It Works

  1. Setup: Ensure you have Redis and Kredis 1.7.0+.
  2. Usage: Add rate_limit in your controllers.

Why This Matters

This feature is great for preventing abuse and managing traffic, and it's also highly flexible. You can customize limits per action and gracefully handle exceeded limits, making it a perfect fit for your needs.

Conclusion

This update makes managing traffic easier. It's straightforward and effective. If you're using Rails, give it a try!

For more details, check out the official pull request.

Top comments (2)

Collapse
 
ben profile image
Ben Halpern

Great feature

Collapse
 
paulmarclay profile image
Paul Marclay

Wow!