Skip to content
Open
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
29 changes: 10 additions & 19 deletions lib/vmpooler/api/rate_limiter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,9 @@ def call(env)
client_id = identify_client(request)
endpoint_type = classify_endpoint(request)

# Check rate limits
return rate_limit_response(client_id, endpoint_type) if rate_limit_exceeded?(client_id, endpoint_type, request)

# Track the request
increment_request_count(client_id, endpoint_type)
# Atomically increment and check in one step
current_count = increment_request_count(client_id, endpoint_type)
return rate_limit_response(client_id, endpoint_type) if current_count.nil? || current_count > limit_for(endpoint_type)

@app.call(env)
end
Expand Down Expand Up @@ -58,29 +56,22 @@ def classify_endpoint(request)
:global_per_ip
end

def rate_limit_exceeded?(client_id, endpoint_type, _request)
limit_config = @config[endpoint_type] || @config[:global_per_ip]
key = "vmpooler__ratelimit__#{endpoint_type}__#{client_id}"

current_count = @redis.get(key).to_i
current_count >= limit_config[:limit]
rescue StandardError => e
# If Redis fails, allow the request through (fail open)
warn "Rate limiter Redis error: #{e.message}"
false
def limit_for(endpoint_type)
(@config[endpoint_type] || @config[:global_per_ip])[:limit]
end

def increment_request_count(client_id, endpoint_type)
limit_config = @config[endpoint_type] || @config[:global_per_ip]
key = "vmpooler__ratelimit__#{endpoint_type}__#{client_id}"

@redis.pipelined do |pipeline|
pipeline.incr(key)
pipeline.expire(key, limit_config[:period])
end
count = @redis.incr(key)
# Only set expiry on first request in the window
@redis.expire(key, limit_config[:period]) if count == 1
count
rescue StandardError => e
# Log error but don't fail the request
warn "Rate limiter increment error: #{e.message}"
nil
end

def rate_limit_response(client_id, endpoint_type)
Expand Down
Loading