Rate Limiting in Rails: The Built-In Way and Its Limits

Rate Limiting in Rails: The Built-In Way and Its Limits

Rails has rate_limit inside the controller since 7.2, we like it, and before trusting it on a login form we poked it from different sides on Rails 8.1.

With to 10 within 3 minutes the answers were ten times 200 and then 429, as promised, but the 429 came with completely empty body and no Retry-After header, so a person would see a white page, this is why we give it a with option which redirects with a message, or for API sets the header by ourselves.

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

  def create
    # ...
  end
end
rate_limit to: 10, within: 3.minutes, only: :create,
  with: -> {
    redirect_to new_session_path,
      alert: "Too many attempts. Try again in a few minutes."
  }
rate_limit to: 100, within: 1.minute, with: -> {
  response.set_header("Retry-After", "60")
  render json: { error: "rate_limited" }, status: :too_many_requests
}

Then the store. Test environment usually has NullStore, we put it and shot 100 requests, and all 100 are 200, it doesn't complain, doesn't warn, there is just no limit, and somebody will write a test, see it failing and dig in the controller for an hour for nothing. Memory store we forked six processes, each got 20 requests, and each one allowed its own 10, in sum 60 passed, so with six workers the number 10 in your code means 60.

About the key, we made limit by email with 8, and then played the attacker, 100 different IP, same email but sometimes with capital letters, sometimes with a space before, 8 went through and 92 got 429, it works because in the by lambda we strip it and downcase it. What we don't like here, anyone who knows your email can now keep you locked out just by typing wrong password, so the window must be short.

rate_limit to: 50, within: 10.minutes, only: :create, name: "ip"
rate_limit to: 8, within: 10.minutes, only: :create, name: "account",
  by: -> { params[:email].to_s.strip.downcase }

The part which surprised us the most was remote_ip. A request coming from a public address with a self made X-Forwarded-For header, 1.2.3.4, and Rails answered that the client is 1.2.3.4. It believes the header. Behind a proxy which appends the real address it took the right one, 203.0.113.7, and ignored the fake before it, but if somebody can reach your server directly, passing the proxy, he can choose a new IP for every request and your IP limit is nothing, close the origin for everybody except the proxy.

Rails.logger.info("remote_ip=#{request.remote_ip}")

See also: Solid Cache and authentication and security.