ruby 15 lines · 1 tab

Rate limiting abusive clients with Rack::Attack

Kai Nakamura Apr 2026
1 tab
class Rack::Attack
  throttle('logins/ip', limit: 5, period: 20.seconds) do |request|
    request.ip if request.path == '/users/sign_in' && request.post?
  end

  throttle('password_reset/email', limit: 3, period: 15.minutes) do |request|
    if request.path == '/password_resets' && request.post?
      request.params['email'].to_s.downcase.strip
    end
  end

  self.throttled_responder = lambda do |_env|
    [429, { 'Content-Type' => 'application/json' }, [{ error: 'rate_limited' }.to_json]]
  end
end
1 file · ruby Explain with highlit

Rate limiting is both a security control and an availability control. I use it to slow credential stuffing, login brute force, and noisy scraping without punishing normal use. The trick is keying limits on the right dimensions and emitting metrics so you know whether you are actually blocking abuse.


Related snips

typescript
export type Settled<R> =
  | { status: 'fulfilled'; value: R }
  | { status: 'rejected'; reason: unknown };

export interface ConcurrencyOptions {
  limit: number;

Simple concurrency limiter for batch operations

node concurrency async
by codesnips 2 tabs
ruby
RegistrationSchema = Dry::Schema.Params do
  required(:email).filled(:string, format?: URI::MailTo::EMAIL_REGEXP)
  required(:password).filled(:string, min_size?: 12)
  optional(:marketing_opt_in).filled(:bool)
  optional(:country).filled(:string, included_in?: %w[US CA GB AU])
end

Input validation with allowlists and explicit schemas

input-validation schemas secure-coding
by Kai Nakamura 1 tab
ini
[sshd]
enabled = true
maxretry = 4
findtime = 10m
bantime = 1h

Fail2ban filters to slow SSH and application abuse

fail2ban ssh brute-force
by Kai Nakamura 1 tab
ruby
cookies.encrypted[:trusted_device] = {
  value: { user_id: current_user.id, fingerprint: device_fingerprint }.to_json,
  expires: 30.days.from_now,
  httponly: true,
  secure: Rails.env.production?,
  same_site: :strict,

Signed and encrypted Rails cookies for tamper resistant state

rails cookies encryption
by Kai Nakamura 1 tab
ruby
class Rack::Attack
  Rack::Attack.cache.store = ActiveSupport::Cache::RedisCacheStore.new(url: ENV['REDIS_URL'])

  safelist('allow-localhost') do |req|
    req.ip == '127.0.0.1' || req.ip == '::1'
  end

Rate limiting with Redis and Rack::Attack

rails security redis
by Alex Kumar 1 tab
php
<?php

namespace App\Providers;

use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;

Laravel rate limiting for API protection

laravel rate-limiting api
by Carlos Mendez 2 tabs

Share this code

Here's the card — post it anywhere.

Rate limiting abusive clients with Rack::Attack — share card
Link copied