Fix API Rate Limit Exhaustion in Rails
API endpoints without rate limiting are a playground for automated abuse. If you expose logic—especially authentication or resource-heavy DB queries—without a throttle, you are inviting DoS attacks and credential stuffing. In the Rails ecosystem, Rack::Attack is the industry standard for implementing robust defense-in-depth at the middleware level.
The Vulnerable Pattern
class Api::V1::LoginsController < ApplicationController
# VULNERABLE: No protection against automated brute-force
def create
user = User.find_by(email: params[:email])
if user&.authenticate(params[:password])
render json: { token: user.generate_jwt }
else
render json: { error: 'Invalid credentials' }, status: :unauthorized
end
end
end
The Secure Implementation
The vulnerable code allows an attacker to spray passwords indefinitely, leading to account takeover or database exhaustion. The secure implementation uses the 'rack-attack' middleware to intercept requests before they reach the controller. By tracking the requester's IP in a fast cache (like Redis) and enforcing a threshold (5 requests per 20 seconds), we effectively neutralize automated scripts while returning a 429 Too Many Requests status to the attacker.
# config/initializers/rack_attack.rb Rack::Attack.cache.store = ActiveSupport::Cache::MemoryStore.new # Use Redis in productionThrottle login attempts by IP address
Rack::Attack.throttle(‘logins/ip’, limit: 5, period: 20.seconds) do |req| if req.path == ‘/api/v1/login’ && req.post? req.ip end end
Custom response for throttled requests
Rack::Attack.throttled_response = lambda do |env| [429, { ‘Content-Type’ => ‘application/json’ }, [{ error: ‘Rate limit exceeded. Try again later.’ }.to_json]] end
Your Rails API
might be exposed to API Rate Limit Exhaustion
74% of Rails apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.
Free Tier • No Credit Card • Instant Report
Verified by Ghost Labs Security Team
This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.