Build a Concurrent Multi-Constraint Rate Limiter
Data Structure DesignModel answerLast updated
Design a thread-safe class that enforces several independent rate limits simultaneously, with atomic all-or-nothing permit acquisition and rollback on failure.
Concurrent Multi-Constraint Rate Limiter
A rate limiter controls how many requests a system allows over time. Your task is to build one that can enforce several rules at once — for example, "no more than 10 requests per second AND no more than 100 requests per minute" — in a multithreaded environment.
What to implement
A RateLimiter class with the following interface:
class RateLimiter:
def add_rule(self, capacity: int, window_ms: int) -> int: ...
def try_acquire(self) -> bool: ...
def release(self) -> bool: ...
add_rule(capacity, window_ms)
Register a new constraint: at most capacity requests are allowed within any rolling window_ms-millisecond period. Returns an identifier for the rule. Raises ValueError if either argument is not a positive integer.
try_acquire()
Try to claim a permit. A permit is granted only when every registered rule has room. Returns True on success, False otherwise. Must be non-blocking — never wait for capacity to free up.
release()
Call this when a request that was successfully acquired later fails (for example, the handler raises an exception). It returns the permit to the pool so that capacity is not wasted. Returns True if a permit was successfully returned, False if there was nothing to release.
Constraints
- Between 1 and 10 rules may be active at any time.
- Rules may be added dynamically after the limiter is already running.
try_acquiremust be atomic across all rules: if any single rule cannot accommodate the request, no permits are consumed anywhere — not even in the rules that had room.- The implementation must be correct under high concurrency (many threads calling
try_acquiresimultaneously).
Usage example
limiter = RateLimiter()
limiter.add_rule(10, 1000) # max 10 requests per second
limiter.add_rule(100, 60000) # max 100 requests per minute
if limiter.try_acquire():
try:
process_request()
except Exception:
limiter.release() # failed — give the slot back
Edge cases to handle
release()is called when no permit is currently outstanding (e.g., called twice, or never acquired).- A rule is removed between the time a permit is acquired and the time
release()is called. - Many threads attempt
try_acquireat the exact same millisecond. try_acquireis called when no rules have been registered yet.- A permit's window expires before
release()is called — the refund should not push the count below zero.
What is expected
A working Python implementation with a brief explanation of:
- the data structure chosen for each rule's window tracking
- how atomicity is guaranteed across multiple rules
- how
release()correctly handles the edge cases above - time and space complexity
You do not need to handle distributed deployments, but be ready to discuss how you would extend the design to one.
Hints
Hint 1
A sliding window log — a deque of grant timestamps per rule — lets you count how many requests fall inside the current window just by discarding entries older than `now - window_ms`. Consider what that means for both checking and committing a permit.
Hint 2
Split `try_acquire` into two phases inside one critical section: first *read* every rule to see whether all of them have room, then — only if all pass — *write* the timestamp to every rule. This separates the decision from the side effect.
Hint 3
To make `release()` work correctly, record a small receipt at acquire time: the timestamp and the set of rule IDs that were charged. On release, look up that receipt and remove the timestamp only from rules that are still present and whose window has not yet expired.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core challenge has two parts: choosing a per-rule data structure that accurately counts requests in a rolling window, and guaranteeing that a multi-rule check-and-consume is atomic.
Per-rule tracking: sliding window log
Each rule maintains a deque of millisecond timestamps, one entry per granted request. Before inspecting a rule, expired entries (those where now - ts >= window_ms) are evicted from the front. After eviction, len(deque) is the exact number of live permits. A rule is full when that count equals its capacity.
This is more accurate than a fixed-window counter, which would reset every full second and allow a burst of 2× capacity straddling a boundary. The cost is O(capacity) space per rule, which is fine given the 1–10 rule limit and practically bounded capacities.
Atomicity with a single lock and two-phase commit
A single threading.Lock guards all rule state. try_acquire runs two phases inside one with self._lock block:
- Check phase — evict expired entries from every rule, then verify
len(log) < capacityfor each one. If any rule fails, returnFalseimmediately without changing anything. - Commit phase — only reached if every rule passed. Append
nowto every rule's log.
Because no state is mutated until all rules have been confirmed to have room, a rejected request leaves the limiter unchanged. Two threads cannot race through the check simultaneously and both append, because the lock serialises them.
Using lock.acquire(blocking=False) to skip waiting would cause correct threads to be spuriously rejected under contention. A short critical section is the right trade-off here.
Release and rollback
release() needs to undo one prior acquisition without an explicit argument. The solution is a grant receipt stored at acquire time: a (timestamp, tuple_of_rule_ids) entry appended to a second deque. release() pops the most recent receipt and removes that timestamp from each rule that was charged.
Three edge cases are handled cleanly:
- Rule removed after acquire — the rule ID is gone from
self._rules; skip it. - Window already expired —
deque.remove(ts)raisesValueError; catch it and move on. The permit already left via natural expiry, so no adjustment is needed and the count cannot go negative. - Rule added after acquire — it was never charged, so it is never touched.
Receipts older than the largest active window are pruned during eviction, since all their timestamps have already expired in every rule. A late release() for such a receipt becomes a no-op.
Complexity
| Operation | Time | Notes |
|---|---|---|
add_rule | O(1) | Dictionary insert under lock |
try_acquire | O(R) amortised | Each timestamp appended and evicted once; R ≤ 10 |
release | O(R · C) worst case | deque.remove is O(C); refunds are rare in practice |
Space: O(Σ capacities) for the logs, plus O(outstanding grants) for receipts — bounded by the same sum.
Common mistakes
- Mutating state before all rules are checked. Appending
nowto rule A before checking rule B means a rejection on B leaves a phantom permit in A. Always separate the check from the commit. - Calling
blocking=Falseon the lock. This causes valid requests to fail under heavy concurrency rather than serialising briefly. Non-blockingtry_acquiremeans the method returns without waiting for capacity, not without waiting for the lock. - Going below zero on release. If you remove a timestamp unconditionally, a double-release or a post-expiry release produces a negative count, which makes future requests pass when they shouldn't. Guard with a
try/except ValueError. - Forgetting the no-rules case. When
self._rulesis empty the check loop passes vacuously and the request is granted, which is the correct behaviour — there are no constraints to violate.
Implementation
import threading
import time
from collections import deque
from itertools import count
from typing import Callable, Optional
class RateLimiter:
def __init__(self, clock: Optional[Callable[[], int]] = None):
# Inject a custom clock (returns ms) for deterministic testing.
self._clock = clock or (lambda: time.monotonic_ns() // 1_000_000)
self._lock = threading.Lock()
# rule_id -> (capacity, window_ms, deque of grant timestamps)
self._rules: dict = {}
self._id_gen = count()
# Grant receipts: deque of (timestamp, tuple_of_rule_ids), oldest first
self._grants: deque = deque()
def add_rule(self, capacity: int, window_ms: int) -> int:
if capacity <= 0 or window_ms <= 0:
raise ValueError("capacity and window_ms must be positive")
with self._lock:
rule_id = next(self._id_gen)
self._rules[rule_id] = (capacity, window_ms, deque())
return rule_id
def remove_rule(self, rule_id: int) -> bool:
with self._lock:
return self._rules.pop(rule_id, None) is not None
def _evict(self, now: int) -> None:
"""Remove expired timestamps from every rule. Also prune old receipts."""
for _, window_ms, log in self._rules.values():
while log and log[0] <= now - window_ms:
log.popleft()
# Receipts older than the longest window can never be refunded usefully.
horizon = max((w for _, w, _ in self._rules.values()), default=0)
while self._grants and self._grants[0][0] <= now - horizon:
self._grants.popleft()
def try_acquire(self) -> bool:
with self._lock:
now = self._clock()
self._evict(now)
# Phase 1: check — no state is changed yet.
for capacity, _, log in self._rules.values():
if len(log) >= capacity:
return False
# Phase 2: commit — only reached when all rules have room.
for _, _, log in self._rules.values():
log.append(now)
# Record a receipt so release() knows what to undo.
self._grants.append((now, tuple(self._rules.keys())))
return True
def release(self) -> bool:
with self._lock:
if not self._grants:
return False # nothing outstanding; never adjust counts below zero
now = self._clock()
self._evict(now)
ts, rule_ids = self._grants.pop() # most recent outstanding grant
for rule_id in rule_ids:
entry = self._rules.get(rule_id)
if entry is None:
continue # rule was removed after the acquire; nothing to refund
log = entry[2]
try:
log.remove(ts) # O(C) but refunds are the exceptional path
except ValueError:
pass # timestamp already expired naturally; skip to avoid undercount
return True
Extending to a distributed environment
The single-lock approach does not cross process boundaries. To scale out, replace each per-rule deque with a Redis sorted set (score = timestamp). A Lua script performs the eviction check and conditional append atomically on the Redis side — Lua scripts run serially within a single Redis instance, giving the same two-phase guarantee without a distributed lock. For multi-region deployments, a strong consistency store or a gossip-based token bucket with acceptable approximation error becomes the next design conversation.