Rails 8 Adds Ability To Use Multiple Rate Limits Per Controller.

Rate limiting is a crucial technique for managing server traffic, enhancing performance, and bolstering security. By controlling the number of incoming requests over a specific time, it protects systems from abuse and overload.

Before

In Rails 7.2, rate limiting was introduced to Action Controller, enabling developers to limit requests to specific actions within a defined time period.

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

However, the limitation here was the inability to define multiple rate limits for different use cases within the same controller.

After

Rails 8 introduces support for multiple rate limits per controller. This enhancement allows developers to apply distinct rate limits to the same action or across multiple actions by using the name: option.

class PostsController < ApplicationController
  rate_limit to: 3, within: 2.seconds, name: "short-term", only: :create
  
  # Long-term limit for general access
  rate_limit to: 10, within: 1.minute, name: "long-term"

  def create
    # Logic for creating a post
  end
end
  • Short-term limit: Allows up to 3 requests in 2 seconds for the create action. It’s identified by the name “short-term”.
  • Long-term limit: Allows up to 10 requests in 1 minute for all actions in the controller. It’s identified by the name “long-term”.

This feature gives us more control over rate limiting, letting developers to set different limits for specific actions and time periods.

We can easily adjust parameters like to, within, by, and with for precise behavior, making it easier to implement robust rate-limiting strategies. This improvement simplifies managing traffic while maintaining clean and maintainable code.

Need help on your Ruby on Rails or React project?

Join Our Newsletter