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
limitpreviously accepted requests with timestamps strictly greater thant - window_size(and<= t), accept the request, recordtfor that user, and returnTrue. - Otherwise, reject the request without recording
tand returnFalse. Rejected calls never consume quota or extend future lockouts. - A request accepted at timestamp
t - window_sizeis alreadywindow_sizeseconds old at timet, so it no longer counts against the user's quota. - Different
user_idvalues do not share quotas. RateLimiter.allow_requestmust remain safe when invoked concurrently by multiple threads, run in amortizedO(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 = 10operations = ["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 = 3andt = 7,"svc_a"has0and1prior accepted calls inside(-7, 3]and(-3, 7], so both returnTrue(stored timestamps:[3, 7]). - At
t = 12, both3and7still lie inside(2, 12], hitting capacity2, so the call returnsFalseand12is not saved. - At
t = 13, the active window(3, 13]drops3(3 <= 13 - 10), leaving only[7], so13is accepted ([7, 13]). - At
t = 16, both7and13lie inside(6, 16], so the call returnsFalse.
- At
Example 2
- Input:
limit = 2,window_size = 4operations = ["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. Byt = 23,"mia"already has two accepted timestamps (20and21) inside(19, 23]and is denied, whereas"leo"only has[20]and is accepted.
Example 3
- Input:
limit = 3,window_size = 2operations = ["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 capacity3and the fourth is rejected. Att = 7, all three calls fromt = 5fall outside(5, 7]and expire, allowing the new call.
Constraints
1 <= limit <= 10,0001 <= window_size <= 3,600(seconds)user_idis a non-empty string.operations[i]is"allow_request"andarguments[i]is[user_id, timestamp], where timestamps are non-decreasing numeric values (intorfloat).allow_requestmust be thread-safe and achieve amortizedO(1)time per request while keeping memory bounded relative to currently active users.
Step-by-step walkthrough
Understand the rolling window and judge harness
We want to build a thread-safe
RateLimiter(limit, window_size)class whoseallow_request(user_id)permits at mostlimitaccepted calls per user inside any rolling span ofwindow_sizeseconds.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 eacharguments[i]supplies[user_id, timestamp]. Makingnowan optional parameter onallow_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:
- The active rolling window at
nowis(now - window_size, now]. A request accepted atnow - window_sizeis alreadywindow_sizeseconds old and has expired (s <= now - window_size). - Denied requests (
False) are not recorded. If the denied call att = 12had been recorded,(3, 13]would hold{7, 12}and wrongly blockt = 13.
- The active rolling window at
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_sizeseconds 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.
- Speed degrades forever: every call scans all historical requests ever served, growing linearly with uptime instead of
Core data structure: one timestamp deque per user
Give each active user a
deque(double-ended queue fromcollections, which supportsO(1)appends on the right andO(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.0Because timestamps arrive in non-decreasing order, all expired timestamps (
<= now - window_size) sit together at the left end:- Pop from the left while
user_times[0] <= now - window_size. - If
len(user_times) >= limit, returnFalse. - Otherwise append
nowto the right and returnTrue.
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 mostlimittimestamps.- Pop from the left while
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 callinguser_times.append(now).Wrapping the entire operation inside a single
threading.Lock(with self.lock:) eliminates this race. Better yet, whennowis not supplied by a test, we calltime.monotonic()insidewith 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.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 anOrderedDict(a dictionary that remembers insertion order and can move any key to the back inO(1)time withmove_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 callself.allowed_times.move_to_end(user_id). That keeps users sorted from oldestdeque[-1]at the front to newestdeque[-1]at the back, so_forget_idle_userscan peel off completely expired users from the front and stop at the very first active user.Implement the RateLimiter class
Putting the deque, mutex lock, and
OrderedDictidle-user cleanup together gives a clean, self-containedRateLimiterclass: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 TrueImplement the simulation driver and trace Example 1
The judge entry point
simulate_rate_limiterinstantiatesRateLimiter(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 resultsTracing Example 1 (
limit = 2, window_size = 10for"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].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)perallow_requestcall (amortizedO(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 ofMrequests isO(1)). Every allowed timestamp is appended to a deque once and popped at most once, and every user entry inOrderedDictis inserted/moved once per allowed request and deleted at most once. - Space:
O(A * L). Inactive users older thanwindow_sizeare deleted from the front ofOrderedDict, and each active user's deque never exceedsLtimestamps because new timestamps are appended only whenlen(user_times) < L.
Edge cases
- Brand-new user with no history: creates a fresh
deque, passes0 < limit, recordsnow, and returnsTruewithout creating stale entries if denied. - Simultaneous burst at the exact same timestamp (
t = 5, 5, 5, 5): the firstlimitcalls returnTrueand append5; every subsequent call att = 5seeslen == limitand returnsFalse. - 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 at3whennow = 3 + window_size. - Denied requests do not penalize future windows: returning
Falsebeforeuser_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:dequeoperations and float comparisons (<= now - window_size) stayO(1)amortized at both extremes. - Millions of one-time users:
_forget_idle_usersevicts inactive users as soon as their window elapses, preventing unbounded dictionary growth.
Common mistakes
- Using
<instead of<=during eviction:user_times[0] < now - window_sizekeeps a timestamp that is alreadywindow_sizeseconds old, failing Example 1 (t = 3vst = 13) and Example 3 (t = 5vst = 7). - Appending timestamps for denied requests: turns a temporary burst into a rolling self-inflicted ban.
- Locking only
appendinstead of the full check-then-act sequence: creates a race condition (concurrent threads interleaving betweenlen(user_times) < limitandappend) that lets simultaneous threads exceedlimit. - Calling
time.time()or reading the clock outside the lock: wall-clocktime.time()can jump backward during NTP clock syncs (usetime.monotonic(), a clock guaranteed never to go backward), and reading the clock before acquiringself.locklets threads append timestamps out of order, breaking the sorted invariant thatpopleft()relies on. - Using
list.pop(0)instead ofdeque.popleft(): shifting a10,000-element Python list on every pop turnsO(1)eviction intoO(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 ascurrent_count + previous_count * overlap_ratio. Cuts per-user memory fromO(L)timestamps toO(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 eachuser_idinto one ofKindependent buckets (bucket = hash(user_id) % K), each with its ownLock,OrderedDict, and_forget_idle_usersqueue. 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_idto 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 wherescore = timestampandmember = unique_request_idso simultaneous sub-millisecond requests do not overwrite each other), and execute "evict scores<= now - W, check cardinality< L, add(now, req_id), and setEXPIRE 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 violatelimit. - 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 anOrderedDictordered by their newest allowed timestamp (move_to_endon 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 (
tokensandlast_refill_time), refills tokens continuously at rateL / Wup to capacityL, and consumes1token per allowed request; a leaky bucket models a queue of capacityLthat drains requests at a steady rateL / W, smoothing bursts into a uniform output stream. Both use strictO(1)memory per user (2numbers instead of up to10,000timestamps) andO(1)worst-case time, making them lighter to store in memory or Redis. The trade-off is boundary accuracy: a full token bucket of sizeLlets a user burstLrequests att = 0and earn almostLmore refilled tokens across(0, W], allowing nearly2Lrequests inside oneW-second span, whereas the rolling-window log guarantees strictly at mostLrequests in every(now - W, now]interval.
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?
- How can the service reclaim memory from inactive user IDs that send a few requests and never return?
- How do token-bucket and leaky-bucket limiters compare with an exact rolling-window log in memory footprint, burst behavior, and boundary accuracy?
Similar questions
- Minimum Tennis Courts for Concurrent Reservations
- Minimum Court Allocation for Match Reservations
- Fixed-Window Moving Average Over a Numeric Stream
- Reciprocal-Depth Sum of Nested Lists
- Sliding-Window Mean Over an Integer Stream
- Segment-Trie Path Router with Single-Segment Wildcards
More Atlassian interview questions
- Minimum Court Allocation for Match Reservations Medium
- Merge Overlapping Intervals Medium
- Two-by-Three React Feed Grid: Static Data, API Fetch, and Hooks Hard Pro
- Design a Trending Workspace Content Leaderboard Medium Pro
- Frontend Architecture for Live Search Over an Unbounded Catalog Hard Pro
- Music Playback State Machine with Queue, Loop, and Shuffle Medium Pro
- Distributed API Rate Limiter Architecture Easy Pro
- Post Comments and Notification Architecture Medium Pro
- Multi-Tenant Tagging Service and REST API Medium Pro
- Hybrid RBAC and Resource ACL Authorization Service Medium Pro