Skip to content

Commit 69b9c5f

Browse files
committed
fix(backend): add periodic cleanup to rate_limit to prevent memory growth
Every 60s, evict keys whose newest timestamp is stale (>60s old). Prevents unbounded memory growth from inactive client IPs.
1 parent b993840 commit 69b9c5f

1 file changed

Lines changed: 11 additions & 0 deletions

File tree

backend/services/rate_limiter.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@
1414

1515
# In-memory rate limit storage (per-process, resets on restart)
1616
_rate_limit_store: Dict[str, list] = {}
17+
_last_cleanup: float = 0.0
18+
_CLEANUP_INTERVAL_SEC = 60
1719

1820

1921
def rate_limit(requests_per_minute: int = 60):
@@ -43,6 +45,15 @@ async def wrapper(*args, **kwargs):
4345
now = time.time()
4446
window_start = now - 60
4547

48+
# Periodic cleanup of stale keys to prevent unbounded memory growth
49+
global _last_cleanup
50+
if now - _last_cleanup > _CLEANUP_INTERVAL_SEC:
51+
for k in list(_rate_limit_store.keys()):
52+
timestamps = _rate_limit_store.get(k, [])
53+
if not timestamps or timestamps[-1] <= window_start:
54+
_rate_limit_store.pop(k, None)
55+
_last_cleanup = now
56+
4657
# Clean old entries and get current count
4758
if key not in _rate_limit_store:
4859
_rate_limit_store[key] = []

0 commit comments

Comments
 (0)