Protect your application against abusive requests
Install rack-attack
middleware using bundler
,
bundle add rack-attack
For Rails 7 application, the rack-attack
enabled by default 🔋 .
To invoke Rack::Attack
, create a initializer
file along with a simple throttling rule, which will allow maximum 5 request
for a duration of 60 seconds
, as follows,
Rack::Attack.throttle('requests by ip', limit: 5, period: 60.seconds, &:ip)
The only last thing, rack-attack, keeps them in a cache store like :memory_store
, :redis_store
. For sake of simplicity, we are going to use :memory_store
, to do that run the following command from the root directory of your application,
bin/rails dev:cache
This will create an caching-dev.txt
in tmp
directory.
ℹ️ If your application already has cache
a file, you are not required to run the above command.
Hm, all set, try to reload your web application or hit REST APIs, after 5 requests (within 1 minute), you will see the following message, with an HTTP status code 429
, which means Too many requests.
Retry later
👮🏻♀️ watches for abusive requests made.