Sliding-Window Rate Limiter per User

medium
Unit 19 · Rate Limiting0/3 to milestone

A token bucket smooths traffic. Many APIs instead promise "at most N requests in any 60-second window": a sliding window log.

Implement SlidingWindowLimiter(limit, window, clock=time.monotonic):

  • allow(user): record and allow the request if the user made fewer than limit allowed requests in the last window seconds (timestamps t with now - t < window). Rejected requests aren't recorded.
  • retry_after(user): seconds until the user can make another request (0 if they can now).
  • Keep a separate deque of timestamps per user, dropping expired ones from the left.
#rate-limiting#deque#design2 visible + 2 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
Sliding-Window Rate Limiter per User · TechGradify