Replay Requests Through a Per-Key Throttle
Data Structure DesignAuto-graded · 18 test casesLast updated
Simulate a per-key sliding-window throttle over a batch of timed requests, tracking only accepted requests and handling window-boundary expiry correctly.
Per-Key Request Throttle Replay
A service throttles traffic separately for each client identifier. You are given the throttle's configuration and a chronological log of calls. Your job is to replay the log and report whether each call was accepted.
Rules
- The throttle is configured with
max_requests, the largest number of accepted requests a single key may have inside its window, andwindow_size_ms, the window length in milliseconds. - Every entry in
operationsis the string"allow". The entry at the same index inargumentsis a two-element list[key, timestamp], holding the client key and the time of the call in milliseconds. - When a call arrives for
keyat timet, only that key's earlier accepted requests are considered. An earlier accepted request at timesis still active ifs > t - window_size_ms. In other words, the active range is the half-open interval(t - window_size_ms, t]. A request made exactlywindow_size_msmilliseconds earlier has already expired. - If the number of active accepted requests for that key is strictly less than
max_requests, the call is accepted (resultTrue) and counts toward that key's future windows. Otherwise it is rejected (resultFalse). - Rejected calls are not recorded and do not use up any quota.
- Different keys never influence each other.
- Several calls may share the same timestamp, and each one is judged in log order. Timestamps never decrease across the log.
Task
Return a list of booleans, one per call, in the same order as the input.
If max_requests is 0, every call is rejected.
Constraints
operationsandargumentshave the same length.- Every operation is
"allow". - Timestamps are integers and are non-decreasing across the whole log.
max_requests >= 0andwindow_size_ms >= 1.- Aim for amortized constant time per call, not a rescan of the whole history on every call.
Examples
Example 1
Input: replay_throttle(2, 1000, ['allow', 'allow', 'allow', 'allow'], [['user1', 100], ['user1', 500], ['user1', 800], ['user1', 1200]])
Output: [True, True, False, True]
Example 2
Input: replay_throttle(2, 1000, ['allow', 'allow', 'allow', 'allow', 'allow'], [['a', 0], ['b', 0], ['a', 1000], ['b', 1000], ['a', 1001]])
Output: [True, True, True, True, True]
Example 3
Input: replay_throttle(1, 100, ['allow', 'allow', 'allow'], [['x', 10], ['x', 10], ['x', 110]])
Output: [True, False, True]
Hints
Hint 1
Keep a separate queue of accepted timestamps for each key, oldest at the front.
Hint 2
Before deciding, drop timestamps from the front while they are less than or equal to t - window_size_ms. A gap of exactly the window size means the old request has expired.
Hint 3
Only append the current timestamp when the call is accepted. Because timestamps never decrease, the queue stays sorted and each entry is added and removed at most once.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Keep, for each key, a deque of the timestamps of the requests that were accepted, oldest first. For each call at time t:
- Compute
cutoff = t - window_size_msand pop from the front of the key's deque while the front value is<= cutoff. Those requests lie outside the half-open window(t - window_size_ms, t]. - If the deque now holds fewer than
max_requestsentries, accept the call and appendt. Otherwise reject it and leave the deque unchanged.
Append the result to the output list and move on.
Why it is correct
- Timestamps never decrease and we only append at the back, so each deque is sorted. The front is always the oldest entry.
- Since the deque is sorted, once the front is inside the window, everything behind it is too. Stopping at the first non-expired entry removes exactly the expired ones.
- After eviction the deque contains precisely the accepted requests of this key in
(t - window_size_ms, t], so comparing its size tomax_requestsimplements the rule exactly. - Rejected calls are never stored, so they cannot reduce future capacity. Separate deques per key guarantee keys are independent.
- With
max_requests = 0the size check0 < 0always fails, so every call is rejected.
Complexity
- Time: amortized O(1) per call, O(n) overall for
ncalls, because each timestamp is appended once and popped at most once. - Space: O(K · max_requests) for K distinct keys, since only accepted requests are stored and a deque never exceeds
max_requestsentries.
Reference solution
from collections import defaultdict, deque
from typing import List
def replay_throttle(max_requests: int, window_size_ms: int, operations: List[str], arguments: List[List[str]]) -> List[bool]:
accepted = defaultdict(deque)
results = []
for operation, args in zip(operations, arguments):
if operation != "allow":
raise ValueError("unsupported operation")
key, timestamp = args
queue = accepted[key]
cutoff = timestamp - window_size_ms
while queue and queue[0] <= cutoff:
queue.popleft()
if len(queue) < max_requests:
queue.append(timestamp)
results.append(True)
else:
results.append(False)
return results