Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rate limiting #236

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions app.rb
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
class TreeStats < Sinatra::Base
configure :production do
use Sentry::Rack::CaptureExceptions
use RateLimiter, limit: 100, seconds: 60
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This means 100 requests are allowed every 60 seconds per IP address.
These numbers aren't based on any real data.

We could configure by environment variable.

end

set :root, File.dirname(__FILE__)
Expand Down
37 changes: 37 additions & 0 deletions lib/rate_limiter.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
require "redis"

class RateLimiter
def initialize(app, options = {})
@app = app
@limit = options[:limit] || 100
@seconds = options[:seconds] || 60
@redis = Redis.new
end

def call(env)
ip = env['REMOTE_ADDR']
key = build_key(ip)

count = increment(key)

if count > @limit
[429, { 'Content-Type' => 'text/plain' }, ['Rate limit exceeded']]
else
@app.call(env)
end
end

private

def build_key(ip)
"rate_limiter:#{ip}:#{Time.now.to_i / @seconds}"
Copy link
Contributor Author

@jkisor jkisor Jan 10, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You may decide on a different key.

end

def increment(key)
count = @redis.incr(key)

@redis.expire(key, @seconds) if count == 1

count
end
end