● Zion Boggan
repos/Sightline/backend/app/core/rate_limit.py
zionboggan.com ↗
22 lines · python
History for this file →
1
"""Minimal in-process sliding-window rate limiter. Production should use Redis (INCR+EXPIRE)
2
so limits hold across workers; this keeps the dev stack dependency-free."""
3
from __future__ import annotations
4
 
5
import time
6
from collections import defaultdict, deque
7
 
8
 
9
class RateLimiter:
10
    def __init__(self, per_minute: int):
11
        self.per_minute = per_minute
12
        self._hits: dict[str, deque[float]] = defaultdict(deque)
13
 
14
    def allow(self, key: str) -> bool:
15
        now = time.monotonic()
16
        window = self._hits[key]
17
        while window and now - window[0] > 60.0:
18
            window.popleft()
19
        if len(window) >= self.per_minute:
20
            return False
21
        window.append(now)
22
        return True