Created
February 9, 2021 14:32
-
-
Save nyku/8bd5c64b224e3a4f82955c514d9dbff6 to your computer and use it in GitHub Desktop.
Simple rails rate limiter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'redis' | |
require 'digest' | |
class RateLimit | |
def initialize(app) | |
@app = app | |
end | |
def call(env) | |
redis = Redis.new | |
timeout_seconds = 2 | |
post_body = env['rack.input'].read | |
env['rack.input'].rewind | |
fingerprint_elements = [ env["ORIGINAL_FULLPATH"], env["REMOTE_ADDR"], env["REQUEST_METHOD"], post_body ] | |
fingerprint = Digest::SHA2.hexdigest(fingerprint_elements.join("")) | |
if redis.get(fingerprint) | |
return [429, { 'Content-Type' => 'text/html' }, [ "Too Many Requests" ]] | |
else | |
redis.setex(fingerprint, timeout_seconds, 1) | |
@app.call(env) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment