Last active
December 26, 2024 17:02
-
-
Save vndee/865b5aede183de5cdb7c6242be0e804f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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