Sliding-Window Traffic Throttle with Dual Limit Rules
Data Structure DesignAuto-graded · 14 test casesLast updated
Tests sliding-window counting over timestamped event logs using per-source and per-source-destination deque-based rate limiting.
Problem
You are building a traffic-analysis tool for a proxy server. The tool replays a request log and flags which requests would have been throttled under configurable rules.
Each entry in the log is a dictionary with three fields:
timestamp— an ISO-8601 UTC timestamp string (e.g."2024-01-01T00:00:05+00:00")request_ip— the client's IPv4 address as a stringhost— the destination hostname as a string
The log is sorted in ascending order by timestamp and fits entirely in memory.
Throttle window semantics
For a request arriving at time t, the relevant history is every earlier request whose timestamp falls in the open interval (t - T, t), where T is the window length in seconds.
- A request timestamped exactly
Tseconds before the current one is outside the window and does not count. - Requests with equal timestamps are evaluated in their original list order, so an earlier entry in the list counts as "already seen" when a later entry with the same timestamp is evaluated.
A throttled request still enters the history. Its timestamp is recorded and can cause future requests to be throttled.
Rule 1 — per-source limit
A request from IP address src is throttled when the number of previous requests (within the window) from that same IP is at least per_ip_limit:
count(requests from src in (t - T, t)) >= per_ip_limit
Your function must return the total number of requests throttled under this rule alone as the first element of its result.
Rule 2 — combined per-source and per-destination limit
A second rule adds a per-(source IP, host) ceiling. A request from IP src to host dst is also throttled when:
count(requests from src to dst in (t - T, t)) >= per_pair_limit
A request is throttled under the combined policy when either Rule 1 or Rule 2 (or both) fires. A request that triggers both rules is still counted once.
Your function must return the total number of requests throttled under the combined policy as the second element of its result.
What to return
Return a list of exactly two integers: [rule1_throttled, combined_throttled].
Constraints
1 <= len(log) <= 10^51 <= T <= 10^6(seconds)1 <= per_ip_limit <= 10^41 <= per_pair_limit <= 10^4- Timestamps are valid ISO-8601 strings with explicit UTC offsets or a trailing
Z. - The log is sorted in non-decreasing order by timestamp; equal timestamps are possible.
- Both rules use the same window length
T. - The function must handle an empty log and return
[0, 0].
Examples
Example 1
Input: count_blocked_requests([{'timestamp': '2024-01-01T00:00:00+00:00', 'request_ip': '127.0.0.1', 'host': 'example1.com'}, {'timestamp': '2024-01-01T00:00:01+00:00', 'request_ip': '127.0.0.1', 'host': 'example2.com'}, {'timestamp': '2024-01-01T00:01:02+00:00', 'request_ip': '127.0.0.1', 'host': 'example1.com'}, {'timestamp': '2024-01-01T00:01:03+00:00', 'request_ip': '127.0.0.1', 'host': 'example2.com'}, {'timestamp': '2024-01-01T00:01:04+00:00', 'request_ip': '127.0.0.1', 'host': 'example1.com'}, {'timestamp': '2024-01-01T00:02:04+00:00', 'request_ip': '127.0.0.1', 'host': 'example1.com'}], 60, 1, 100)
Output: [3, 3]
Example 2
Input: count_blocked_requests([{'timestamp': '2024-01-01T00:00:00+00:00', 'request_ip': '127.0.0.1', 'host': 'example1.com'}, {'timestamp': '2024-01-01T00:00:01+00:00', 'request_ip': '127.0.0.1', 'host': 'example2.com'}, {'timestamp': '2024-01-01T00:00:10+00:00', 'request_ip': '127.0.0.1', 'host': 'example1.com'}, {'timestamp': '2024-01-01T00:00:11+00:00', 'request_ip': '127.0.0.1', 'host': 'example3.com'}, {'timestamp': '2024-01-01T00:01:04+00:00', 'request_ip': '127.0.0.1', 'host': 'example3.com'}, {'timestamp': '2024-01-01T00:01:11+00:00', 'request_ip': '127.0.0.1', 'host': 'example1.com'}], 60, 3, 1)
Output: [1, 3]
Hints
Hint 1
For each arriving request you need to know how many earlier requests from the same source (or source+destination) fall inside the open interval (t − T, t). A deque per key lets you evict expired entries from the front in O(1) amortized time — what comparison determines whether a timestamp has fallen out of the window?
Hint 2
Evict before you check the deque length, then append the current timestamp unconditionally afterward. Appending regardless of whether the request was throttled is critical — skipping it for blocked requests is the most common bug and will produce wrong counts.
Hint 3
Both answers can be produced in a single pass over the log. Rule 1 is a strict subset of the combined decision, so you never need to re-process any entry. For the combined count, use a logical OR of the two individual limit checks and increment a single counter — that way a request violating both rules is counted exactly once.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a sliding-window counting problem where each request needs two questions answered: how many prior requests from the same source IP, and how many from the same (source IP, host) pair, land inside the open interval (t − T, t)?
The efficient structure for this is a deque of timestamps per key. Because the log is sorted, timestamps in any deque are also sorted, so expired entries are always at the front and can be removed with popleft in O(1).
Algorithm (single pass)
For each request at time t:
- Compute
cutoff = t − T. - Pop from the front of the IP deque and the pair deque while the front entry is
<= cutoff. The<=comparison is what enforces the open-interval boundary: a timestamp exactlyTseconds old is outside the window. - The remaining lengths are exactly the counts of in-window prior requests. Compare against the two limits.
- Append
tto both deques regardless of whether the request was throttled. Skipping this step for throttled requests is the most common bug — it turns the counter into an "allowed requests only" tracker and produces wrong results.
Both answers are computed in the same pass. Rule 1 is a strict subset of the combined decision, so there is no need to iterate twice.
Why it is correct
After eviction, every timestamp s remaining in a deque satisfies s > t − T (not evicted) and s < t (was appended by an earlier processed request, and since the log is sorted, earlier requests have timestamps <= t; equal-timestamp requests that appear earlier in the list are already in the deque when the current entry is evaluated). That is precisely the set of requests in (t − T, t).
The or in the combined check guarantees a request that violates both rules increments combined_blocked exactly once.
Trace of sample 1 (T = 60, per_ip_limit = 1, per_pair_limit = 100)
| # | Time (s) | Cutoff | IP deque before check | IP throttled? | Combined? |
|---|---|---|---|---|---|
| 1 | 0 | -60 | [] → len 0 | no | no |
| 2 | 1 | -59 | [0] → len 1 | yes | yes |
| 3 | 62 | 2 | evicts 0,1 → [] | no | no |
| 4 | 63 | 3 | [62] → len 1 | yes | yes |
| 5 | 64 | 4 | [62,63] → len 2 | yes | yes |
| 6 | 124 | 64 | evicts 62,63,64 → [] | no | no |
Rule 1 total: 3. Combined total: 3. Request 6 demonstrates the exclusive boundary: the entry at second 64 is exactly 60 seconds old, so 64 <= 64 is true and it is evicted.
Complexity
- Time: O(n) amortized. Each entry is appended once to its IP deque and once to its pair deque. Each entry is popped at most once. Dictionary lookups are O(1) average. The nested
whileloops do not make this O(n²) — total pops across the entire run are bounded by total pushes, which is O(n). - Space: O(n) worst case. Deques across all keys hold at most n timestamps in total for each map. In practice, memory is bounded by the number of distinct IPs and pairs whose timestamps still fall within the current window.
Edge cases
- Empty log — the loop body never executes;
[0, 0]is returned. - Exact boundary —
<=in the eviction condition handles this precisely. - Throttled bursts extending the block — because throttled requests are appended, a run of blocked entries from the same IP keeps the deque full and blocks the next request too.
- Trailing
Zin timestamps — normalized to+00:00before parsing to support Python versions before 3.11.
from collections import deque
from datetime import datetime, timedelta
from typing import Dict, List
def count_blocked_requests(
log: List[Dict[str, str]],
window_seconds: int,
per_ip_limit: int,
per_pair_limit: int,
) -> List[int]:
ip_history = {} # ip -> deque of datetime timestamps within the window
pair_history = {} # (ip, host) -> deque of datetime timestamps within the window
rule1_blocked = 0
combined_blocked = 0
window = timedelta(seconds=window_seconds)
for row in log:
ts_text = row["timestamp"]
# datetime.fromisoformat before Python 3.11 cannot handle a trailing 'Z'
ts = datetime.fromisoformat(
ts_text[:-1] + "+00:00" if ts_text.endswith("Z") else ts_text
)
ip = row["request_ip"]
host = row["host"]
ip_queue = ip_history.setdefault(ip, deque())
pair_queue = pair_history.setdefault((ip, host), deque())
# The window is the open interval (t - T, t).
# Any timestamp <= t - T is outside the window and must be evicted.
cutoff = ts - window
while ip_queue and ip_queue[0] <= cutoff:
ip_queue.popleft()
while pair_queue and pair_queue[0] <= cutoff:
pair_queue.popleft()
# Check both throttle conditions against the now-current deque lengths.
ip_throttled = len(ip_queue) >= per_ip_limit
pair_throttled = len(pair_queue) >= per_pair_limit
if ip_throttled:
rule1_blocked += 1
if ip_throttled or pair_throttled: # OR: violating both still counts once
combined_blocked += 1
# Throttled requests count toward future limits — append unconditionally.
ip_queue.append(ts)
pair_queue.append(ts)
return [rule1_blocked, combined_blocked]