Rolling-Window Error Alerting by Endpoint Prefix
Easy · Software Engineering Fundamentals · Software Engineer · Technical Screen
Problem Statement
Build an error-rate alerting monitor that groups incoming HTTP failures by endpoint prefix and evaluates whether recent failures exceed an alert limit inside a rolling 10-minute (600-second) lookback window.
Given a scheme-free URL string such as "shop.net/v2/checkout/pay", its prefix consists of the host followed by up to its first two path segments separated by "/" (that is, everything before the third "/", or the entire string if fewer than three slashes are present — yielding "shop.net/v2/checkout").
Implement an AlertMonitor class together with the driver function alert_monitor(operations: List[str], arguments: List[List]) -> List[Optional[bool]] that executes a chronological batch of operations on one AlertMonitor instance:
"record_error"with[timestamp, url]: logs one failure at Unix secondtimestampunderurl's normalized two-segment prefix, and appendsNoneto the returned list."should_alert"with[timestamp, prefix, threshold]: counts how many failures recorded for the exactprefixfall within the inclusive interval[timestamp - 600, timestamp], appendingTruewhen that count is strictly greater thanthresholdandFalseotherwise.
Multiple failures may arrive at the identical timestamp (each counts individually), and queries may occur arbitrarily long after earlier failures have aged out of the 600-second window.
Examples
Example 1
Input:
operations = ["record_error", "record_error", "record_error", "should_alert", "should_alert"]
arguments = [
[200, "shop.net/v2/checkout/pay"],
[350, "shop.net/v2/checkout/refund"],
[410, "shop.net/v2/catalog/view"],
[500, "shop.net/v2/checkout", 1],
[500, "shop.net/v2/checkout", 2]
]
Output: [None, None, None, True, False]
Explanation: The first two failures map to "shop.net/v2/checkout" (at t = 200 and t = 350), while the third maps to "shop.net/v2/catalog". At t = 500, the inclusive window [-100, 500] contains 2 failures for "shop.net/v2/checkout": 2 > 1 returns True, whereas 2 > 2 is false because the comparison is strict.
Example 2
Input:
operations = ["record_error", "record_error", "should_alert", "should_alert"]
arguments = [
[100, "auth.dev/oauth/token/refresh"],
[450, "auth.dev/oauth/token/revoke"],
[700, "auth.dev/oauth/token", 1],
[701, "auth.dev/oauth/token", 1]
]
Output: [None, None, True, False]
Explanation: Both failures normalize to "auth.dev/oauth/token". At t = 700, the window [100, 700] includes both 100 and 450 (2 > 1 -> True). One second later at t = 701, the window [101, 701] excludes 100, leaving 1 active failure (1 > 1 -> False).
Constraints
0 <= len(operations) == len(arguments) <= 10^5- Every
timestampis a positive integer (1 <= timestamp <= 10^9), and calls arrive in non-decreasing timestamp order. - Every
thresholdis a non-negative integer (0 <= threshold <= 10^5). 1 <= len(url), len(prefix) <= 200
Step-by-step walkthrough
Understand the operations and boundary rules
The judge replays a sequence of method calls on a single
AlertMonitorinstance and records one output per call:"record_error"with[timestamp, url]: records one failure forurl's normalized prefix and appendsNoneto the output list."should_alert"with[timestamp, prefix, threshold]: returnsTrueif the number of recorded failures forprefixinside[timestamp - 600, timestamp]is strictly greater thanthreshold, andFalseotherwise.
operations = ["record_error", "record_error", "record_error", "should_alert", "should_alert"] arguments = [[200, "shop.net/v2/checkout/pay"], [350, "shop.net/v2/checkout/refund"],[410, "shop.net/v2/catalog/view"], [500, "shop.net/v2/checkout", 1], [500, "shop.net/v2/checkout", 2]] output = [None, None, None, True, False]Check four details before coding:
- Inclusive window
[timestamp - 600, timestamp]: a failure at exacttimestamp - 600or exacttimestampstill counts (601integer seconds wide inclusive). - Strict threshold (
>): if2failures occurred andthreshold == 2,should_alertreturnsFalse. - Exact prefix lookup:
should_alertreceives an already-formed prefix like"shop.net/v2/checkout"and checks only that bucket (querying"shop.net/v2"does not sum"shop.net/v2/checkout"and"shop.net/v2/catalog"). - Chronological timestamps: in live request monitoring, calls arrive in non-decreasing
timestamporder (t_1 <= t_2 <= ...). Always confirm this assumption with your interviewer; if late out-of-order events can arrive, see the binary-search variant in the explanation.
Extract the two-segment URL prefix
A URL's prefix consists of the host plus up to the first two path segments. Splitting on
"/"places the host at index0and the first two path segments at indices1and2, so takingparts[:3]and rejoining with"/"handles every path depth cleanly:URL url.split("/") "/".join(parts[:3]) ----------------------------------- -------------------------------------------- ------------------------ "shop.net/v2/checkout/pay" -> ["shop.net", "v2", "checkout", "pay"] -> "shop.net/v2/checkout" "shop.net/v2/checkout/9/retry" -> ["shop.net", "v2", "checkout", "9", ...] -> "shop.net/v2/checkout" "shop.net/v2/checkout" -> ["shop.net", "v2", "checkout"] -> "shop.net/v2/checkout" "shop.net/ping" -> ["shop.net", "ping"] -> "shop.net/ping"def extract_url_prefix(url: str) -> str: """Return host plus the first two path segments (e.g. 'shop.net/v2/checkout/pay' -> 'shop.net/v2/checkout').""" parts = url.split("/") return "/".join(parts[:3])Why keeping a flat list of all errors falls short
The brute-force approach appends
(timestamp, prefix)to one list on everyrecord_error, and scans the entire list on everyshould_alert. That breaks down in two ways:- Every query takes
O(total errors ever recorded)time, even when querying a quiet or unknown prefix. - Old failures from hours ago stay in memory forever instead of being cleaned up.
We want each query to inspect only its own prefix, and we want expired timestamps to be removed cheaply.
- Every query takes
Key idea: one FIFO `deque` per prefix with front eviction
Store a dictionary
prefix_timestampsmapping eachprefixstring to acollections.deque(a double-ended queue that appends to the right and pops from the left inO(1)time). Because calls arrive in non-decreasing timestamp order, appending each newtimestampto the right keeps every deque sorted from oldest (left) to newest (right).When a call arrives at
current_time, any timestamp strictly belowcutoff_time = current_time - 600has fallen out of[current_time - 600, current_time]. And since all future calls will havetimestamp >= current_time, those expired timestamps can never fall inside a future window either — so we pop them permanently from the front!Deque for "shop.net/v2/checkout": deque([80, 200, 550, 750]) Query: should_alert(current_time=850, prefix="shop.net/v2/checkout", threshold=1) Active window: [850 - 600, 850] = [250, 850] (cutoff_time = 250) front = 80 < 250 -> popleft() front = 200 < 250 -> popleft() front = 550 >= 250 -> stop! Remaining deque: deque([550, 750]) -> len == 2 -> 2 > 1 is True!Why use
deque.popleft()instead oflist.pop(0)? Removing element0from a Pythonlistshifts every remaining element one slot left (O(k)per pop), whereasdeque.popleft()unlinks the front item inO(1). Every recorded failure is appended once and popped at most once, giving amortizedO(1)eviction cost per operation.Two extra hygiene details keep memory tidy:
- Evict expired timestamps inside
record_erroras well asshould_alert, so prefixes that receive failures without being queried do not accumulate unbounded history. - In
should_alert, use.get(prefix)so unknown prefixes never allocate empty deques, anddel self.prefix_timestamps[prefix]whenever eviction leaves a deque empty.
- Evict expired timestamps inside
Implement `AlertMonitor` and the `alert_monitor` driver
from collections import deque from typing import Dict, List, Optional WINDOW_SECONDS = 600 class AlertMonitor: """Tracks error counts per URL prefix over an inclusive rolling [t - 600, t] window.""" def __init__(self) -> None: self.prefix_timestamps: Dict[str, deque] = {} def _evict_expired(self, timestamps: deque, current_time: int) -> None: cutoff_time = current_time - WINDOW_SECONDS while timestamps and timestamps[0] < cutoff_time: timestamps.popleft() def record_error(self, timestamp: int, url: str) -> None: prefix = extract_url_prefix(url) if prefix not in self.prefix_timestamps: self.prefix_timestamps[prefix] = deque() timestamps = self.prefix_timestamps[prefix] timestamps.append(timestamp) self._evict_expired(timestamps, timestamp) def should_alert(self, timestamp: int, prefix: str, threshold: int) -> bool: timestamps = self.prefix_timestamps.get(prefix) if timestamps is None: return False self._evict_expired(timestamps, timestamp) if not timestamps: del self.prefix_timestamps[prefix] return False return len(timestamps) > thresholdThe top-level
alert_monitor(operations, arguments)function creates a freshAlertMonitorper test run, dispatches each operation, and appendsNonefor"record_error"so output indices match input indices.Trace Example 2 (`"auth.dev/oauth/token"`)
Call cutoff deque["auth.dev/oauth/token"] return --------------------------------------------------- ------ ----------------------------- ------ record_error(100, "auth.dev/oauth/token/refresh") -500 deque([100]) None record_error(450, "auth.dev/oauth/token/revoke") -150 deque([100, 450]) None should_alert(700, "auth.dev/oauth/token", 1) 100 deque([100, 450]) True (100 >= 100 kept; 2 > 1) should_alert(701, "auth.dev/oauth/token", 1) 101 deque([450]) (100 popped) False (1 > 1 is False)Complete solution
from collections import deque from typing import Any, Dict, List, Optional, Set, Tuple WINDOW_SECONDS = 600 # 10-minute rolling window in seconds def extract_url_prefix(url: str) -> str: """Return host plus the first two path segments (e.g. 'shop.net/v2/checkout/pay' -> 'shop.net/v2/checkout').""" # Splitting on '/' gives [host, seg1, seg2, ...]; [:3] safely keeps up to 3 parts. parts = url.split("/") return "/".join(parts[:3]) class AlertMonitor: """Tracks error counts per URL prefix over an inclusive rolling [t - 600, t] window.""" def __init__(self) -> None: # prefix_timestamps: maps prefix str -> deque[int] of error timestamps (oldest at index 0) self.prefix_timestamps: Dict[str, deque] = {} def _evict_expired(self, timestamps: deque, current_time: int) -> None: """Pop timestamps strictly older than current_time - 600 from the front of the deque.""" # Window [current_time - 600, current_time] is inclusive on both ends, # so an error at exact cutoff_time still counts (strict '<', not '<='). cutoff_time = current_time - WINDOW_SECONDS while timestamps and timestamps[0] < cutoff_time: timestamps.popleft() def record_error(self, timestamp: int, url: str) -> None: # Phase 1: Normalize full URL to its 2-segment prefix and append the new error time. prefix = extract_url_prefix(url) if prefix not in self.prefix_timestamps: self.prefix_timestamps[prefix] = deque() timestamps = self.prefix_timestamps[prefix] timestamps.append(timestamp) # Phase 2: Evict expired entries now too so write-only prefixes do not grow unboundedly. self._evict_expired(timestamps, timestamp) def should_alert(self, timestamp: int, prefix: str, threshold: int) -> bool: # Unknown prefix has 0 errors; since threshold >= 0, 0 > threshold is always False. # Using .get() avoids polluting prefix_timestamps with empty deques for queried-only keys. timestamps = self.prefix_timestamps.get(prefix) if timestamps is None: return False # Evict expired timestamps and delete the key if no recent errors remain. self._evict_expired(timestamps, timestamp) if not timestamps: del self.prefix_timestamps[prefix] return False # Alert fires only when active error count is strictly greater than threshold. return len(timestamps) > threshold def alert_monitor(operations: List[str], arguments: List[List]) -> List[Optional[bool]]: monitor = AlertMonitor() results: List[Optional[bool]] = [] for op_name, args in zip(operations, arguments): if op_name == "record_error": monitor.record_error(args[0], args[1]) results.append(None) elif op_name == "should_alert": results.append(monitor.should_alert(args[0], args[1], args[2])) else: raise ValueError(f"Unknown operation: {op_name}") return results✅ Submit now — all tests should pass.
Intuition & how it works
Picture giving each URL prefix its own ticket line: every time an error arrives at timestamp t, we place a stamped ticket at the back of that prefix's line, and whenever we record or check a prefix at time now, we tear off any tickets at the front stamped earlier than now - 600 before counting how many tickets remain. Counting events inside a moving [now - 600, now] interval is called a rolling sliding window, and we keep each prefix's tickets in a deque (double-ended queue) — a queue structure that supports adding to the back and removing from the front in O(1) constant time without shifting elements in memory. Because each error timestamp is appended once and popped from the front at most once across the entire run, cleanup costs amortized O(1) time (meaning the average cleanup work per call is constant, even if one call after a long quiet period pops many expired timestamps at once).
Why do simpler list-based designs fall short? Keeping one flat list of (timestamp, prefix) pairs forces every should_alert call to scan every historical error across all prefixes in O(total errors) time while leaking stale memory forever. Grouping by prefix into a standard Python list and calling list.pop(0) scopes lookups to one prefix, but every pop(0) shifts all k remaining elements one slot to the left, turning k expirations into O(k^2) work instead of O(k).
Let's trace the four calls from Example 2 on "auth.dev/oauth/token" step by step:
1. record_error(100, "auth.dev/oauth/token/refresh")
prefix = "auth.dev/oauth/token", cutoff = -500 -> deque = [100]
2. record_error(450, "auth.dev/oauth/token/revoke")
prefix = "auth.dev/oauth/token", cutoff = -150 -> deque = [100, 450]
3. should_alert(700, "auth.dev/oauth/token", threshold=1)
window [100, 700]: front 100 >= 100 (keep) -> len is 2, 2 > 1 -> True
4. should_alert(701, "auth.dev/oauth/token", threshold=1)
window [101, 701]: front 100 < 101 (popleft!), 450 >= 101 (keep)
deque = [450] -> len is 1, 1 > 1 -> False
Complexity
Let L be the length of the URL or prefix string in a call, P be the number of active prefixes stored, and W be the total number of error timestamps currently retained across all prefixes.
record_error: amortizedO(L)time. Splitting the URL string on"/"and hashing the prefix takeO(L)time; appending to the right of thedequetakesO(1)time, and each timestamp is popped by_evict_expiredat most once in its lifetime (O(1)amortized per recorded error).should_alert: amortizedO(L)time. Looking upprefixin the hash map takesO(L)time, popping expired front entries takes amortizedO(1)time, and checkinglen(timestamps) > thresholdtakesO(1)time.- Space:
O(P + W). The dictionary holds at mostPprefix keys andWtimestamps in total; each prefix retains at most the timestamps from the600seconds preceding its most recent call, and prefixes emptied duringshould_alertare deleted immediately.
Edge cases
- Exact boundary timestamps (
timestamp - 600andtimestamp): Both endpoints belong to[timestamp - 600, timestamp], so_evict_expiredpops only whentimestamps[0] < timestamp - 600(strict<), keeping an error at400when queried at1000and dropping it at1001. - Count equal to
threshold: Does not alert because the rule requires strictly greater (len(timestamps) > threshold); conversely,threshold = 0alerts on a single active error (1 > 0). - Multiple errors at the exact same second: Appending each call separately (
deque([500, 500, 500])) counts all three errors and expires all three together attimestamp = 1101. - Long quiet gap before a query (
stale data): A query hours later pops every old timestamp, deletes the empty deque fromprefix_timestamps, and returnsFalse; subsequent errors start fresh. - Unknown or never-errored prefix:
.get(prefix)returnsNoneand immediately returnsFalsewithout inserting an empty key intoprefix_timestamps. - URL path depth variations:
"shop.net/v2/checkout"(already two segments) and"shop.net/v2/checkout/pay/retry"both map to"shop.net/v2/checkout", whereas querying"shop.net/v2"checks only the exact key"shop.net/v2". (If URLs in production include a scheme like"https://shop.net/v2/checkout/pay", strip or preserve the scheme before splitting on"/"so"https:"and""aren't treated as host and segments.)
Common mistakes
- Off-by-one boundary operators: Using
>=instead of>forthresholdtriggers false alerts on ties, and using<=instead of<in_evict_expiredwrongly drops errors attimestamp - 600. - Using
list.pop(0)instead ofdeque.popleft(): Shifting ak-element Pythonliston each pop degrades burst eviction fromO(k)toO(k^2). - Evicting only inside
should_alert: Prefixes that log millions of errors without ever being queried would retain every timestamp in memory forever. - Using
defaultdict(deque)insideshould_alert: Indexingself.prefix_timestamps[prefix]on a read-only query allocates an emptydequefor every nonexistent prefix queried, slowly leaking dictionary keys. - Storing
AlertMonitoras a module-level global: Inalert_monitor(operations, arguments), always instantiatemonitor = AlertMonitor()inside the function so state from one test case never leaks into the next.
Alternative approaches
- Sorted list + binary search (
bisect) for out-of-order timestamps: If network delays cause events to arrive out of chronological order, maintain a sorted list per prefix withbisect.insort(times, timestamp)and count[timestamp - 600, timestamp]viabisect_right(times, timestamp) - bisect_left(times, timestamp - 600). Without a bound on lateness, no timestamp can ever be evicted; if events are delayed by at mostDseconds, you can safely evict timestamps older thanmax_timestamp_seen - D - 600. - Fixed-size per-second circular ring buffer: Store a
601-slot array(slot_second, count)per prefix indexed bytimestamp % 601. That caps memory per prefix at601integers even if a prefix receives50,000errors per second, tradingO(601)per-prefix overhead (or a maintained running sum) for bounded burst memory.
Follow-up questions
- How can we keep memory consumption bounded when millions of distinct URL prefixes pass through the monitor? Attack both idle prefixes and noisy prefixes. For idle prefixes, maintain a global time-ordered eviction queue (or doubly linked list / min-heap of
(last_seen_time, prefix)) so a background sweep deletes prefixes whose last error fell behindnow - 600, even ifshould_alertis never called on them. For noisy prefixes, aggregate timestamps into a time-bucketed ring buffer (a fixed-length circular array of sub-window counters, such as60ten-second buckets plus a running sum) so a prefix uses constant memory regardless of QPS; if approximate counts are acceptable, a count-min sketch (a fixed-size probabilistic hash-counter matrix that estimates frequencies using sub-linear memory and never undercounts) per time bucket bounds total RAM independent of prefix cardinality. - What structural changes would you make if the lookback horizon expanded from 10 minutes to a full 24-hour day? Changing
WINDOW_SECONDSfrom600to86400keeps the exact deque logicO(1)amortized, but storing raw timestamps for24hours multiplies per-prefix RAM by144x(864,000ints at10errors/sec). Instead, bucket errors into1,440one-minute counters (or8,640ten-second counters) per prefix and maintain a running 24-hour sum by subtracting the expiring bucket as the clock advances; if millisecond-exact edges matter, keep raw timestamps only for the oldest and newest partial buckets. Because losing24hours of history on a process restart would blind alerting for a full day, you should also persist bucket snapshots or replay from a durable log (like Kafka) on startup. - How would you partition or synchronize state if error ingestion and alert checks ran across a multi-node cluster? The cleanest scaling pattern is consistent hashing (a routing scheme that maps each prefix hash onto a ring of worker nodes so every event and query for the same prefix lands on the same primary node, minimizing data movement when nodes join or leave), which avoids cross-server coordination on the hot path while replicating state to a standby node for failover. Alternatively, stateless ingestion servers can batch local per-prefix, per-second counts every second and flush atomic
HINCRBY/INCRBYupdates with a TTL to a sharded store like Redis, whereshould_alertsums the active window's buckets. Because distributed servers have clock skew and network jitter, key buckets by event timestamp rather than arrival time and apply an allowed-lateness watermark (a short grace buffer of a few seconds before treating a time bucket as complete), trading a few seconds of alert latency for eventual consistency (all nodes converging to the same count once in-flight updates settle).
Follow-up questions
- How can we keep memory consumption bounded when millions of distinct URL prefixes pass through the monitor?
- What structural changes would you make if the lookback horizon expanded from 10 minutes to a full 24-hour day?
- How would you partition or synchronize state if error ingestion and alert checks ran across a multi-node cluster?
Similar questions
- Global Event Ticketing and Seat Inventory Platform
- In-Memory Relational Table with Transaction Rollback
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination
- Case-Insensitive Ticket Queue Filtering and UI State Debugging