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

  1. 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.
  2. Per-IP active window: When deciding request i at time t = timestamps[i] from address ip = ip_addresses[i], count prior indices j < i that satisfy all of:
    • ip_addresses[j] == ip (compared as raw exact strings; distinct strings never share quota),
    • request j was permitted (1) — throttled (0) requests are discarded and never consume quota for later arrivals, and
    • timestamps[j] lies strictly above t - time_window, i.e., inside (t - time_window, t]. An arrival at exactly t - time_window has already expired.
  3. Decision: If that active count is strictly below limit, permit request i (1) and record t for ip; otherwise throttle request i (0) without recording t.

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, where n = len(timestamps) == len(ip_addresses)
  • 0 <= timestamps[i] <= 10^9, with timestamps[i] <= timestamps[i + 1] for all 0 <= i < n - 1
  • 1 <= limit <= 10^5
  • 1 <= time_window <= 10^9
  • Each ip_addresses[i] is a non-empty string of length 1 to 45.

Step-by-step walkthrough

  1. Understand the sliding-window rule

    We receive n requests in chronological order (timestamps[0] <= timestamps[1] <= ...), each paired with an ip string, and must return a list of 1 (permitted) or 0 (throttled) decisions of length n.

    When request i arrives at current_time = timestamps[i] from ip = ip_addresses[i], we count earlier requests j < i that satisfy all three conditions:

    1. Same IP address: ip_addresses[j] == ip (exact string match; different IPs are completely independent).
    2. Previously permitted: request j returned 1 (throttled requests are never stored and never count toward future limits).
    3. 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..9
    

    If fewer than limit earlier permitted requests from ip lie inside (current_time - time_window, current_time], we permit (1) and record current_time; otherwise we throttle (0) and record nothing.

  2. 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 index j < i and 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 decisions
    

    This reference logic is great for cross-checking tests, but across n = 10^5 requests it performs roughly n^2 / 2 = 5 * 10^9 checks — far too slow for a one-second limit.

  3. Key idea: one monotonic queue per IP

    Two observations eliminate the inner loop completely:

    1. Group by IP: Only requests from the same ip affect one another, so store a separate sequence of permitted timestamps per IP in a dictionary accepted_by_ip.
    2. The window only slides right: Because timestamps never decreases, cutoff = current_time - time_window never decreases either. Any permitted timestamp that falls at or before cutoff today will also be at or before cutoff for 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 a deque (a double-ended queue from collections that pops from the front in O(1) constant time, unlike list.pop(0) which shifts the entire list) lets us strip expired timestamps from the front and check len(window) < limit in O(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]
    
  4. Implement the per-request loop

    For each (current_time, ip) pair:

    1. Fetch (or create) window = accepted_by_ip[ip].
    2. Compute cutoff = current_time - time_window and pop from the front while window[0] <= cutoff.
    3. If len(window) < limit, append current_time to window and append 1 to decisions; otherwise append 0 without touching window.
    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
    
  5. 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]
    
  6. 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 <= 45 as constant time. Amortized O(1) means that even though one request's while loop 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 total append and popleft work across all n requests is at most 2n.
  • Space: O(min(n, U * limit)) (at most O(n)). accepted_by_ip stores at most U deques, each holding at most limit active timestamps (and at most n timestamps across all deques combined), plus n integers for the decisions output list.

Edge cases

  • Exact window boundary (timestamps[j] == current_time - time_window): Excluded from (current_time - time_window, current_time]; using <= in window[0] <= cutoff drops 3 when current_time = 9, time_window = 6 in Example 3.
  • Throttled requests do not extend the lockout: A throttled request at t = 6 is never pushed onto window, so 172.16.0.5 is permitted again at t = 7 in Example 1 once t = 2 expires.
  • Identical timestamps: Evaluated in index order; in Example 2 ([12, 12, 12, 12] with limit = 2), the first two requests append 12 and the next two see len(window) == 2 and get throttled ([1, 1, 0, 0]).
  • time_window = 1: cutoff = current_time - 1, so every timestamp <= current_time - 1 is evicted and only permitted requests at the exact same current_time count.
  • Negative cutoff (current_time < time_window): current_time - time_window is negative while all timestamps are >= 0, so window[0] <= cutoff is cleanly False with no special-case max(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 under limit = 1, time_window = 6 locks itself out forever instead of succeeding again after 6 time units.
  • Off-by-one boundary (< instead of <=): Writing window[0] < current_time - time_window treats the window as closed [current_time - time_window, current_time] of width time_window + 1 integers and wrongly throttles Example 3 at t = 9 and t = 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 of deque.popleft(): Turns O(n) total time into O(n * limit) when a single IP sustains heavy traffic under a large limit (such as test_large_input_is_fast with limit = 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 in O(log n) steps) to find the first index strictly greater than cutoff. Then len(times) - idx gives the active count in O(log n) time per request without ever deleting elements, at the cost of O(n) history retention instead of O(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_ip forever. In a production server, run a periodic background sweep (or maintain a time-ordered expiration queue of active IPs) that deletes any ip key whose newest timestamp satisfies window[-1] <= now - time_window, because an empty deque behaves identically to an absent dictionary key.
  • When limit is 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 to O(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 use O(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, run ZREMRANGEBYSCORE, ZCARD, and conditional ZADD inside a single Lua script so the check-and-record executes as one atomic operation (an indivisible step where two gateways cannot simultaneously read limit - 1 and both accept the limit + 1-st request).

Follow-up questions

Similar questions

More Ramp interview questions

All 42 Ramp questions →