Skip to content

Instantly share code, notes, and snippets.

@vndee
Last active December 26, 2024 17:02
Show Gist options
  • Save vndee/865b5aede183de5cdb7c6242be0e804f to your computer and use it in GitHub Desktop.
Save vndee/865b5aede183de5cdb7c6242be0e804f to your computer and use it in GitHub Desktop.
from redis_data_structures import RingBuffer
from datetime import datetime, timedelta
class RateLimiter:
def __init__(self, window_size: int, max_requests: int):
self.buffer = RingBuffer("rate-limits", capacity=max_requests)
self.window_size = window_size
def is_allowed(self, client_id: str) -> bool:
key = f"rate_limit:{client_id}"
now = datetime.now()
cutoff = now - timedelta(seconds=self.window_size)
# Cleanup old requests first
requests = self.buffer.get_all(key)
valid_requests = [
req for req in requests
if datetime.fromisoformat(req["timestamp"]) > cutoff
]
if len(valid_requests) >= self.buffer.capacity:
return False
self.buffer.push({"timestamp": now.isoformat()})
return True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment