Rolling-Window Request Throttle Per Client Address
Data Structure DesignAuto-graded · 17 test casesLast updated
Simulate a per-IP sliding-window-log throttle over a sequence of requests, using per-key queues with lazy expiry and strict half-open window boundaries.
Rolling-Window Request Throttle
A gateway protects itself by limiting how often each client address may call it. Every client is tracked separately, and the limit applies over a rolling time span rather than fixed clock buckets.
You are given the throttle's settings and a recorded sequence of calls. Replay the calls in order and report whether each one is admitted.
Rules
max_requestsis the largest number of admitted requests a single address may have inside any rolling window.window_secondsis the length of that window in seconds.- A request from address
ipat integer timetis admitted if the number of previously admitted requests from that same address with times in the half-open interval(t - window_seconds, t]is strictly less thanmax_requests. - An admitted request is remembered for that address. A rejected request is not remembered and never counts toward any later decision.
- An earlier admitted request made exactly
window_secondsbeforet(that is, at timet - window_seconds) is already expired and does not count. - Several requests may share the same timestamp, and each is judged in the order given.
- Different addresses are completely independent.
- Timestamps for any one address never decrease from one call to the next.
Input
max_requests(int): the per-address cap.window_seconds(int): the window length in seconds.operations(list of str): the operation names, one per call. Every entry is"allow_request". If any other name appears, raiseValueError.arguments(list of lists):arguments[i]is[ip, timestamp]for the i-th call, whereipis a string andtimestampis an integer number of seconds.
Output
Return a list of booleans with one entry per call, in order: True if the request was admitted, False otherwise.
Constraints
1 <= max_requests1 <= window_secondstimestamp >= 0len(operations) == len(arguments), up to10^6calls in total.- For a fixed
ip, timestamps are given in non-decreasing order. - Memory for addresses with nothing remembered should not be retained.
Examples
Example 1
Input: replay_ip_throttle(3, 10, ['allow_request', 'allow_request', 'allow_request', 'allow_request', 'allow_request', 'allow_request'], [['10.0.0.1', 1], ['10.0.0.1', 2], ['10.0.0.1', 5], ['10.0.0.1', 8], ['10.0.0.1', 11], ['10.0.0.2', 8]])
Output: [True, True, True, False, True, True]
Example 2
Input: replay_ip_throttle(2, 5, ['allow_request', 'allow_request', 'allow_request', 'allow_request', 'allow_request'], [['a', 0], ['b', 0], ['a', 1], ['a', 5], ['b', 5]])
Output: [True, True, True, True, True]
Hints
Hint 1
Only admitted requests matter for the count, so you only need to store admitted timestamps for each address.
Hint 2
Because an address's timestamps never decrease, its stored timestamps are sorted, so stale ones are always at the front. A double-ended queue per address lets you drop them cheaply.
Hint 3
Expire a stored time s when s <= t - window_seconds (not strictly less). Check the count after expiring, and append only when admitting.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Keep, for each address, a queue of the timestamps of its admitted requests. Since an address's timestamps never decrease, this queue is always sorted, so expired entries are always at the front.
For each call (ip, t):
- Fetch (or create) the queue for
ip. - Compute
cutoff = t - window_secondsand pop from the front while the front value is<= cutoff. Using<=makes the window half-open: a request exactlywindow_secondsold is expired. - If the queue length is less than
max_requests, appendtand recordTrue. Otherwise recordFalseand store nothing. - If the queue ended up empty, remove the address from the map so empty containers do not accumulate.
An unknown operation name raises ValueError.
Why it is correct
Invariant: after handling a call at time t for an address, its queue holds exactly the admitted timestamps of that address inside (t - window_seconds, t], in sorted order.
- Eviction is safe. The cutoff only moves forward for a given address, so an evicted timestamp can never matter again. Anything older than the front was evicted earlier, so inspecting only the front is enough.
- The count is exact. After eviction, the queue length equals the number of admitted requests in the window, and comparing it with
max_requestsusing<matches the "strictly less than" rule. - Rejections are not stored. A rejected request never shortens or extends anyone's allowance, as the rules require.
- Same-second bursts are appended one by one until the cap is reached; the rest are rejected, since
t > t - window_secondsmeans none of them expire early.
Complexity
- Time: each admitted timestamp is appended once and removed at most once, so the total is O(N) for N calls, i.e. O(1) amortized per call.
- Space: each address's queue never exceeds
max_requestsentries, so total space is O(active addresses × max_requests), and at most O(N).
Reference solution
from collections import deque
from typing import List
def replay_ip_throttle(max_requests: int, window_seconds: int, operations: List[str], arguments: List[List]) -> List[bool]:
logs = {}
results = []
for op, args in zip(operations, arguments):
if op != "allow_request":
raise ValueError("unsupported operation")
ip, t = args
q = logs.get(ip)
if q is None:
q = deque()
logs[ip] = q
# Drop admitted requests that fell out of (t - window_seconds, t].
cutoff = t - window_seconds
while q and q[0] <= cutoff:
q.popleft()
if len(q) < max_requests:
q.append(t)
results.append(True)
else:
results.append(False)
# Do not keep empty containers around.
if not q:
del logs[ip]
return results