Rails API - Throttling with Rack::Attack

Episode #52 by Teacher's Avatar David Kimura

Summary

Save expensive calculation time using Rack::Attack, we will learn how to limit requests coming into our application. This gem not only limits requests, but can be used to blacklist or whitelist users as well.
rails api security 7:10

Resources

Summary

# Gemfile
gem 'rack-attack'

# config/application.rb
module Template
  class Application < Rails::Application
    ...
    config.middleware.use Rack::Attack
  end
end

# config/initializers/rack_attack.rb
class Rack::Attack
  Rack::Attack.cache.store = ActiveSupport::Cache::MemoryStore.new 

  throttle('api/ip', limit: 3, period: 10) do |req|
    req.ip if req.subdomain == 'api'
  end

  class Request < ::Rack::Request
    def subdomain
      host.split('.').first
    end
  end
end