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_secondsremain inside the active window. A prior record dated right att - window_seconds(aged by the fullwindow_secondsspan) 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:
- Client-IP policy (
ip_only_blocked): Reject the current record when at leastip_req_maxactive prior records share the same"request_ip". - Combined policy (
combined_blocked): Reject the current record when at leastip_req_maxactive prior records share the same"request_ip"or at leastip_host_req_maxactive prior records share both"request_ip"and"host". A single record breaching both thresholds at once incrementscombined_blockedby1, not2.
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^5logis ordered chronologically (timestamp[i] <= timestamp[i + 1]).- Every
"timestamp"is a valid ISO-8601 UTC string (with explicit offset such as+00:00or trailingZ, optionally with fractional seconds). 0 <= window_seconds <= 10^90 <= 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
Understand the rules and the window boundary
We receive a chronologically ordered list of gateway records
{"timestamp", "request_ip", "host"}, a lookback durationwindow_seconds, and two thresholds:ip_req_maxandip_host_req_max. Our job is to return[blocked_ip_only, blocked_combined]:- Client-IP policy (
blocked_ip_only): Count records that see at leastip_req_maxactive prior arrivals from the same IP. - Combined policy (
blocked_combined): Count records that trigger the Client-IP threshold or see at leastip_host_req_maxactive prior arrivals from the same IP to the same host. Breaching both limits on the same record still incrementsblocked_combinedby1.
Let's visualize the active lookback interval for an arrival at instant
nowwhenwindow_seconds > 0:Timeline: ... ----+----------------------------+----> time now - window now ( ] evicted (<= now - window) counted (> now - window, earlier in log)- Left boundary (
now - windowis excluded): An earlier entry stamped right atnow - windowhas aged out completely. Only prior entries strictly afternow - windowremain 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 atnowstays active and counts against the next record atnow. - 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_secondsseconds.
- Client-IP policy (
Why scanning backward every time is too slow
A brute-force loop stands at each index
iand walks backward across all earlier indices0 .. i - 1, tallying entries with matching keys andtime[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.Key idea: one sliding-window queue per key in a single pass
Two observations remove all redundant work:
- Timestamps never move backward. Because
logis ordered chronologically,cutoff = now - windowonly advances forward. Once an older timestamp satisfiestimestamp <= cutoff, it will also be<=every future cutoff — so we can discard it permanently! - 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 supportingO(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 - windowEvery record enters two deques once and leaves each deque at most once, keeping total work
O(n).- Timestamps never move backward. Because
Parse ISO-8601 timestamps accurately
Instead of comparing raw strings or truncating to whole seconds, we parse timestamps into
datetimeobjects:- Sub-second precision matters: an arrival at
08:00:00.500Zfollowed by one at08:01:00Zis59.5seconds apart, which is still inside a60-second window. Dropping fractional seconds would misread the gap as60seconds. - Replacing a trailing
"Z"with"+00:00"guaranteesdatetime.fromisoformatsucceeds across Python versions, and defaulting missing offsets totimezone.utclets 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- Sub-second precision matters: an arrival at
Evict expired timestamps and count active ones
Given one key's
historydeque andcutoff = now - window, we pop from the front whilehistory[0] <= cutoff. Because timestamps inside the deque are non-decreasing, stopping at the first timestamp strictly greater thancutoffmeans every remaining item inhistoryis active, solen(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)Combine both rules in a single pass
For each log entry, we execute four clear steps in order:
- Parse
now, computecutoff = now - window, and initialize empty deques foripand(ip, host)on first sight. - Call
count_active_requestson both deques to obtainip_countandpair_count. - Increment
blocked_ip_onlywhenip_count >= ip_req_max, and incrementblocked_combinedwhenip_count >= ip_req_max or pair_count >= ip_host_req_max(usingorensures a dual breach counts once). - Append
nowto 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]- Parse
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 from203.0.113.42(offsets in seconds from09:00:00, queues shown right after eviction and before appendingnow):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 = 20andnow = 62, both thresholds are breached at once, yetblocked_combinedrises by1each time. - Atnow = 60,cutoff = 15, sot = 15has aged by the full45seconds (15 <= 15) and is evicted, while the rejectedt = 20entry remains inby_ip_host[('203.0.113.42', 'cdn.shop.net')]and blocksnow = 60.Totals:
blocked_ip_only = 2(t = 20, 62) andblocked_combined = 4(t = 15, 20, 60, 62), returning[2, 4].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 thenrecords once, parsing each ISO-8601 timestamp (a standard text date-time format such as2025-06-10T08:00:00+00:00) inO(1)time since timestamp strings have bounded length, performingO(1)average-time dictionary lookups, and appending each timestamp to two deques. Although a singlewhileloop may pop several expired entries at once, each of thentimestamps enters a deque once and leaves it at most once, making eviction amortizedO(1)per record (meaning the average cost per record across the entire run is constant). - Space:
O(n)— In the worst case, allnrecords fall inside a singlewindow_secondsspan, soby_ipandby_ip_hosttogether storentimestamps each across at mostnkeys.
Edge cases
- Entry right at the boundary (
timestamp == now - window_seconds): Excluded becausehistory[0] <= cutoffuses<=, whereas an entrywindow_seconds - 0.001seconds old remains active. - Identical timestamps: Evaluated in list order; when
window_seconds > 0,now > now - window_seconds, so earlier entries atnowstay in the deque and count against subsequent entries atnow. - Sustained blocked bursts: Rejected entries still append
nowto both deques, so a noisy client firing every few seconds remains throttled continuously instead of slipping one call through everywindow_secondsseconds. - Breaching both thresholds simultaneously: Checked via
if exceeds_ip_limit or exceeds_pair_limit, incrementingblocked_combinedby1rather than2. - Zero limits (
ip_req_max == 0orip_host_req_max == 0): Becausecount >= 0always holds, every entry triggers a zero-threshold policy. - Zero window (
window_seconds == 0):cutoff == now, so every earlier entry satisfiestimestamp <= cutoffand is popped immediately, leavingcount == 0. - Sub-second timestamps and trailing
"Z": Preserved accurately bydatetimemicrosecond 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 fullwindow_secondsspan 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
nowbefore counting: Causes every arrival to count itself as an active prior entry, effectively lowering every threshold by1. - Incrementing
blocked_combinedseparately for each rule: Adding+1for the IP cap and another+1for the(IP, host)cap double-counts dual breaches. - Converting timestamps to floats (
datetime.timestamp()) or integer seconds: Float rounding can nudge microsecond boundaries acrosscutoff, and integer truncation discards.500Zfractional seconds.
Alternative approaches
- Bounding each deque's size at the threshold: To test
count >= limit(forlimit >= 1), we only need to check whether thelimit-th most recent timestamp is still> cutoff. Popping from the left wheneverlen(history) > limitcaps memory atO(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
headpointer whiletimes[head] <= cutoffalso runs inO(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_ipandby_ip_hostdeques, so the per-record logic works online directly. To keep memory bounded as millions of transient IPs appear and go idle, cap each deque atmax(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, insertnow" 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 inO(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 theexceeds_ip_limitandexceeds_pair_limitflags we already evaluate. That gives operators per-request diagnostics while still allowing both summary counts to be derived immediately.
Follow-up questions
- How would you adapt this algorithm for an unbounded live traffic stream rather than a finite batch list?
- How could you enforce these sliding-window thresholds consistently across a cluster of stateless gateway nodes?
- How would you extend the return value to report which specific rule rejected each individual entry?
Similar questions
- Top Five Client IPv4s Across Server Logs
- Defending an API with Layered Rate Limiting
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance