Per-User Rolling Quota Gate with Concurrent Access
Data Structure DesignModel answerLast updated
Design a thread-safe class that caps how many requests each user may make in any trailing time interval, avoiding the burst problem of fixed windows, with sub-linear cost per check.
Rolling Quota Gate
Build a RateLimiter class that enforces a per-user quota over a trailing time interval. A fixed-window counter is not acceptable, because it lets a user send a full quota just before a boundary and another full quota just after it. Your design must make sure that any interval of the configured length contains no more than the allowed number of accepted requests.
Interface
RateLimiter(capacity, window_size_seconds)creates a limiter that allows at mostcapacityaccepted requests per user in any interval ofwindow_size_secondsseconds.allow(user_id)decides whether the current request fromuser_idis accepted. It returnsTrueif so andFalseif the user is over quota.
Requirements
- Quotas are tracked independently per user.
- The class must be safe to call from many threads at once.
- The cost of
allow()must be better than O(N), where N is the number of requests currently inside the window. - You may use
time.time()for the current time in seconds. - A request recorded exactly
window_size_secondsago no longer counts against the quota.
Example
# Up to 2 requests per 5 seconds
limiter = RateLimiter(2, 5)
limiter.allow(1) # True
limiter.allow(1) # True
limiter.allow(1) # False (quota used up)
# ...5 seconds go by...
limiter.allow(1) # True
What to discuss
- What do you store for each user, and why?
- How do you discard outdated entries cheaply?
- Which locking strategy do you pick, and what does it cost in contention?
- Should rejected requests count toward the quota?
- How would the design change if the service ran on many machines?
Provide the implementation, explain its complexity, and justify your concurrency approach.
Hints
Hint 1
Keep a time-ordered queue of timestamps per user. Because time only moves forward, the oldest entries are always at one end, so you never need to scan the whole collection.
Hint 2
Think about which requests should be recorded. If rejected calls were also stored, a client that keeps retrying would never recover. Record only accepted requests.
Hint 3
Evicting stale timestamps, checking the size and appending a new one form a check-then-act sequence. Protect it with a lock per user, and guard the creation of a user's entry with a short global lock. Read the clock while holding the user lock so stored timestamps stay in order.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach: per-user sliding log
Keep a dictionary mapping each user_id to a deque of timestamps of accepted requests, oldest on the left. For each call to allow(user_id):
- Read the current time
now. - Pop from the left while the oldest timestamp satisfies
ts <= now - window. These entries have aged out. - If the deque has fewer than
capacityentries, appendnowand returnTrue. Otherwise returnFalse.
Why a sliding log and not a fixed window
A fixed-window counter resets at boundaries. A user can send capacity requests at 4.9s and another capacity at 5.1s, so twice the quota arrives within 0.2s. The sliding log counts exactly the requests in the trailing interval ending at now, so every interval of length window holds at most capacity accepted requests.
Design decisions to state explicitly
- Only accepted requests are stored. Recording rejected ones would let a retrying client lock itself out indefinitely and would allow unbounded memory growth. With this rule each deque holds at most
capacityitems. - Boundary rule. An entry exactly
windowseconds old is expired (ts <= now - window). This matches the example, where the first request no longer counts after 5 seconds. - Reading the clock inside the user lock. Appended timestamps are then non-decreasing, which keeps the deque sorted and makes left-side eviction correct.
Thread safety
The sequence evict, check, append is a check-then-act race. Two threads could both see capacity - 1 entries and both append, exceeding the quota. It must be atomic per user.
| Option | Pros | Cons |
|---|---|---|
| One global lock | Trivial and obviously correct | All users contend on one lock |
| Lock per user plus a short map lock | Different users never block each other | Slightly more code; the map lock is still needed for first-time creation |
The implementation below uses the second option. The global lock is held only for an O(1) dictionary lookup or insert, and the per-user lock covers the deque operations.
Correctness argument
Invariant: after allow() returns for a user, the deque holds exactly that user's accepted requests in (now - window, now], sorted.
- Appends happen under the user lock with a clock read taken inside it, so order is preserved and expired items are always a prefix.
- After eviction,
len(deque)equals the count of accepted requests in the current window. Accepting only when this is belowcapacitybounds every window bycapacity. - The user lock serializes concurrent calls, so each call observes the result of the previous one.
Complexity
- Time: amortized O(1) per call. Each timestamp is appended once and popped at most once. A single call may pop many entries after a long idle spell, but the total pops never exceed the total appends. Filtering a list on every call would be O(N), which the constraint rules out.
- Space: O(U · capacity) in the worst case for U active users, since rejected requests are never stored.
Code
import threading
import time
from collections import deque
class RateLimiter:
def __init__(self, capacity: int, window_size_seconds: int, clock=time.time):
if capacity < 0:
raise ValueError("capacity must be non-negative")
if window_size_seconds <= 0:
raise ValueError("window_size_seconds must be positive")
self.capacity = capacity
self.window = window_size_seconds
self._clock = clock
self._logs = {} # user_id -> deque of timestamps
self._locks = {} # user_id -> Lock
self._map_lock = threading.Lock() # guards both dicts
def _state_for(self, user_id):
with self._map_lock:
lock = self._locks.get(user_id)
if lock is None:
lock = threading.Lock()
self._locks[user_id] = lock
self._logs[user_id] = deque()
return lock, self._logs[user_id]
def allow(self, user_id: int) -> bool:
lock, log = self._state_for(user_id)
with lock:
now = self._clock()
cutoff = now - self.window
while log and log[0] <= cutoff:
log.popleft()
if len(log) < self.capacity:
log.append(now)
return True
return False
A deterministic test uses an injectable clock:
t = [0.0]
limiter = RateLimiter(2, 5, clock=lambda: t[0])
assert limiter.allow(1) is True
assert limiter.allow(1) is True
assert limiter.allow(1) is False
t[0] = 5.0
assert limiter.allow(1) is True
Edge cases
capacity == 0rejects everything;window <= 0or negative capacity is invalid input.- A request exactly one window after an old one sees the old one as expired.
- Several requests with identical timestamps are fine, since the deque only needs non-decreasing order.
- Wall-clock time can jump backwards when NTP adjusts it. In production prefer
time.monotonic(). - Idle users leave empty or stale entries behind. A periodic sweep or an LRU policy that removes users whose newest timestamp is older than the window keeps memory bounded.
Common mistakes
- Using a fixed-window counter and allowing boundary bursts.
- Logging rejected requests.
- Using
<instead of<=in the eviction test, which breaks the boundary example. - Locking only the dictionary but not the deque, or reading the clock before acquiring the user lock.
- Filtering the whole list on each call, giving O(N) per request.
Follow-up: multiple servers
Local memory no longer works when one user's requests land on different nodes. Two main options:
- Central store. Use Redis with a sorted set per user, with a unique member per request. Run these steps as one atomic Lua script: remove entries with score at or below
now - window, count the rest, add the new entry if under capacity, and set a TTL equal to the window. Use the store's own clock to avoid skew between nodes, and shard keys byuser_id. - Sticky routing. Consistent-hash
user_idto one limiter node so the local implementation still applies. This saves network hops but needs care when nodes fail or the ring rebalances.
Trade-offs: every check adds a network round trip, and you must choose fail-open or fail-closed when the store is unreachable. If approximate enforcement is acceptable, each node can apply capacity / num_nodes locally. A cheaper alternative with less precision is a sliding-window counter that weights the previous and current fixed windows, using O(1) memory per user instead of a log.