Skip to content

Instantly share code, notes, and snippets.

@nyku
Created February 9, 2021 14:32
Show Gist options
  • Save nyku/8bd5c64b224e3a4f82955c514d9dbff6 to your computer and use it in GitHub Desktop.
Save nyku/8bd5c64b224e3a4f82955c514d9dbff6 to your computer and use it in GitHub Desktop.
Simple rails rate limiter
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