Implement an in-memory sliding-window rate limiter
Write allow_request(key: str, limit: int, window_sec: float) -> bool using a deque of timestamps and monotonic time.
Model Answer & Explanation
from collections import defaultdict, deque
import time
class SlidingWindowLimiter:
def __init__(self, limit: int, window_sec: float):
self.limit = limit
self.window = window_sec
self.hits = defaultdict(deque)
def allow(self, key: str) -> bool:
now = time.monotonic()
q = self.hits[key]
while q and now - q[0] >= self.window:
q.popleft()
if len(q) >= self.limit:
return False
q.append(now)
return True Store a deque of request timestamps per key. On each call, use time.monotonic() (never wall-clock time.time() which can jump), pop timestamps older than now - window_sec from the left, check len(q) < limit, and if allowed append now. Clean up empty keys periodically or bound dict size to avoid memory leaks.