Counting Throttled Requests in Sliding Windows

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

An edge gateway records incoming HTTP traffic as a chronological list of dictionaries log. Every record contains three string fields:

  • "timestamp": an ISO-8601 UTC timestamp string (for example, "2025-06-10T08:00:00+00:00" or "2025-06-10T08:00:00.500Z").
  • "request_ip": the caller's IP address string.
  • "host": the destination domain name string.

Records in log are already ordered in non-decreasing timestamp order. When multiple records carry the exact same timestamp, evaluate them one by one in their given list position.

To evaluate an incoming record at instant t against a lookback duration of window_seconds seconds:

  • Only previously processed records whose timestamp is strictly greater than t - window_seconds remain inside the active window. A prior record dated right at t - window_seconds (aged by the full window_seconds span) is outside the window and does not count.
  • Every processed record — regardless of whether it was permitted or rejected — is retained in the traffic history and counts toward subsequent records whose windows include t.

Implement count_blocked_requests(log, window_seconds, ip_req_max, ip_host_req_max) -> List[int] to return a two-integer list [ip_only_blocked, combined_blocked] comparing two independent throttling policies over log:

  1. Client-IP policy (ip_only_blocked): Reject the current record when at least ip_req_max active prior records share the same "request_ip".
  2. Combined policy (combined_blocked): Reject the current record when at least ip_req_max active prior records share the same "request_ip" or at least ip_host_req_max active prior records share both "request_ip" and "host". A single record breaching both thresholds at once increments combined_blocked by 1, not 2.

Examples

Example 1

Input:
  log = [
    {"timestamp": "2025-06-10T08:00:00+00:00", "request_ip": "198.51.100.7", "host": "api.payments.io"},
    {"timestamp": "2025-06-10T08:00:12+00:00", "request_ip": "198.51.100.7", "host": "auth.payments.io"},
    {"timestamp": "2025-06-10T08:00:25+00:00", "request_ip": "198.51.100.7", "host": "api.payments.io"},
    {"timestamp": "2025-06-10T08:00:30+00:00", "request_ip": "198.51.100.7", "host": "auth.payments.io"},
    {"timestamp": "2025-06-10T08:00:35+00:00", "request_ip": "198.51.100.8", "host": "api.payments.io"},
    {"timestamp": "2025-06-10T08:00:56+00:00", "request_ip": "198.51.100.7", "host": "api.payments.io"},
  ]
  window_seconds = 30, ip_req_max = 2, ip_host_req_max = 5

Output: [2, 2]

Walk-through (offsets in seconds from 08:00:00): - At 0s and 12s, "198.51.100.7" has 0 and 1 active prior calls (< 2), so both pass. - At 25s, "198.51.100.7" already has 2 calls after -5s (0s and 12s), hitting ip_req_max = 2 -> rejected under both policies, yet 25s is still recorded. - At 30s, the cutoff is 0s, so the 0s call ages out (0 <= 0), leaving 12s and the rejected 25s call (2 >= 2) -> rejected under both policies. - At 35s, "198.51.100.8" has an empty history -> permitted. - At 56s, the cutoff is 26s, so 12s and 25s age out, leaving only 30s (1 < 2) -> permitted.

Example 2

Input:
  log = [
    {"timestamp": "2025-06-10T09:00:00+00:00", "request_ip": "203.0.113.42", "host": "cdn.shop.net"},
    {"timestamp": "2025-06-10T09:00:08+00:00", "request_ip": "203.0.113.42", "host": "cart.shop.net"},
    {"timestamp": "2025-06-10T09:00:15+00:00", "request_ip": "203.0.113.42", "host": "cdn.shop.net"},
    {"timestamp": "2025-06-10T09:00:20+00:00", "request_ip": "203.0.113.42", "host": "cdn.shop.net"},
    {"timestamp": "2025-06-10T09:00:55+00:00", "request_ip": "203.0.113.42", "host": "search.shop.net"},
    {"timestamp": "2025-06-10T09:01:00+00:00", "request_ip": "203.0.113.42", "host": "cdn.shop.net"},
    {"timestamp": "2025-06-10T09:01:02+00:00", "request_ip": "203.0.113.42", "host": "search.shop.net"},
  ]
  window_seconds = 45, ip_req_max = 3, ip_host_req_max = 1

Output: [2, 4]

Walk-through (offsets from 09:00:00, all from "203.0.113.42"): - 0s (cdn) and 8s (cart) pass under both policies. - 15s (cdn) has 2 < 3 prior IP calls (passes Policy 1) but 1 >= 1 prior (ip, cdn) call at 0s (rejected under Policy 2). - 20s (cdn) has 3 >= 3 prior IP calls (0s, 8s, 15s) and 2 >= 1 prior (ip, cdn) calls -> rejected under Policy 1 and counted once under Policy 2. - 55s (search) has cutoff 10s; 0s and 8s expire, leaving 15s and 20s (2 < 3 IP calls, 0 search calls) -> passes both. - 60s (cdn) has cutoff 15s; 15s expires (15 <= 15), leaving 20s and 55s (2 < 3 IP calls -> passes Policy 1), while 20s keeps (ip, cdn) at 1 >= 1 (rejected under Policy 2). - 62s (search) has cutoff 17s; active IP calls 20s, 55s, 60s reach 3 >= 3 and (ip, search) has 55s (1 >= 1) -> rejected under both policies (counted once in Policy 2).

Constraints

  • 0 <= len(log) <= 10^5
  • log is ordered chronologically (timestamp[i] <= timestamp[i + 1]).
  • Every "timestamp" is a valid ISO-8601 UTC string (with explicit offset such as +00:00 or trailing Z, optionally with fractional seconds).
  • 0 <= window_seconds <= 10^9
  • 0 <= ip_req_max, ip_host_req_max <= 10^5
  • Your solution should run in O(len(log)) time so large in-memory logs finish quickly.

Step-by-step walkthrough

  1. Understand the rules and the window boundary

    We receive a chronologically ordered list of gateway records {"timestamp", "request_ip", "host"}, a lookback duration window_seconds, and two thresholds: ip_req_max and ip_host_req_max. Our job is to return [blocked_ip_only, blocked_combined]:

    1. Client-IP policy (blocked_ip_only): Count records that see at least ip_req_max active prior arrivals from the same IP.
    2. Combined policy (blocked_combined): Count records that trigger the Client-IP threshold or see at least ip_host_req_max active prior arrivals from the same IP to the same host. Breaching both limits on the same record still increments blocked_combined by 1.

    Let's visualize the active lookback interval for an arrival at instant now when window_seconds > 0:

    Timeline:   ... ----+----------------------------+----> time
                  now - window                      now
                       ( ]
      evicted (<= now - window)   counted (> now - window, earlier in log)
    
    • Left boundary (now - window is excluded): An earlier entry stamped right at now - window has aged out completely. Only prior entries strictly after now - window remain active.
    • Equal-timestamp ties: Records stamped at the exact same instant are handled one by one in list order. When window_seconds > 0, now > now - window, so an earlier record at now stays active and counts against the next record at now.
    • Rejected arrivals stay in history: Even when an incoming call is throttled, its timestamp is still recorded and counts toward subsequent arrivals within the next window_seconds seconds.
  2. Why scanning backward every time is too slow

    A brute-force loop stands at each index i and walks backward across all earlier indices 0 .. i - 1, tallying entries with matching keys and time[j] > time[i] - window:

    Entry i=0: scan 0 earlier entries
    Entry i=1: scan 1 earlier entry
    ...
    Entry i=99,999: scan 99,999 earlier entries  --> ~5,000,000,000 checks total!
    

    That nested loop runs in O(n^2) time, repeatedly inspecting ancient timestamps that expired long ago.

  3. Key idea: one sliding-window queue per key in a single pass

    Two observations remove all redundant work:

    1. Timestamps never move backward. Because log is ordered chronologically, cutoff = now - window only advances forward. Once an older timestamp satisfies timestamp <= cutoff, it will also be <= every future cutoff — so we can discard it permanently!
    2. History never depends on allow/reject outcomes. Every arrival — permitted or rejected — enters the history. Because both policies observe the exact same per-IP timeline, we can compute [blocked_ip_only, blocked_combined] together in one pass.

    For each IP (and each (IP, host) pair), we maintain a deque (collections.deque, a double-ended queue supporting O(1) front removals and back appends) holding only the timestamps still inside the active lookback span:

    Front (oldest)                               Back (newest)
       [ 09:00:00,  09:00:08,  09:00:15 ]   <-- append(now)
         ^
         popleft() while front <= now - window
    

    Every record enters two deques once and leaves each deque at most once, keeping total work O(n).

  4. Parse ISO-8601 timestamps accurately

    Instead of comparing raw strings or truncating to whole seconds, we parse timestamps into datetime objects:

    • Sub-second precision matters: an arrival at 08:00:00.500Z followed by one at 08:01:00Z is 59.5 seconds apart, which is still inside a 60-second window. Dropping fractional seconds would misread the gap as 60 seconds.
    • Replacing a trailing "Z" with "+00:00" guarantees datetime.fromisoformat succeeds across Python versions, and defaulting missing offsets to timezone.utc lets any two parsed moments be subtracted cleanly.
    def parse_time(timestamp_text: str) -> datetime:
        """Parse an ISO-8601 timestamp string into a timezone-aware UTC datetime."""
        # Replace a trailing 'Z' (UTC shorthand) with '+00:00' so fromisoformat always succeeds.
        normalized = timestamp_text
        if normalized.endswith(("Z", "z")):
            normalized = normalized[:-1] + "+00:00"
        moment = datetime.fromisoformat(normalized)
        # If no UTC offset was provided, treat the timestamp as UTC so all moments can be compared.
        if moment.tzinfo is None:
            moment = moment.replace(tzinfo=timezone.utc)
        return moment
    
  5. Evict expired timestamps and count active ones

    Given one key's history deque and cutoff = now - window, we pop from the front while history[0] <= cutoff. Because timestamps inside the deque are non-decreasing, stopping at the first timestamp strictly greater than cutoff means every remaining item in history is active, so len(history) is the exact active count.

    def count_active_requests(history: deque, cutoff: datetime) -> int:
        """Evict timestamps at or before cutoff, then return how many active timestamps remain."""
        # Use '<=' because an entry dated right at the boundary (now - window) has aged out
        # of the lookback span and does not count toward the current arrival.
        while history and history[0] <= cutoff:
            history.popleft()
        return len(history)
    
  6. Combine both rules in a single pass

    For each log entry, we execute four clear steps in order:

    1. Parse now, compute cutoff = now - window, and initialize empty deques for ip and (ip, host) on first sight.
    2. Call count_active_requests on both deques to obtain ip_count and pair_count.
    3. Increment blocked_ip_only when ip_count >= ip_req_max, and increment blocked_combined when ip_count >= ip_req_max or pair_count >= ip_host_req_max (using or ensures a dual breach counts once).
    4. Append now to both deques after counting (so an entry never counts against itself) and unconditionally (so rejected arrivals still affect future windows).
    def count_blocked_requests(log: List[Dict[str, str]], window_seconds: int, ip_req_max: int, ip_host_req_max: int) -> List[int]:
        window = timedelta(seconds=window_seconds)
        # by_ip: maps ip_str -> deque([datetime, ...]) of timestamps still inside the window
        by_ip: Dict[str, deque] = {}
        # by_ip_host: maps (ip_str, host_str) -> deque([datetime, ...]) of timestamps in the window
        by_ip_host: Dict[Tuple[str, str], deque] = {}
    
        blocked_ip_only = 0
        blocked_combined = 0
    
        for entry in log:
            # Phase 1: Parse the request's instant and identify its IP and (IP, host) keys.
            now = parse_time(entry["timestamp"])
            cutoff = now - window
            ip = entry["request_ip"]
            ip_host_pair = (ip, entry["host"])
    
            if ip not in by_ip:
                by_ip[ip] = deque()
            if ip_host_pair not in by_ip_host:
                by_ip_host[ip_host_pair] = deque()
    
            # Phase 2: Evict expired timestamps and count earlier requests after (now - T).
            ip_count = count_active_requests(by_ip[ip], cutoff)
            pair_count = count_active_requests(by_ip_host[ip_host_pair], cutoff)
    
            # Phase 3: Check rate-limit thresholds; a dual violation in Part 2 still counts once.
            exceeds_ip_limit = ip_count >= ip_req_max
            exceeds_pair_limit = pair_count >= ip_host_req_max
            if exceeds_ip_limit:
                blocked_ip_only += 1
            if exceeds_ip_limit or exceeds_pair_limit:
                blocked_combined += 1
    
            # Phase 4: Record this request AFTER counting so it never counts against itself,
            # and record it even when blocked because blocked requests still affect future windows.
            by_ip[ip].append(now)
            by_ip_host[ip_host_pair].append(now)
    
        return [blocked_ip_only, blocked_combined]
    
  7. Trace Example 2 step by step

    Let's walk through Example 2 with window_seconds = 45, ip_req_max = 3, ip_host_req_max = 1, where all 7 records come from 203.0.113.42 (offsets in seconds from 09:00:00, queues shown right after eviction and before appending now):

    now  cutoff  host    by_ip after evict   ip_cnt  pair queue  pair_cnt  decision
    ---  ------  ------  ------------------  ------  ----------  --------  ------------------------------
      0     -45  cdn     []                       0  []                 0  Policy 1: ok,    Policy 2: ok
      8     -37  cart    [0]                      1  []                 0  Policy 1: ok,    Policy 2: ok
     15     -30  cdn     [0, 8]                   2  [0]                1  Policy 1: ok,    Policy 2: BLOCK (pair)
     20     -25  cdn     [0, 8, 15]               3  [0, 15]            2  Policy 1: BLOCK, Policy 2: BLOCK (both)
     55      10  search  [15, 20] (0,8 out)       2  []                 0  Policy 1: ok,    Policy 2: ok
     60      15  cdn     [20, 55] (15 out!)       2  [20] (0,15 out)    1  Policy 1: ok,    Policy 2: BLOCK (pair)
     62      17  search  [20, 55, 60]             3  [55]               1  Policy 1: BLOCK, Policy 2: BLOCK (both)
    

    Notice three crucial details in this trace: - At now = 20 and now = 62, both thresholds are breached at once, yet blocked_combined rises by 1 each time. - At now = 60, cutoff = 15, so t = 15 has aged by the full 45 seconds (15 <= 15) and is evicted, while the rejected t = 20 entry remains in by_ip_host[('203.0.113.42', 'cdn.shop.net')] and blocks now = 60.

    Totals: blocked_ip_only = 2 (t = 20, 62) and blocked_combined = 4 (t = 15, 20, 60, 62), returning [2, 4].

  8. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    from collections import deque
    from datetime import datetime, timedelta, timezone
    
    
    def parse_time(timestamp_text: str) -> datetime:
        """Parse an ISO-8601 timestamp string into a timezone-aware UTC datetime."""
        # Replace a trailing 'Z' (UTC shorthand) with '+00:00' so fromisoformat always succeeds.
        normalized = timestamp_text
        if normalized.endswith(("Z", "z")):
            normalized = normalized[:-1] + "+00:00"
        moment = datetime.fromisoformat(normalized)
        # If no UTC offset was provided, treat the timestamp as UTC so all moments can be compared.
        if moment.tzinfo is None:
            moment = moment.replace(tzinfo=timezone.utc)
        return moment
    
    
    def count_active_requests(history: deque, cutoff: datetime) -> int:
        """Evict timestamps at or before cutoff, then return how many active timestamps remain."""
        # Use '<=' because an entry dated right at the boundary (now - window) has aged out
        # of the lookback span and does not count toward the current arrival.
        while history and history[0] <= cutoff:
            history.popleft()
        return len(history)
    
    
    def count_blocked_requests(log: List[Dict[str, str]], window_seconds: int, ip_req_max: int, ip_host_req_max: int) -> List[int]:
        window = timedelta(seconds=window_seconds)
        # by_ip: maps ip_str -> deque([datetime, ...]) of timestamps still inside the window
        by_ip: Dict[str, deque] = {}
        # by_ip_host: maps (ip_str, host_str) -> deque([datetime, ...]) of timestamps in the window
        by_ip_host: Dict[Tuple[str, str], deque] = {}
    
        blocked_ip_only = 0
        blocked_combined = 0
    
        for entry in log:
            # Phase 1: Parse the request's instant and identify its IP and (IP, host) keys.
            now = parse_time(entry["timestamp"])
            cutoff = now - window
            ip = entry["request_ip"]
            ip_host_pair = (ip, entry["host"])
    
            if ip not in by_ip:
                by_ip[ip] = deque()
            if ip_host_pair not in by_ip_host:
                by_ip_host[ip_host_pair] = deque()
    
            # Phase 2: Evict expired timestamps and count earlier requests after (now - T).
            ip_count = count_active_requests(by_ip[ip], cutoff)
            pair_count = count_active_requests(by_ip_host[ip_host_pair], cutoff)
    
            # Phase 3: Check rate-limit thresholds; a dual violation in Part 2 still counts once.
            exceeds_ip_limit = ip_count >= ip_req_max
            exceeds_pair_limit = pair_count >= ip_host_req_max
            if exceeds_ip_limit:
                blocked_ip_only += 1
            if exceeds_ip_limit or exceeds_pair_limit:
                blocked_combined += 1
    
            # Phase 4: Record this request AFTER counting so it never counts against itself,
            # and record it even when blocked because blocked requests still affect future windows.
            by_ip[ip].append(now)
            by_ip_host[ip_host_pair].append(now)
    
        return [blocked_ip_only, blocked_combined]
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine a security desk keeping a chronological sign-in ledger for each caller over a sliding window (a moving time span covering only the most recent window_seconds seconds up to the current arrival). Because records arrive in timestamp order, the oldest entries always sit at the top of each ledger and the newest ones sit at the bottom. Whenever a call arrives at now, the guard crosses off entries from the top that occurred at or before now - window_seconds, counts how many lines remain, checks the thresholds, and writes now at the bottom — even when the caller was turned away! In Python, each ledger is a deque (a double-ended queue that removes from the front and appends to the back in O(1) constant time).

Why does a naive loop fall short? Scanning backward to index 0 on every arrival re-checks expired timestamps again and again, turning a 100,000-entry log into roughly 5 billion comparisons (O(n^2) time). Running two separate passes where Policy 1 strips out rejected calls before Policy 2 runs would also produce wrong counts, because rejected arrivals still stay in the sliding history and count toward later arrivals.

Let's trace 4 arrivals from 198.51.100.7 with window_seconds = 30, ip_req_max = 2, and ip_host_req_max = 1 (offsets in seconds):

1. t=0  (api):  cutoff=-30 | ip deque []      (0 < 2), (ip,api)  []  (0 < 1) -> OK;             append 0
2. t=12 (api):  cutoff=-18 | ip deque [0]     (1 < 2), (ip,api)  [0] (1 >= 1)-> Policy 2 BLOCK; append 12
3. t=25 (auth): cutoff=-5  | ip deque [0, 12] (2 >= 2),(ip,auth) []  (0 < 1) -> Both BLOCK;     append 25
4. t=42 (api):  cutoff=12  | pop 0 & 12 (<=12)-> ip deque [25] (1 < 2), (ip,api) [] (0 < 1) -> OK

Notice how t = 12 was rejected in step 2 yet still pushed the IP count to 2 at t = 25, and at t = 42 both t = 0 and t = 12 (12 <= 42 - 30) popped off the front permanently, yielding [1, 2].

Complexity

Let n be the number of records in log.

  • Time: O(n) — We iterate through the n records once, parsing each ISO-8601 timestamp (a standard text date-time format such as 2025-06-10T08:00:00+00:00) in O(1) time since timestamp strings have bounded length, performing O(1) average-time dictionary lookups, and appending each timestamp to two deques. Although a single while loop may pop several expired entries at once, each of the n timestamps enters a deque once and leaves it at most once, making eviction amortized O(1) per record (meaning the average cost per record across the entire run is constant).
  • Space: O(n) — In the worst case, all n records fall inside a single window_seconds span, so by_ip and by_ip_host together store n timestamps each across at most n keys.

Edge cases

  • Entry right at the boundary (timestamp == now - window_seconds): Excluded because history[0] <= cutoff uses <=, whereas an entry window_seconds - 0.001 seconds old remains active.
  • Identical timestamps: Evaluated in list order; when window_seconds > 0, now > now - window_seconds, so earlier entries at now stay in the deque and count against subsequent entries at now.
  • Sustained blocked bursts: Rejected entries still append now to both deques, so a noisy client firing every few seconds remains throttled continuously instead of slipping one call through every window_seconds seconds.
  • Breaching both thresholds simultaneously: Checked via if exceeds_ip_limit or exceeds_pair_limit, incrementing blocked_combined by 1 rather than 2.
  • Zero limits (ip_req_max == 0 or ip_host_req_max == 0): Because count >= 0 always holds, every entry triggers a zero-threshold policy.
  • Zero window (window_seconds == 0): cutoff == now, so every earlier entry satisfies timestamp <= cutoff and is popped immediately, leaving count == 0.
  • Sub-second timestamps and trailing "Z": Preserved accurately by datetime microsecond arithmetic without rounding to whole seconds.
  • Empty log ([]): Loop skips cleanly and returns [0, 0].

Common mistakes

  • Evicting with < instead of <= (history[0] < now - window): Leaves an entry aged by the full window_seconds span inside the active deque, over-counting boundary arrivals.
  • Recording only permitted calls: Skipping append(now) when a call is rejected lets noisy clients succeed again as soon as their earlier permitted calls expire.
  • Appending now before counting: Causes every arrival to count itself as an active prior entry, effectively lowering every threshold by 1.
  • Incrementing blocked_combined separately for each rule: Adding +1 for the IP cap and another +1 for the (IP, host) cap double-counts dual breaches.
  • Converting timestamps to floats (datetime.timestamp()) or integer seconds: Float rounding can nudge microsecond boundaries across cutoff, and integer truncation discards .500Z fractional seconds.

Alternative approaches

  • Bounding each deque's size at the threshold: To test count >= limit (for limit >= 1), we only need to check whether the limit-th most recent timestamp is still > cutoff. Popping from the left whenever len(history) > limit caps memory at O(unique_keys * limit) without changing any allow/reject outcome.
  • Per-key list with an advancing head index: Storing a plain list per key and advancing an integer head pointer while times[head] <= cutoff also runs in O(n) time, though expired timestamps stay allocated in the list.

Follow-up questions

  • How would you adapt this algorithm for an unbounded live traffic stream rather than a finite batch list? Each incoming event already depends only on the active by_ip and by_ip_host deques, so the per-record logic works online directly. To keep memory bounded as millions of transient IPs appear and go idle, cap each deque at max(limit, 1) entries and periodically sweep out dictionary keys whose newest timestamp is <= now - window. If distributed collectors deliver events slightly out of timestamp order, hold arrivals in a brief min-heap buffer and evaluate them once a watermark (a trailing timestamp cutoff behind which late stragglers are no longer expected) moves past them.
  • How could you enforce these sliding-window thresholds consistently across a cluster of stateless gateway nodes? Either route requests via consistent hashing (a hashing scheme that maps each client IP to one designated rate-limiter instance with minimal remapping when nodes scale) so in-memory deques stay local, or maintain per-key sorted sets in Redis and run "evict <= cutoff, count, insert now" inside a single atomic Lua script so concurrent gateways never race. When storing individual timestamps per caller becomes too memory-heavy at massive scale, production gateways often approximate sliding windows using a token bucket (a compact counter of available permits that refills smoothly over time in O(1) space per key).
  • How would you extend the return value to report which specific rule rejected each individual entry? Instead of maintaining only two aggregate counters, append a per-record tag such as "allowed", "ip", "ip_host", or "both" computed directly from the exceeds_ip_limit and exceeds_pair_limit flags we already evaluate. That gives operators per-request diagnostics while still allowing both summary counts to be derived immediately.

Follow-up questions

Similar questions

More Render interview questions

All 3 Render questions →