Sliding-Window Request Throttler by Client IP
Medium · Coding & Algorithms · Software Engineer · Online Assessment
Problem Statement
An API gateway inspects a chronological log of n incoming requests, where request i arrives at integer timestamp timestamps[i] from client address ip_addresses[i]. Under the gateway's throttling policy, no single client IP may accumulate more than limit permitted requests within any trailing half-open interval of width time_window.
Evaluate the log sequentially from index 0 to n - 1 and return 1 for each permitted request or 0 for each throttled request:
def rate_limit(
timestamps: list[int],
ip_addresses: list[str],
limit: int,
time_window: int,
) -> list[int]:
Throttling Rules
- Sequential order: Requests arrive in non-decreasing timestamp order (
timestamps[0] <= timestamps[1] <= ... <= timestamps[n - 1]). Arrivals sharing the exact same timestamp are evaluated in index order. - Per-IP active window: When deciding request
iat timet = timestamps[i]from addressip = ip_addresses[i], count prior indicesj < ithat satisfy all of:ip_addresses[j] == ip(compared as raw exact strings; distinct strings never share quota),- request
jwas permitted (1) — throttled (0) requests are discarded and never consume quota for later arrivals, and timestamps[j]lies strictly abovet - time_window, i.e., inside(t - time_window, t]. An arrival at exactlyt - time_windowhas already expired.
- Decision: If that active count is strictly below
limit, permit requesti(1) and recordtforip; otherwise throttle requesti(0) without recordingt.
Examples
Example 1
Input:
timestamps = [2, 4, 5, 6, 7, 8]
ip_addresses = [
"172.16.0.5", "172.16.0.5", "172.16.0.9",
"172.16.0.5", "172.16.0.5", "172.16.0.5"
]
limit = 2
time_window = 5
Output: [1, 1, 1, 0, 1, 0]
Walk-through:
- t = 2 and t = 4 (172.16.0.5) are both permitted ([2, 4]), and t = 5 (172.16.0.9) uses an independent quota (1).
- At t = 6 (172.16.0.5), the active interval (1, 6] still holds [2, 4], reaching limit = 2, so t = 6 is throttled (0) and not stored.
- At t = 7 (172.16.0.5), 2 <= 7 - 5 has expired from (2, 7], leaving only [4], so t = 7 is permitted ([4, 7]).
- At t = 8 (172.16.0.5), (3, 8] holds [4, 7], so t = 8 is throttled (0).
Example 2
Input:
timestamps = [12, 12, 12, 12]
ip_addresses = ["203.0.113.42", "203.0.113.42", "203.0.113.42", "203.0.113.42"]
limit = 2
time_window = 8
Output: [1, 1, 0, 0]
Walk-through:
- All four requests share timestamp 12 from 203.0.113.42. The first two fill the limit = 2 budget inside (4, 12], and the remaining two are throttled.
Example 3
Input:
timestamps = [3, 9, 14, 15, 20]
ip_addresses = [
"198.51.100.8", "198.51.100.8", "198.51.100.8",
"198.51.100.8", "198.51.100.8"
]
limit = 1
time_window = 6
Output: [1, 1, 0, 1, 0]
Walk-through:
- t = 3 is permitted (1).
- At t = 9, 3 == 9 - 6 sits on the excluded left boundary of (3, 9], so 3 has expired and t = 9 is permitted (1).
- At t = 14, 9 remains inside (8, 14], throttling t = 14 (0).
- At t = 15, 9 == 15 - 6 expires from (9, 15], permitting t = 15 (1), which then blocks t = 20 inside (14, 20] (0).
Constraints
1 <= n <= 10^5, wheren = len(timestamps) == len(ip_addresses)0 <= timestamps[i] <= 10^9, withtimestamps[i] <= timestamps[i + 1]for all0 <= i < n - 11 <= limit <= 10^51 <= time_window <= 10^9- Each
ip_addresses[i]is a non-empty string of length1to45.
Step-by-step walkthrough
Understand the sliding-window rule
We receive
nrequests in chronological order (timestamps[0] <= timestamps[1] <= ...), each paired with anipstring, and must return a list of1(permitted) or0(throttled) decisions of lengthn.When request
iarrives atcurrent_time = timestamps[i]fromip = ip_addresses[i], we count earlier requestsj < ithat satisfy all three conditions:- Same IP address:
ip_addresses[j] == ip(exact string match; different IPs are completely independent). - Previously permitted: request
jreturned1(throttled requests are never stored and never count toward future limits). - Strictly inside the window:
timestamps[j] > current_time - time_window.
Timeline at current_time = 9 with time_window = 6: 3 4 5 ... 8 9 ---o------------------------*]---> time ^ ^ cutoff = 3 current_time = 9 (included) (excluded: 3 <= 3) Active interval is (3, 9], covering integer times 4..9If fewer than
limitearlier permitted requests fromiplie inside(current_time - time_window, current_time], we permit (1) and recordcurrent_time; otherwise we throttle (0) and record nothing.- Same IP address:
Start with a literal brute-force scan
We can translate the specification directly into nested loops: for each request
i, look back over every earlier indexj < iand count matching permitted requests.def rate_limit_slow(timestamps, ip_addresses, limit, time_window): decisions = [] for i in range(len(timestamps)): current_time = timestamps[i] cutoff = current_time - time_window count = 0 for j in range(i): if ( ip_addresses[j] == ip_addresses[i] and decisions[j] == 1 and timestamps[j] > cutoff ): count += 1 if count < limit: decisions.append(1) else: decisions.append(0) return decisionsThis reference logic is great for cross-checking tests, but across
n = 10^5requests it performs roughlyn^2 / 2 = 5 * 10^9checks — far too slow for a one-second limit.Key idea: one monotonic queue per IP
Two observations eliminate the inner loop completely:
- Group by IP: Only requests from the same
ipaffect one another, so store a separate sequence of permitted timestamps per IP in a dictionaryaccepted_by_ip. - The window only slides right: Because
timestampsnever decreases,cutoff = current_time - time_windownever decreases either. Any permitted timestamp that falls at or beforecutofftoday will also be at or beforecutofffor every future request — we can discard it permanently!
Since we append timestamps in non-decreasing order, the oldest permitted timestamp for an IP is always at index
0(the front). Storing each IP's timestamps in adeque(a double-ended queue fromcollectionsthat pops from the front inO(1)constant time, unlikelist.pop(0)which shifts the entire list) lets us strip expired timestamps from the front and checklen(window) < limitinO(1)time:IP "172.16.0.5" in Example 1 (limit = 2, time_window = 5): t=2: cutoff=-3, deque=[] -> len 0 < 2 -> PERMIT, deque=[2] t=4: cutoff=-1, deque=[2] -> len 1 < 2 -> PERMIT, deque=[2, 4] t=6: cutoff=1, deque=[2, 4] -> len 2 == 2 -> THROTTLE, deque stays [2, 4] t=7: cutoff=2, pop 2 (<= 2) -> deque=[4], len 1 < 2 -> PERMIT, deque=[4, 7] t=8: cutoff=3, deque=[4, 7] -> len 2 == 2 -> THROTTLE, deque stays [4, 7]- Group by IP: Only requests from the same
Implement the per-request loop
For each
(current_time, ip)pair:- Fetch (or create)
window = accepted_by_ip[ip]. - Compute
cutoff = current_time - time_windowand pop from the front whilewindow[0] <= cutoff. - If
len(window) < limit, appendcurrent_timetowindowand append1todecisions; otherwise append0without touchingwindow.
from collections import deque def rate_limit(timestamps: list[int], ip_addresses: list[str], limit: int, time_window: int) -> list[int]: # accepted_by_ip: dict mapping ip -> deque of accepted timestamps [t_oldest, ..., t_newest] accepted_by_ip: Dict[str, deque] = {} # decisions: 1 (accepted) or 0 (rejected) for each request in arrival order decisions: List[int] = [] for current_time, ip in zip(timestamps, ip_addresses): if ip not in accepted_by_ip: accepted_by_ip[ip] = deque() window = accepted_by_ip[ip] # Phase 1 (Evict expired timestamps): Active interval is (current_time - time_window, current_time]. # Use <= because an arrival at `current_time - time_window` has already expired, and since # timestamps never decrease, evicted entries can never re-enter a later interval. cutoff = current_time - time_window while window and window[0] <= cutoff: window.popleft() # Phase 2 (Decide): Record the timestamp only on acceptance so denied arrivals consume no quota. if len(window) < limit: window.append(current_time) decisions.append(1) else: decisions.append(0) return decisions- Fetch (or create)
Trace Example 1 and Example 3
Let's verify both tricky rules — unrecorded throttling and exact window boundaries — on our examples:
Example 1 (limit = 2, time_window = 5): req 0: t=2, ip=172.16.0.5 | cutoff=-3 | after pop: [] | len 0 < 2 -> 1 | after: [2] req 1: t=4, ip=172.16.0.5 | cutoff=-1 | after pop: [2] | len 1 < 2 -> 1 | after: [2, 4] req 2: t=5, ip=172.16.0.9 | cutoff=0 | after pop: [] | len 0 < 2 -> 1 | after: [5] req 3: t=6, ip=172.16.0.5 | cutoff=1 | after pop: [2, 4] | len 2 == 2 -> 0 | after: [2, 4] req 4: t=7, ip=172.16.0.5 | cutoff=2 | pop 2 -> [4] | len 1 < 2 -> 1 | after: [4, 7] req 5: t=8, ip=172.16.0.5 | cutoff=3 | after pop: [4, 7] | len 2 == 2 -> 0 | after: [4, 7] Result: [1, 1, 1, 0, 1, 0] Example 3 (limit = 1, time_window = 6, all ip = 198.51.100.8): req 0: t=3 | cutoff=-3 | after pop: [] | len 0 < 1 -> 1 | after: [3] req 1: t=9 | cutoff=3 | pop 3 -> [] | len 0 < 1 -> 1 | after: [9] req 2: t=14 | cutoff=8 | 9 > 8 stays | len 1 == 1 -> 0 | after: [9] req 3: t=15 | cutoff=9 | pop 9 -> [] | len 0 < 1 -> 1 | after: [15] req 4: t=20 | cutoff=14 | 15 > 14 stays | len 1 == 1 -> 0 | after: [15] Result: [1, 1, 0, 1, 0]Full solution
from typing import Any, Dict, List, Optional, Set, Tuple from collections import deque def rate_limit(timestamps: list[int], ip_addresses: list[str], limit: int, time_window: int) -> list[int]: # accepted_by_ip: dict mapping ip -> deque of accepted timestamps [t_oldest, ..., t_newest] accepted_by_ip: Dict[str, deque] = {} # decisions: 1 (accepted) or 0 (rejected) for each request in arrival order decisions: List[int] = [] for current_time, ip in zip(timestamps, ip_addresses): if ip not in accepted_by_ip: accepted_by_ip[ip] = deque() window = accepted_by_ip[ip] # Phase 1 (Evict expired timestamps): Active interval is (current_time - time_window, current_time]. # Use <= because an arrival at `current_time - time_window` has already expired, and since # timestamps never decrease, evicted entries can never re-enter a later interval. cutoff = current_time - time_window while window and window[0] <= cutoff: window.popleft() # Phase 2 (Decide): Record the timestamp only on acceptance so denied arrivals consume no quota. if len(window) < limit: window.append(current_time) decisions.append(1) else: decisions.append(0) return decisions✅ Submit now — all tests should pass.
Intuition & how it works
Picture a club bouncer who keeps a separate small notepad for each visitor (ip) listing the entry times of their permitted visits. Because visitors arrive in chronological order, the oldest entry on any notepad is always on the top line: when a visitor arrives at current_time, the bouncer crosses off every top line at or before current_time - time_window, counts how many active lines remain in this sliding window (a fixed-width time interval (current_time - time_window, current_time] that advances forward with current_time), and writes down current_time only if the count is strictly below limit. In code, each visitor's notepad is a deque (double-ended queue) — a queue structure that appends to the back and removes from the front in O(1) constant time without shifting remaining elements.
Why does the obvious approach fall short? Re-scanning all earlier requests from index 0 to i - 1 on every arrival takes O(n^2) comparisons, which reaches roughly 5 * 10^9 operations when n = 10^5 and times out. Storing per-IP timestamps in a plain Python list and calling list.pop(0) also slows down when limit is large because removing element 0 shifts every remaining element one slot left.
Here is how our per-IP deque handles Example 1 (limit = 2, time_window = 5):
Arrival cutoff = t - 5 IP's deque after popleft len < 2? Decision & updated deque
t=2, 172.16.0.5 -3 [] Yes 1 -> [2]
t=4, 172.16.0.5 -1 [2] Yes 1 -> [2, 4]
t=5, 172.16.0.9 0 [] (separate IP) Yes 1 -> [5]
t=6, 172.16.0.5 1 [2, 4] (2 > 1 stays) No 0 -> [2, 4] (6 not saved!)
t=7, 172.16.0.5 2 [4] (2 <= 2 popped) Yes 1 -> [4, 7]
t=8, 172.16.0.5 3 [4, 7] (4 > 3 stays) No 0 -> [4, 7]
Complexity
Let n be the number of requests and U (U <= n) be the number of distinct IP addresses.
- Time:
O(n)overall (O(1)amortized per request), treating hashing an IP string of length<= 45as constant time. AmortizedO(1)means that even though one request'swhileloop might pop several old timestamps at once, each request is appended to a deque at most once and popped at most once across the entire run, so totalappendandpopleftwork across allnrequests is at most2n. - Space:
O(min(n, U * limit))(at mostO(n)).accepted_by_ipstores at mostUdeques, each holding at mostlimitactive timestamps (and at mostntimestamps across all deques combined), plusnintegers for thedecisionsoutput list.
Edge cases
- Exact window boundary (
timestamps[j] == current_time - time_window): Excluded from(current_time - time_window, current_time]; using<=inwindow[0] <= cutoffdrops3whencurrent_time = 9, time_window = 6in Example 3. - Throttled requests do not extend the lockout: A throttled request at
t = 6is never pushed ontowindow, so172.16.0.5is permitted again att = 7in Example 1 oncet = 2expires. - Identical timestamps: Evaluated in index order; in Example 2 (
[12, 12, 12, 12]withlimit = 2), the first two requests append12and the next two seelen(window) == 2and get throttled ([1, 1, 0, 0]). time_window = 1:cutoff = current_time - 1, so every timestamp<= current_time - 1is evicted and only permitted requests at the exact samecurrent_timecount.- Negative
cutoff(current_time < time_window):current_time - time_windowis negative while all timestamps are>= 0, sowindow[0] <= cutoffis cleanlyFalsewith no special-casemax(0, ...)needed. - Unnormalized IP strings:
"10.0.0.1"and"10.0.0.01"are distinct dictionary keys, matching the exact-string rule.
Common mistakes
- Appending throttled requests to
window: If throttled requests are recorded, a noisy client that sends one request per second underlimit = 1, time_window = 6locks itself out forever instead of succeeding again after6time units. - Off-by-one boundary (
<instead of<=): Writingwindow[0] < current_time - time_windowtreats the window as closed[current_time - time_window, current_time]of widthtime_window + 1integers and wrongly throttles Example 3 att = 9andt = 15. - Using a single shared deque across all IPs: Forgets to partition by
ip, allowing traffic from one IP to block unrelated clients. - Calling
list.pop(0)instead ofdeque.popleft(): TurnsO(n)total time intoO(n * limit)when a single IP sustains heavy traffic under a largelimit(such astest_large_input_is_fastwithlimit = 1000).
Alternative approaches
- Append-only list with binary search: Store every permitted timestamp for an IP in a plain Python
list(which stays sorted) and use binary search (bisect.bisect_right(times, current_time - time_window), which repeatedly halves the sorted list inO(log n)steps) to find the first index strictly greater thancutoff. Thenlen(times) - idxgives the active count inO(log n)time per request without ever deleting elements, at the cost ofO(n)history retention instead ofO(limit)per IP.
Follow-up questions
- In a long-running service handling millions of ephemeral client IPs, how would you reclaim memory from idle entries? In our batch function, an IP that sends a burst and never returns leaves its deque sitting in
accepted_by_ipforever. In a production server, run a periodic background sweep (or maintain a time-ordered expiration queue of active IPs) that deletes anyipkey whose newest timestamp satisfieswindow[-1] <= now - time_window, because an empty deque behaves identically to an absent dictionary key. - When
limitis very large (for example, 100,000 requests per hour), how can you avoid storing every individual timestamp per IP? Exact sliding-window logs must remember individual timestamps, so reducing memory toO(1)per IP requires an approximation such as a sliding-window counter (storing just two integers — the previous fixed window's count and the current fixed window's count — and weighting the previous count by the overlap fraction) or a token bucket (storing[tokens, last_refill_time]to enforce an average rate plus a burst cap). Mention to the interviewer that both useO(1)space per IP at the trade-off of slightly different boundary decisions than the exact log rule. - How would you enforce this per-IP rate limit consistently across a fleet of stateless API gateway instances? Either route all traffic from a given client IP to the same rate-limiter shard using consistent hashing (mapping each key onto a hash ring so adding or removing a node moves only a small fraction of keys) to keep fast in-memory deques, or store each IP's timestamps in a shared Redis sorted set (
ZSET). With Redis, runZREMRANGEBYSCORE,ZCARD, and conditionalZADDinside a single Lua script so the check-and-record executes as one atomic operation (an indivisible step where two gateways cannot simultaneously readlimit - 1and both accept thelimit + 1-st request).
Follow-up questions
- In a long-running service handling millions of ephemeral client IPs, how would you reclaim memory from idle entries?
- When `limit` is very large (for example, 100,000 requests per hour), how can you avoid storing every individual timestamp per IP?
- How would you enforce this per-IP rate limit consistently across a fleet of stateless API gateway instances?
Similar questions
- Identify Recurring Charges in a Card Ledger
- Exit Discovery in a Locked Web Graph
- Adaptive-Timeout Web Graph Search with Deferred Retries
- Traveler Airport Lookup by Timestamp
- Versioned Recipe Catalog Service
- Progressive In-Memory Task Manager
More Ramp interview questions
- Resilient HTTP Graph Crawler with Retries and Cycle Detection Medium
- Exit Discovery in a Locked Web Graph Medium
- Adaptive-Timeout Web Graph Search with Deferred Retries Medium Pro
- Shortest Exit Route Through an Unreliable HTTP Maze Medium Pro
- Linear HTTP Endpoint Chain Traversal Medium Pro
- Rolling One-Minute Website Traffic Counter Hard Pro
- Traveler Airport Lookup Across Flight Schedules Medium Pro
- Stateful 3x3 Tic-Tac-Toe Rules Engine Medium Pro
- Versioned Recipe Catalog Service Medium Pro
- Deduplicate and Reconcile Person Records Hard Pro