Rate limiting examples 🙌🏼

With Rails 8 upgrade, developers can now leverage built-in rate-limiting controls directly within their controllers 🚀

Advantages

  1. Prevents Abuse: Rate limiting deters spamming, brute-force attacks, and abusive behavior by controlling request frequency.
  2. Enhances Security: By limiting requests, it reduces vulnerability to denial-of-service (DoS) attacks.
  3. Improves Performance: Reduces server load and optimizes resource usage by restricting excessive requests.
  4. Fair Resource Allocation: Ensures equitable access for all users, preventing a single user or bot from monopolizing resources.
  5. Protects Against Data Scraping: Limits requests to guard against unauthorized data scraping and crawling bots.

Examples

Allowing max 10 requests within 3 minutes for create action:

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

Using :by for specifing domain and :with to redirect to custom url:

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

Passing custom datastore instead of saving it into config.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

Define multiple rate limits using :name

class SessionsController < ApplicationController
  rate_limit to: 3, within: 2.seconds, name: "short-term"
  rate_limit to: 10, within: 5.minutes, name: "long-term"
end

References 📌