Two-Tier API Rate Limiter with a Sliding Window
Data Structure DesignModel answerLast updated
Design a thread-safe rate limiter that enforces both a per-endpoint quota and a shared global quota using a rolling time window.
Two-Tier API Rate Limiter with a Sliding Window
Your team operates an API gateway that needs to control traffic at two levels simultaneously: no single endpoint should be hammered beyond its own capacity, and the entire service should not receive more requests than it can handle overall.
Implement a RateLimiter class with the following interface:
class RateLimiter:
def __init__(self, global_limit: int, endpoint_limits: dict[str, int], window_seconds: int):
"""
global_limit – maximum requests allowed across all endpoints combined,
within any rolling window of window_seconds.
endpoint_limits – per-path caps, e.g. {"/login": 10}.
window_seconds – width of the rolling window (positive integer).
"""
def allow_request(self, endpoint: str) -> bool:
"""
Return True if the request may proceed, False if it should be dropped.
Must be safe to call from multiple threads concurrently.
"""
Behaviour rules
- Both limits must pass. A request to a configured endpoint is allowed only when it fits under that endpoint's cap and under the global cap. Exceeding either one causes rejection.
- Sliding window. At the moment a request arrives (time
T), the relevant window is[T − window_seconds, T]. A request from exactlyT − window_secondsis still inside the window. - Rejected requests are not counted. Only admitted requests consume quota. A client retrying a rejected call does not dig itself into a deeper hole.
- Unknown endpoints are subject only to the global limit; they have no per-endpoint cap.
- Memory must stay bounded. Do not retain timestamps that have scrolled outside every relevant window.
- Thread safety. Concurrent calls to
allow_requestmust never produce a race condition that lets more requests through than either limit allows.
Example
global_limit = 100
endpoint_limits = {"/login": 10}
window_seconds = 10
A call to allow_request("/login") at time t = 5 is allowed when:
- the number of admitted
/loginrequests in the interval[-5, 5]is fewer than 10, and - the number of admitted requests across all endpoints in that same interval is fewer than 100.
Constraints
window_secondsis a positive integer.global_limitand any endpoint limit may be 0 (every request is rejected).- The implementation must handle high concurrency with minimal lock contention.
- You may use standard library modules (
threading,collections,time).
Hints
Hint 1
A sliding-window log stores the actual timestamps of admitted requests in a deque. After pruning entries older than `now − window`, the length of the deque is the exact request count for the current window — no arithmetic required.
Hint 2
You need two locks: one per endpoint and one global. Always acquire them in the same order (endpoint first, then global) on every code path. A consistent acquisition order makes deadlock structurally impossible.
Hint 3
Do a cheap pre-check under just the endpoint lock before you ever touch the global lock. If the endpoint is already at its limit you can reject immediately, sparing the shared global lock from the extra contention that comes from hot, throttled endpoints.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core data structure is a sliding-window log: for each counter (one global, one per configured endpoint), keep a deque of the timestamps of every admitted request. When a new request arrives at time T:
- Prune any timestamp older than
T − Wfrom the front of the deque. - Check whether
len(deque) < limit. - If yes, append
Tand admit the request.
Because only admitted requests are appended, a deque can never grow past its configured limit. Memory is therefore bounded by O(global_limit + Σ endpoint_limits) even without any pruning; pruning just keeps the deques small in practice.
Locking strategy
Two counters must be updated atomically together, which requires two locks. The critical decisions are:
- Fixed acquisition order: always take the endpoint lock first, then the global lock. This eliminates the possibility of a deadlock cycle.
- Endpoint pre-check: while holding only the endpoint lock, prune and check the endpoint deque. If it is already full, reject immediately without ever acquiring the global lock. Hot endpoints being throttled are exactly where contention peaks, so this short-circuits the common rejection case cheaply.
- Commit under both locks: the final length checks and both appends happen while holding both locks. No other thread can observe a state between "passed the check" and "recorded the request."
Use time.monotonic() rather than time.time(). Wall-clock time can jump backwards during NTP adjustments, which would corrupt a sorted deque.
Complexity
- Time: amortized O(1) per call. Each timestamp is appended once and popped at most once. A call that prunes a large backlog is O(k), but that cost is amortised over the k earlier admissions that created it.
- Space: O(global_limit + Σ endpoint_limits) as argued above.
Edge cases
| Scenario | Behaviour |
|---|---|
| Limit is 0 | Every request is rejected; 0 >= 0 handles this naturally. |
| Unknown endpoint | Only the global limit applies. |
Timestamp exactly at T − W | Still inside the window (inclusive boundary). |
| Many requests with the same timestamp | Deques hold duplicates fine. |
| Both limits exceeded simultaneously | Rejected; neither counter is updated. |
| Idle endpoint with stale entries | Entries persist until the next call, but they are capped at the endpoint's limit so memory stays bounded. |
Python implementation
import threading
import time
from collections import deque
from typing import Callable, Optional
class RateLimiter:
def __init__(
self,
global_limit: int,
endpoint_limits: dict[str, int],
window_seconds: int,
clock: Callable[[], float] = time.monotonic, # injectable for testing
):
if window_seconds <= 0:
raise ValueError("window_seconds must be positive")
self._window = window_seconds
self._clock = clock
self._global_limit = global_limit
self._global_q: deque[float] = deque()
self._global_lock = threading.Lock()
# Built once at construction; never mutated, so reads need no lock.
self._endpoints: dict[str, tuple[int, deque[float], threading.Lock]] = {
ep: (limit, deque(), threading.Lock())
for ep, limit in endpoint_limits.items()
}
# ------------------------------------------------------------------ #
# Internal helpers #
# ------------------------------------------------------------------ #
def _prune(self, q: deque[float], now: float) -> None:
"""Remove timestamps that have fallen outside the rolling window."""
cutoff = now - self._window # timestamps < cutoff are expired
while q and q[0] < cutoff:
q.popleft()
def _try_global(self, ep_q: Optional[deque[float]]) -> bool:
"""
Check and (if passing) commit the global counter.
ep_q is the endpoint deque to commit alongside; None for unknown endpoints.
Caller must already hold the endpoint lock when ep_q is not None.
"""
with self._global_lock:
now = self._clock() # read under lock → appends are non-decreasing
self._prune(self._global_q, now)
if len(self._global_q) >= self._global_limit:
return False
# Both counters pass — commit atomically.
self._global_q.append(now)
if ep_q is not None:
ep_q.append(now)
return True
# ------------------------------------------------------------------ #
# Public API #
# ------------------------------------------------------------------ #
def allow_request(self, endpoint: str) -> bool:
entry = self._endpoints.get(endpoint)
if entry is None:
# No per-endpoint cap; only the global limit applies.
return self._try_global(None)
limit, ep_q, ep_lock = entry
with ep_lock: # acquire order: endpoint → global
self._prune(ep_q, self._clock())
if len(ep_q) >= limit:
return False # fast-path rejection; global lock never touched
# ep_q is still held, so its length cannot change before _try_global commits.
return self._try_global(ep_q)
Worked example
Using global_limit=100, {"/login": 10}, window_seconds=10: suppose 10 /login calls were admitted in the interval [0, 5].
- An 11th
/loginatt=5fails the endpoint pre-check (10 >= 10) and is rejected before the global lock is touched. - A
/searchrequest at the same moment succeeds because only 10 out of 100 global slots are used.
Common mistakes
- Reading the clock outside the global lock. If
nowis captured before acquiring the lock, two threads can capture different values and append out of order, breaking the sorted-deque invariant that makes left-pruning correct. - Counting rejected requests. Recording a failed attempt lets a persistent client inflate its apparent usage and lock itself out indefinitely.
- Inconsistent lock ordering. Any path that acquires global first and endpoint second creates a potential deadlock with a path that does the reverse.
- Using
time.time()instead oftime.monotonic()— susceptible to clock adjustments.
Scaling to a distributed system
When multiple gateway nodes share traffic, local deques no longer give an accurate global count. The standard approach is to move each counter into a Redis sorted set (score = timestamp, member = unique request ID) and run the entire prune-check-commit sequence as a single Lua script, which Redis executes atomically. This preserves the same logical contract with network latency as the only new cost. For very high throughput, a token-bucket in Redis (using INCR with a TTL) trades some precision for fewer round trips.