Skip to content

Instantly share code, notes, and snippets.

@evenicoulddoit
Created September 17, 2024 16:00
Show Gist options
  • Save evenicoulddoit/b8e89f319eb09c923b745992648bd0a1 to your computer and use it in GitHub Desktop.
Save evenicoulddoit/b8e89f319eb09c923b745992648bd0a1 to your computer and use it in GitHub Desktop.
# Connect to Redis
r = redis.StrictRedis(host='localhost', port=6379, db=0)
# Rate limiter configuration
MAX_REQUESTS = 5 # Maximum number of allowed requests
TIME_WINDOW = 60 # Sliding window size in seconds (e.g., 1 minute)
def is_allowed(client_id):
current_time = int(time.time() * 1000) # Current time in milliseconds
window_start = current_time - (TIME_WINDOW * 1000) # Start of sliding window
# Key for the client's rate limiting sorted set
client_key = f"rate_limit:{client_id}"
# Remove old requests outside the sliding window
r.zremrangebyscore(client_key, 0, window_start)
# Get the number of requests in the current sliding window
request_count = r.zcard(client_key)
if request_count >= MAX_REQUESTS:
return False # Limit exceeded
# Add the current request's timestamp to the sorted set
r.zadd(client_key, {current_time: current_time})
# Set a TTL (time to live) for the key to clean up old clients automatically
r.expire(client_key, TIME_WINDOW)
return True # Request is allowed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment