Nothing runs between calls. So an expired record sits in your dict until a read filters it out or a write removes it. That's why every read applies the window, counts and snapshots included.
One tick too many changes the answers
Here's a rate limiter that allows 2 requests per user in any 10 seconds, with the window written once. Next to it is a copy whose window includes its end.
class RateLimiter:
"""At most `limit` allowed requests per user in any `window` seconds."""
def __init__(self, limit: int, window: int) -> None:
self.limit, self.window = limit, window
# user -> times of allowed requests, oldest first
self._allowed: dict[str, list[int]] = {}
def _in_window(self, t: int, now: int) -> bool:
return t <= now < t + self.window
def allow(self, user: str, now: int) -> bool:
recent = [t for t in self._allowed.get(user, []) if self._in_window(t, now)]
if len(recent) >= self.limit:
return False
self._allowed[user] = recent + [now]
return True
class InclusiveLimiter(RateLimiter):
def _in_window(self, t: int, now: int) -> bool:
return t <= now <= t + self.window
half_open, inclusive = RateLimiter(2, 10), InclusiveLimiter(2, 10)
for now in [0, 5, 9, 10, 11, 15]:
print(now, half_open.allow("u", now), inclusive.allow("u", now))