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

feat: Skip Redis operations if RateLimit is disabled #12226

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
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
12 changes: 10 additions & 2 deletions api/core/app/features/rate_limiting/rate_limit.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ def __new__(cls: type["RateLimit"], client_id: str, max_active_requests: int):

def __init__(self, client_id: str, max_active_requests: int):
self.max_active_requests = max_active_requests
# must be called after max_active_requests is set
if self.disabled():
return
if hasattr(self, "initialized"):
return
self.initialized = True
Expand All @@ -37,6 +40,8 @@ def __init__(self, client_id: str, max_active_requests: int):
self.flush_cache(use_local_value=True)

def flush_cache(self, use_local_value=False):
if self.disabled():
return
self.last_recalculate_time = time.time()
# flush max active requests
if use_local_value or not redis_client.exists(self.max_active_requests_key):
Expand All @@ -63,10 +68,10 @@ def flush_cache(self, use_local_value=False):
redis_client.hdel(self.active_requests_key, *timeout_requests)

def enter(self, request_id: Optional[str] = None) -> str:
if self.disabled():
return RateLimit._UNLIMITED_REQUEST_ID
if time.time() - self.last_recalculate_time > RateLimit._ACTIVE_REQUESTS_COUNT_FLUSH_INTERVAL:
self.flush_cache()
if self.max_active_requests <= 0:
return RateLimit._UNLIMITED_REQUEST_ID
if not request_id:
request_id = RateLimit.gen_request_key()

Expand All @@ -84,6 +89,9 @@ def exit(self, request_id: str):
return
redis_client.hdel(self.active_requests_key, request_id)

def disabled(self):
return self.max_active_requests <= 0

@staticmethod
def gen_request_key() -> str:
return str(uuid.uuid4())
Expand Down
Loading