Per-User Rolling-Window Rate Limiter

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Design a thread-safe per-user rate limiter that caps how many requests each user may perform inside a moving window of window_size seconds.

Specifically, implement a RateLimiter(limit, window_size) class with an allow_request(user_id) method alongside the judge entry point:

def simulate_rate_limiter(limit: int, window_size: int, operations: List[str], arguments: List[List]) -> List[bool]:

Each client identified by user_id is permitted at most limit accepted requests within any half-open rolling interval (t - window_size, t], where t is the timestamp (in seconds) of the incoming check:

  • If the user currently has fewer than limit previously accepted requests with timestamps strictly greater than t - window_size (and <= t), accept the request, record t for that user, and return True.
  • Otherwise, reject the request without recording t and return False. Rejected calls never consume quota or extend future lockouts.
  • A request accepted at timestamp t - window_size is already window_size seconds old at time t, so it no longer counts against the user's quota.
  • Different user_id values do not share quotas.
  • RateLimiter.allow_request must remain safe when invoked concurrently by multiple threads, run in amortized O(1) time per call, and avoid unbounded memory retention for long-idle users.

For deterministic evaluation, simulate_rate_limiter instantiates a limiter configured with (limit, window_size) and processes operations paired with arguments: when operations[i] == "allow_request", arguments[i] is [user_id, timestamp], and the function returns the list of boolean decisions in call order.

Examples

Example 1

  • Input:
    • limit = 2, window_size = 10
    • operations = ["allow_request", "allow_request", "allow_request", "allow_request", "allow_request"]
    • arguments = [["svc_a", 3], ["svc_a", 7], ["svc_a", 12], ["svc_a", 13], ["svc_a", 16]]
  • Output: [True, True, False, True, False]
  • Explanation:
    • At t = 3 and t = 7, "svc_a" has 0 and 1 prior accepted calls inside (-7, 3] and (-3, 7], so both return True (stored timestamps: [3, 7]).
    • At t = 12, both 3 and 7 still lie inside (2, 12], hitting capacity 2, so the call returns False and 12 is not saved.
    • At t = 13, the active window (3, 13] drops 3 (3 <= 13 - 10), leaving only [7], so 13 is accepted ([7, 13]).
    • At t = 16, both 7 and 13 lie inside (6, 16], so the call returns False.

Example 2

  • Input:
    • limit = 2, window_size = 4
    • operations = ["allow_request", "allow_request", "allow_request", "allow_request", "allow_request"]
    • arguments = [["mia", 20], ["leo", 20], ["mia", 21], ["mia", 23], ["leo", 23]]
  • Output: [True, True, True, False, True]
  • Explanation: "mia" and "leo" maintain independent quotas. By t = 23, "mia" already has two accepted timestamps (20 and 21) inside (19, 23] and is denied, whereas "leo" only has [20] and is accepted.

Example 3

  • Input:
    • limit = 3, window_size = 2
    • operations = ["allow_request", "allow_request", "allow_request", "allow_request", "allow_request"]
    • arguments = [["api_9", 5], ["api_9", 5], ["api_9", 5], ["api_9", 5], ["api_9", 7]]
  • Output: [True, True, True, False, True]
  • Explanation: Four simultaneous calls arrive at t = 5; the first three fill capacity 3 and the fourth is rejected. At t = 7, all three calls from t = 5 fall outside (5, 7] and expire, allowing the new call.

Constraints

  • 1 <= limit <= 10,000
  • 1 <= window_size <= 3,600 (seconds)
  • user_id is a non-empty string.
  • operations[i] is "allow_request" and arguments[i] is [user_id, timestamp], where timestamps are non-decreasing numeric values (int or float).
  • allow_request must be thread-safe and achieve amortized O(1) time per request while keeping memory bounded relative to currently active users.

Step-by-step walkthrough

  1. Understand the rolling window and judge harness

    We want to build a thread-safe RateLimiter(limit, window_size) class whose allow_request(user_id) permits at most limit accepted calls per user inside any rolling span of window_size seconds.

    Because an automated test suite cannot pause for real minutes or hours, the judge calls a driver simulate_rate_limiter(limit, window_size, operations, arguments) where each arguments[i] supplies [user_id, timestamp]. Making now an optional parameter on allow_request(user_id, now=None) lets production callers omit it (reading the system clock automatically) while tests inject exact timestamps.

    Let's confirm the exact rules on Example 1:

    Example 1: limit = 2, window_size = 10, user_id = "svc_a"
      t =  3 -> True   (window (-7, 3] has []        -> record 3)
      t =  7 -> True   (window (-3, 7] has {3}       -> record 7)
      t = 12 -> False  (window (2, 12] has {3, 7}    -> denied, NOT recorded)
      t = 13 -> True   (window (3, 13] drops 3 <= 3  -> {7} left, record 13)
      t = 16 -> False  (window (6, 16] has {7, 13}   -> denied, NOT recorded)
    

    Notice two things:

    1. The active rolling window at now is (now - window_size, now]. A request accepted at now - window_size is already window_size seconds old and has expired (s <= now - window_size).
    2. Denied requests (False) are not recorded. If the denied call at t = 12 had been recorded, (3, 13] would hold {7, 12} and wrongly block t = 13.
  2. Why a flat request log fails on both speed and memory

    A brute-force limiter appends every allowed (user_id, timestamp) pair to a single list and scans the entire list on every new request to count matching entries inside (now - window_size, now].

    That approach breaks down in two ways:

    • Speed degrades forever: every call scans all historical requests ever served, growing linearly with uptime instead of O(1).
    • Memory leaks across millions of users: timestamps older than window_size seconds can never affect any future decision (since clocks move forward), yet keeping them — or keeping empty entries for millions of one-time users — wastes gigabytes of RAM.
  3. Core data structure: one timestamp deque per user

    Give each active user a deque (double-ended queue from collections, which supports O(1) appends on the right and O(1) pops from the left) holding only that user's allowed timestamps in chronological order:

    user_times for "svc_a" (limit = 2, window_size = 10):
    
      oldest                                    newest
      +-----+-----+                             +-----+------+
      | 3.0 | 7.0 |  --- at now = 13.0 --->     | 7.0 | 13.0 |
      +-----+-----+      cutoff = 3.0           +-----+------+
         ^               pop 3.0 <= 3.0,
       popleft()         then append 13.0
    

    Because timestamps arrive in non-decreasing order, all expired timestamps (<= now - window_size) sit together at the left end:

    1. Pop from the left while user_times[0] <= now - window_size.
    2. If len(user_times) >= limit, return False.
    3. Otherwise append now to the right and return True.

    Every allowed timestamp is appended once and popped at most once, making per-user updates amortized O(1) (constant average work per call), and each user's deque holds at most limit timestamps.

  4. Thread safety: why check-and-append must share one lock

    Without synchronization, two threads handling the same user can hit a race condition (a bug where interleaved thread execution corrupts shared logic):

    limit = 2, "svc_a" currently has deque([3.0]) (length 1):
    
      Thread A: checks len(user_times) < 2  --> True!
      Thread B: checks len(user_times) < 2  --> True!   (Thread A hasn't appended yet!)
      Thread A: appends 4.0, returns True
      Thread B: appends 4.0, returns True               (BUG: 3 requests allowed in window!)
    

    Even in CPython, the interpreter can switch threads right between checking len(user_times) and calling user_times.append(now).

    Wrapping the entire operation inside a single threading.Lock (with self.lock:) eliminates this race. Better yet, when now is not supplied by a test, we call time.monotonic() inside with self.lock: — a monotonic clock never jumps backward during system clock adjustments, and reading it inside the lock guarantees timestamps are appended in non-decreasing order.

  5. Memory safety: evicting quiet users with an OrderedDict

    Per-user popleft() only runs when that specific user makes another request. What if 5 million visitors each make one request and never come back? Plain dictionary keys would stay in memory forever!

    We solve this in O(1) amortized time using an OrderedDict (a dictionary that remembers insertion order and can move any key to the back in O(1) time with move_to_end):

    self.allowed_times (OrderedDict ordered by LATEST allowed timestamp):
    
      Front (least recent user)                      Back (most recent user)
      +-------------------+    +-------------------+    +-------------------+
      | "leo": [1.0, 2.0] | -> | "mia": [6.0]      | -> | "kai": [4.0, 9.0] |
      +-------------------+    +-------------------+    +-------------------+
                ^
      At now = 8.0, window_size = 5.0 (cutoff = 3.0):
      1. Check front ("leo"): newest time is 2.0 <= 3.0 -> ALL of leo's times expired! Delete "leo".
      2. Check new front ("mia"): newest time is 6.0 > 3.0 -> STOP! Every user behind "mia" is >= 6.0 too.
    

    Whenever a user is allowed a request at now, we call self.allowed_times.move_to_end(user_id). That keeps users sorted from oldest deque[-1] at the front to newest deque[-1] at the back, so _forget_idle_users can peel off completely expired users from the front and stop at the very first active user.

  6. Implement the RateLimiter class

    Putting the deque, mutex lock, and OrderedDict idle-user cleanup together gives a clean, self-contained RateLimiter class:

    from collections import OrderedDict, deque
    import threading
    import time
    
    
    class RateLimiter:
        """Thread-safe per-user sliding-window rate limiter."""
    
        def __init__(self, limit: int, window_size: float):
            self.limit = limit
            self.window_size = window_size
            # allowed_times: OrderedDict mapping user_id (str) -> deque of allowed float timestamps
            # sorted oldest-to-newest, e.g. {"svc_a": deque([3.0, 7.0])}.
            # Users themselves are kept ordered by their LATEST allowed request (least recent first).
            self.allowed_times: "OrderedDict[str, deque]" = OrderedDict()
            # A single mutex guards clock reads, expiry, quota checks, and OrderedDict updates across threads.
            self.lock = threading.Lock()
    
        def _forget_idle_users(self, cutoff: float) -> None:
            """Delete inactive users from the front whose latest allowed request is <= cutoff."""
            while self.allowed_times:
                oldest_user = next(iter(self.allowed_times))
                oldest_deque = self.allowed_times[oldest_user]
                # Because users are ordered by their newest timestamp (oldest_deque[-1]),
                # the first user still active inside the window proves every later user is active too.
                if oldest_deque and oldest_deque[-1] > cutoff:
                    break
                del self.allowed_times[oldest_user]
    
        def allow_request(self, user_id: str, now: Optional[float] = None) -> bool:
            if self.limit <= 0:
                return False
    
            with self.lock:
                # Read the monotonic clock inside the lock so timestamps enter deques in non-decreasing order.
                if now is None:
                    now = time.monotonic()
    
                # Rolling window is (now - window_size, now]: a request at `now - window_size` has just expired.
                cutoff = now - self.window_size
    
                # Phase 1: Reclaim memory from quiet users whose entire timestamp history has expired.
                self._forget_idle_users(cutoff)
    
                # Phase 2: Pop this user's own expired timestamps from the left of their deque.
                user_times = self.allowed_times.get(user_id)
                if user_times is None:
                    user_times = deque()
                while user_times and user_times[0] <= cutoff:
                    user_times.popleft()
    
                # Phase 3: Enforce capacity; denied requests are never recorded and do not extend lockouts.
                if len(user_times) >= self.limit:
                    if not user_times and user_id in self.allowed_times:
                        del self.allowed_times[user_id]
                    return False
    
                # Phase 4: Record the allowed timestamp and move this user to the most-recent end.
                user_times.append(now)
                self.allowed_times[user_id] = user_times
                self.allowed_times.move_to_end(user_id)
                return True
    
  7. Implement the simulation driver and trace Example 1

    The judge entry point simulate_rate_limiter instantiates RateLimiter(limit, window_size) and replays each [user_id, timestamp] operation:

    def simulate_rate_limiter(limit: int, window_size: int, operations: List[str], arguments: List[List]) -> List[bool]:
        limiter = RateLimiter(limit, window_size)
        results: List[bool] = []
        for op, args in zip(operations, arguments):
            if op == "allow_request":
                user_id, timestamp = args[0], args[1]
                results.append(limiter.allow_request(user_id, timestamp))
            else:
                raise ValueError(f"Unknown operation: {op}")
        return results
    

    Tracing Example 1 (limit = 2, window_size = 10 for "svc_a"):

    call | now | cutoff | deque after popleft | len < 2? | return | deque stored
    -----+-----+--------+---------------------+----------+--------+-------------
      1  |  3  |   -7   | []                  |   Yes    |  True  | [3]
      2  |  7  |   -3   | [3]                 |   Yes    |  True  | [3, 7]
      3  | 12  |    2   | [3, 7]              |   No     |  False | [3, 7]
      4  | 13  |    3   | [7] (3 <= 3 popped) |   Yes    |  True  | [7, 13]
      5  | 16  |    6   | [7, 13]             |   No     |  False | [7, 13]
    

    Output: [True, True, False, True, False].

  8. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    from collections import OrderedDict, deque
    import threading
    import time
    
    
    class RateLimiter:
        """Thread-safe per-user sliding-window rate limiter."""
    
        def __init__(self, limit: int, window_size: float):
            self.limit = limit
            self.window_size = window_size
            # allowed_times: OrderedDict mapping user_id (str) -> deque of allowed float timestamps
            # sorted oldest-to-newest, e.g. {"svc_a": deque([3.0, 7.0])}.
            # Users themselves are kept ordered by their LATEST allowed request (least recent first).
            self.allowed_times: "OrderedDict[str, deque]" = OrderedDict()
            # A single mutex guards clock reads, expiry, quota checks, and OrderedDict updates across threads.
            self.lock = threading.Lock()
    
        def _forget_idle_users(self, cutoff: float) -> None:
            """Delete inactive users from the front whose latest allowed request is <= cutoff."""
            while self.allowed_times:
                oldest_user = next(iter(self.allowed_times))
                oldest_deque = self.allowed_times[oldest_user]
                # Because users are ordered by their newest timestamp (oldest_deque[-1]),
                # the first user still active inside the window proves every later user is active too.
                if oldest_deque and oldest_deque[-1] > cutoff:
                    break
                del self.allowed_times[oldest_user]
    
        def allow_request(self, user_id: str, now: Optional[float] = None) -> bool:
            if self.limit <= 0:
                return False
    
            with self.lock:
                # Read the monotonic clock inside the lock so timestamps enter deques in non-decreasing order.
                if now is None:
                    now = time.monotonic()
    
                # Rolling window is (now - window_size, now]: a request at `now - window_size` has just expired.
                cutoff = now - self.window_size
    
                # Phase 1: Reclaim memory from quiet users whose entire timestamp history has expired.
                self._forget_idle_users(cutoff)
    
                # Phase 2: Pop this user's own expired timestamps from the left of their deque.
                user_times = self.allowed_times.get(user_id)
                if user_times is None:
                    user_times = deque()
                while user_times and user_times[0] <= cutoff:
                    user_times.popleft()
    
                # Phase 3: Enforce capacity; denied requests are never recorded and do not extend lockouts.
                if len(user_times) >= self.limit:
                    if not user_times and user_id in self.allowed_times:
                        del self.allowed_times[user_id]
                    return False
    
                # Phase 4: Record the allowed timestamp and move this user to the most-recent end.
                user_times.append(now)
                self.allowed_times[user_id] = user_times
                self.allowed_times.move_to_end(user_id)
                return True
    
    
    def simulate_rate_limiter(limit: int, window_size: int, operations: List[str], arguments: List[List]) -> List[bool]:
        limiter = RateLimiter(limit, window_size)
        results: List[bool] = []
        for op, args in zip(operations, arguments):
            if op == "allow_request":
                user_id, timestamp = args[0], args[1]
                results.append(limiter.allow_request(user_id, timestamp))
            else:
                raise ValueError(f"Unknown operation: {op}")
        return results
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine a gym check-in desk enforcing "at most limit entries per member in any rolling window_size-second span." Each active member gets a small index card listing their recent accepted entry times from oldest at the top to newest at the bottom, and all member cards sit in a tray ordered from least-recently-seen at the front to most-recently-seen at the back. When a member badges in at now, the receptionist first tosses out any cards at the very front of the tray whose newest entry is already at least window_size seconds old, then crosses off expired timestamps from the top of this member's card, and lets them in only if fewer than limit timestamps remain — writing now at the bottom and moving their card to the back of the tray.

A naive log that stores every (user_id, timestamp) forever forces each check to scan a growing history (O(total_requests) per call) and eventually runs out of memory across millions of inactive users. Splitting time into fixed buckets (0..W, W..2W, ...) uses O(1) counters per user, but fails precision at bucket edges: a user can send limit requests just before W and limit more just after W, firing 2 * limit requests inside a tiny span. Pairing a per-user deque (a double-ended queue with O(1) front removal and back insertion) with an OrderedDict (a hash map that maintains key order and moves keys to the back in O(1) time) gives exact rolling-window enforcement, thread safety under a mutex lock, and automatic memory cleanup.

Walk through Example 1 (limit = 2, window_size = 10) for "svc_a" at timestamps 3, 7, 12, 13, 16: 1. t = 3: "svc_a" has deque([]); 0 < 2, so record 3 -> deque([3]), return True. 2. t = 7: cutoff = -3; 3 > -3 stays; 1 < 2, so record 7 -> deque([3, 7]), return True. 3. t = 12: cutoff = 2; deque([3, 7]) has length 2 == limit, so return False without recording 12. 4. t = 13: cutoff = 13 - 10 = 3; 3 <= 3 is popped from the left, leaving deque([7]) (length 1 < 2), so record 13 -> deque([7, 13]), return True. 5. t = 16: cutoff = 6; both 7 and 13 exceed 6, so deque([7, 13]) stays full (2 == limit) and returns False.

Complexity

Let L = limit be the maximum requests allowed per window and A be the number of users who had at least one allowed request within the last window_size seconds.

  • Time: amortized O(1) per allow_request call (amortized O(1) means that although a single call after a quiet gap may pop multiple expired timestamps or idle users, the average cost per call over any sequence of M requests is O(1)). Every allowed timestamp is appended to a deque once and popped at most once, and every user entry in OrderedDict is inserted/moved once per allowed request and deleted at most once.
  • Space: O(A * L). Inactive users older than window_size are deleted from the front of OrderedDict, and each active user's deque never exceeds L timestamps because new timestamps are appended only when len(user_times) < L.

Edge cases

  • Brand-new user with no history: creates a fresh deque, passes 0 < limit, records now, and returns True without creating stale entries if denied.
  • Simultaneous burst at the exact same timestamp (t = 5, 5, 5, 5): the first limit calls return True and append 5; every subsequent call at t = 5 sees len == limit and returns False.
  • Exact window boundary (s == now - window_size): because the active window is (now - window_size, now], user_times[0] <= cutoff (<=, not <) evicts a request made at 3 when now = 3 + window_size.
  • Denied requests do not penalize future windows: returning False before user_times.append(now) ensures rejected retries do not prolong a user's lockout.
  • Sub-second floating-point timestamps and 1-hour (3,600s) / 10,000-capacity limits: deque operations and float comparisons (<= now - window_size) stay O(1) amortized at both extremes.
  • Millions of one-time users: _forget_idle_users evicts inactive users as soon as their window elapses, preventing unbounded dictionary growth.

Common mistakes

  • Using < instead of <= during eviction: user_times[0] < now - window_size keeps a timestamp that is already window_size seconds old, failing Example 1 (t = 3 vs t = 13) and Example 3 (t = 5 vs t = 7).
  • Appending timestamps for denied requests: turns a temporary burst into a rolling self-inflicted ban.
  • Locking only append instead of the full check-then-act sequence: creates a race condition (concurrent threads interleaving between len(user_times) < limit and append) that lets simultaneous threads exceed limit.
  • Calling time.time() or reading the clock outside the lock: wall-clock time.time() can jump backward during NTP clock syncs (use time.monotonic(), a clock guaranteed never to go backward), and reading the clock before acquiring self.lock lets threads append timestamps out of order, breaking the sorted invariant that popleft() relies on.
  • Using list.pop(0) instead of deque.popleft(): shifting a 10,000-element Python list on every pop turns O(1) eviction into O(L) per request (O(L^2) over a window).

Alternative approaches

  • Sliding-window counter (approximate, O(1) memory per user): store only two integers per user — the count in the current fixed window and the count in the previous fixed window — and estimate the rolling count as current_count + previous_count * overlap_ratio. Cuts per-user memory from O(L) timestamps to O(1) integers, at the cost of assuming requests in the previous window were evenly spaced.
  • Lock striping for higher multi-core concurrency: instead of one global threading.Lock, hash each user_id into one of K independent buckets (bucket = hash(user_id) % K), each with its own Lock, OrderedDict, and _forget_idle_users queue. Different users in different stripes no longer contend on the same lock while idle-user pruning stays local to each stripe.

Follow-up questions

  • How would you adapt this rate limiter when traffic is spread across a fleet of stateless backend servers that must enforce one shared per-user quota? Either route each user_id to a sticky limiter node via consistent hashing (a hashing scheme that maps each user to one server while minimizing remapping when servers join or leave), or store per-user state in a shared store like Redis. In Redis, represent each user's sliding window as a sorted set (an ordered collection where score = timestamp and member = unique_request_id so simultaneous sub-millisecond requests do not overwrite each other), and execute "evict scores <= now - W, check cardinality < L, add (now, req_id), and set EXPIRE W" inside one atomic Lua script (run single-threaded by Redis without interleaving) using Redis's server clock so clock skew and cross-server races cannot violate limit.
  • How can the service reclaim memory from inactive user IDs that send a few requests and never return? Our implementation already solves this online in amortized O(1) time by keeping users in an OrderedDict ordered by their newest allowed timestamp (move_to_end on every allowed call) and deleting front entries whose newest timestamp is <= now - window_size. Two practical alternatives are: (1) a background sweeper thread that periodically scans shards of the map and deletes empty/expired user deques, or (2) in Redis, attaching a key TTL (EXPIRE user_key window_size) on every allowed request so Redis automatically reclaims idle users. Avoid a fixed-capacity LRU cache (Least Recently Used eviction that drops entries purely by count) if the cache cap is smaller than active users, because evicting an in-window user forgets their recent requests and resets their quota!
  • How do token-bucket and leaky-bucket limiters compare with an exact rolling-window log in memory footprint, burst behavior, and boundary accuracy? A token bucket stores just two floats per user (tokens and last_refill_time), refills tokens continuously at rate L / W up to capacity L, and consumes 1 token per allowed request; a leaky bucket models a queue of capacity L that drains requests at a steady rate L / W, smoothing bursts into a uniform output stream. Both use strict O(1) memory per user (2 numbers instead of up to 10,000 timestamps) and O(1) worst-case time, making them lighter to store in memory or Redis. The trade-off is boundary accuracy: a full token bucket of size L lets a user burst L requests at t = 0 and earn almost L more refilled tokens across (0, W], allowing nearly 2L requests inside one W-second span, whereas the rolling-window log guarantees strictly at most L requests in every (now - W, now] interval.

Follow-up questions

Similar questions

More Atlassian interview questions

All 55 Atlassian questions →