GuardAPI Logo
GuardAPI

Fix Lack of Resources & Rate Limiting in Hanami

Hanami applications are built for performance, but without explicit rate limiting, they are sitting ducks for resource exhaustion and DoS. If an attacker can trigger expensive operations—like complex database queries or external API calls—repeatedly, they can saturate the Ruby thread pool and crash the service. In Hanami, the most robust way to handle this is at the Rack layer before the request even hits your action logic.

The Vulnerable Pattern

module Bookshelf
  module Actions
    module Reports
      class Create < Bookshelf::Action
        def handle(request, response)
          # VULNERABLE: No throttling on an expensive PDF generation task
          data = Repository.new.fetch_heavy_stats
          pdf = Generator.generate_report(data)
          response.body = pdf
        end
      end
    end
  end
end

The Secure Implementation

The vulnerable code allows an attacker to spawn infinite 'heavy' processes, leading to CPU and memory exhaustion. The fix involves implementing Rack::Attack as middleware within the Hanami application stack. This intercepts requests at the entry point, checking the client IP against a memory store (like Redis). If the threshold (3 requests per 60 seconds) is exceeded, the middleware returns a 429 Too Many Requests response immediately, preventing the expensive Hanami action from ever executing.

# 1. Add 'rack-attack' to Gemfile
# 2. Configure middleware in config/app.rb or a provider

require “rack/attack”

Rack::Attack.throttle(“reports/ip”, limit: 3, period: 60) do |req| req.ip if req.path == “/reports” && req.post? end

module Bookshelf class App < Hanami::App config.middleware.use Rack::Attack end end

System Alert • ID: 1413
Target: Hanami API
Potential Vulnerability

Your Hanami API might be exposed to Lack of Resources & Rate Limiting

74% of Hanami apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.

RUN FREE SECURITY DIAGNOSTIC
GuardLabs Engine: ONLINE

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.