백엔드 전체 구현 완료: 내부 서비스(Auth, Client, Realtime), API 엔드포인트 및 스케줄러 구현
This commit is contained in:
35
backend/app/core/rate_limiter.py
Normal file
35
backend/app/core/rate_limiter.py
Normal file
@@ -0,0 +1,35 @@
|
||||
import asyncio
|
||||
import time
|
||||
|
||||
class RateLimiter:
|
||||
"""
|
||||
Centralized Request Queue that enforces a physical delay between API calls.
|
||||
Default delay is 250ms (4 requests per second).
|
||||
"""
|
||||
def __init__(self):
|
||||
self._lock = asyncio.Lock()
|
||||
self._last_call_time = 0
|
||||
self._delay = 0.25 # seconds (250ms)
|
||||
|
||||
async def wait(self):
|
||||
"""
|
||||
Acquire lock and sleep if necessary to respect the rate limit.
|
||||
"""
|
||||
async with self._lock:
|
||||
now = time.monotonic()
|
||||
elapsed = now - self._last_call_time
|
||||
|
||||
if elapsed < self._delay:
|
||||
sleep_time = self._delay - elapsed
|
||||
await asyncio.sleep(sleep_time)
|
||||
|
||||
self._last_call_time = time.monotonic()
|
||||
|
||||
def set_delay(self, ms: int):
|
||||
"""
|
||||
Update the delay interval dynamically from DB settings.
|
||||
"""
|
||||
self._delay = ms / 1000.0
|
||||
|
||||
# Singleton instance
|
||||
global_rate_limiter = RateLimiter()
|
||||
Reference in New Issue
Block a user