No. 06medium25 min16 tests

Sliding Window Rate Limiter

Description

An API gateway allows each user at most limit requests in any rolling window of window seconds. Implement the limiter.

class SlidingWindowRateLimiter:
    def __init__(self, limit: int, window: float): ...
    def allow(self, user_id: str, timestamp: float) -> bool: ...

Constructor

Raise ValueError unless limit is a positive int and window is a positive int or float. Booleans are not allowed for either, and NaN is not positive.

allow(user_id, timestamp)

Return True and record the request if the user has fewer than limit allowed requests in the window (timestamp - window, timestamp]. Otherwise return False.

  • The window is open on the left. A request made exactly window seconds ago no longer counts.
  • Only allowed requests are recorded. A rejected request does not use up quota.
  • Users are independent.
  • Strip user_id, so " alice " and "alice" are the same user.
  • Raise ValueError if user_id is not a string or is empty after stripping.
  • Raise ValueError if timestamp is not an int or float, is a bool, is negative, or is NaN.

Example

limiter = SlidingWindowRateLimiter(limit=2, window=5)
limiter.allow("alice", 0)   # True
limiter.allow("alice", 1)   # True
limiter.allow("alice", 2)   # False, 2 requests in (-3, 2]
limiter.allow("bob", 2)     # True, bob has his own window
limiter.allow("alice", 5)   # True, the request at 0 left the window (0, 5]
limiter.allow("alice", 5.5) # False, 1 and 5 are still in (0.5, 5.5]

Constraints

  • Timestamps for a given user arrive in non-decreasing order.
  • Up to 10^5 calls. Each call should cost amortized O(1), not O(limit) or O(history).

Solution

Reference solution and explanationTry it first. The explanation covers the approach, complexity, pitfalls and follow-ups.
Reveal solution

Approach

This is the sliding window log algorithm. Keep a deque of allowed timestamps per user, oldest on the left. On each call:

  1. Pop from the left while the oldest timestamp is <= timestamp - window. Those requests are outside (timestamp - window, timestamp].
  2. If the deque still holds limit entries, reject.
  3. Otherwise append the timestamp and allow.

Since timestamps per user only move forward, anything expired once stays expired, so each entry is appended once and popped at most once. A defaultdict(deque) creates a user's log on first sight.

Validate everything before touching state. A call that raises must not leave a half-recorded request.

Complexity

Amortized O(1) per call. Space is O(limit) per active user, since a log never grows past limit entries.

Pitfalls

  • Using < instead of <= when expiring. The window is open on the left, so a request exactly window old must go.
  • Recording rejected requests. That turns the limiter into a penalty box where a client that keeps retrying is locked out forever.
  • Using a list and list.pop(0) or a filter comprehension on every call. That is O(n) per call.
  • isinstance(True, int) is True, so booleans slip through isinstance checks.
  • Logs for users who went quiet are never freed. Fine for an interview, but worth naming.
  • Rejecting timestamps with timestamp < 0. NaN passes that check, and a recorded NaN never expires because every comparison with it is false, so the user is locked out for good. Write not timestamp >= 0.

Follow-ups interviewers ask

  • Memory per user is O(limit). Compare the sliding window counter (two fixed-window counts, weighted by overlap) and the token bucket, which are O(1) per user but approximate.
  • Run it across several gateway instances. Move state to Redis, using a sorted set per user with ZREMRANGEBYSCORE plus ZCARD plus ZADD inside a Lua script or MULTI so the check and record are atomic.
  • Evict idle users: drop a user's deque when it empties, or run a periodic sweep.
  • Return how long the client should wait (Retry-After): log[0] + window - timestamp when rejected.
  • Make it async-safe. With asyncio on one thread, allow has no await, so it is already atomic. With real threads you need a lock per user or a global lock.

Reference solution

from collections import defaultdict, deque


def _is_number(value) -> bool:
    return type(value) in (int, float)


class SlidingWindowRateLimiter:
    def __init__(self, limit: int, window: float):
        if type(limit) is not int or limit <= 0:
            raise ValueError(f"limit must be a positive int, got {limit!r}")
        if not _is_number(window) or not window > 0:
            raise ValueError(f"window must be a positive number, got {window!r}")
        self.limit = limit
        self.window = window
        self._allowed: dict[str, deque] = defaultdict(deque)

    def allow(self, user_id: str, timestamp: float) -> bool:
        if not isinstance(user_id, str) or not user_id.strip():
            raise ValueError(f"invalid user_id {user_id!r}")
        if not _is_number(timestamp) or not timestamp >= 0:
            raise ValueError(f"invalid timestamp {timestamp!r}")

        log = self._allowed[user_id.strip()]
        while log and log[0] <= timestamp - self.window:
            log.popleft()
        if len(log) >= self.limit:
            return False
        log.append(timestamp)
        return True

Notes

solution.pySaved
class SlidingWindowRateLimiter:
    def __init__(self, limit: int, window: float):
        """Validate limit and window. Track allowed timestamps per user."""
        pass

    def allow(self, user_id: str, timestamp: float) -> bool:
        """
        Allow and record the request if the user has fewer than `limit`
        allowed requests in (timestamp - window, timestamp].
        """
        raise NotImplementedError
Python loads on first run

Run checks the 2 example tests. Submit runs all 16 and marks the problem solved when they pass.