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:

  1. "record_error" with [timestamp, url]: logs one failure at Unix second timestamp under url's normalized two-segment prefix, and appends None to the returned list.
  2. "should_alert" with [timestamp, prefix, threshold]: counts how many failures recorded for the exact prefix fall within the inclusive interval [timestamp - 600, timestamp], appending True when that count is strictly greater than threshold and False otherwise.

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 timestamp is a positive integer (1 <= timestamp <= 10^9), and calls arrive in non-decreasing timestamp order.
  • Every threshold is a non-negative integer (0 <= threshold <= 10^5).
  • 1 <= len(url), len(prefix) <= 200

Step-by-step walkthrough

  1. Understand the operations and boundary rules

    The judge replays a sequence of method calls on a single AlertMonitor instance and records one output per call:

    • "record_error" with [timestamp, url]: records one failure for url's normalized prefix and appends None to the output list.
    • "should_alert" with [timestamp, prefix, threshold]: returns True if the number of recorded failures for prefix inside [timestamp - 600, timestamp] is strictly greater than threshold, and False otherwise.
    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:

    1. Inclusive window [timestamp - 600, timestamp]: a failure at exact timestamp - 600 or exact timestamp still counts (601 integer seconds wide inclusive).
    2. Strict threshold (>): if 2 failures occurred and threshold == 2, should_alert returns False.
    3. Exact prefix lookup: should_alert receives 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").
    4. Chronological timestamps: in live request monitoring, calls arrive in non-decreasing timestamp order (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.
  2. 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 index 0 and the first two path segments at indices 1 and 2, so taking parts[: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])
    
  3. Why keeping a flat list of all errors falls short

    The brute-force approach appends (timestamp, prefix) to one list on every record_error, and scans the entire list on every should_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.

  4. Key idea: one FIFO `deque` per prefix with front eviction

    Store a dictionary prefix_timestamps mapping each prefix string to a collections.deque (a double-ended queue that appends to the right and pops from the left in O(1) time). Because calls arrive in non-decreasing timestamp order, appending each new timestamp to the right keeps every deque sorted from oldest (left) to newest (right).

    When a call arrives at current_time, any timestamp strictly below cutoff_time = current_time - 600 has fallen out of [current_time - 600, current_time]. And since all future calls will have timestamp >= 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 of list.pop(0)? Removing element 0 from a Python list shifts every remaining element one slot left (O(k) per pop), whereas deque.popleft() unlinks the front item in O(1). Every recorded failure is appended once and popped at most once, giving amortized O(1) eviction cost per operation.

    Two extra hygiene details keep memory tidy:

    • Evict expired timestamps inside record_error as well as should_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, and del self.prefix_timestamps[prefix] whenever eviction leaves a deque empty.
  5. 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) > threshold
    

    The top-level alert_monitor(operations, arguments) function creates a fresh AlertMonitor per test run, dispatches each operation, and appends None for "record_error" so output indices match input indices.

  6. 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)
    
  7. 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: amortized O(L) time. Splitting the URL string on "/" and hashing the prefix take O(L) time; appending to the right of the deque takes O(1) time, and each timestamp is popped by _evict_expired at most once in its lifetime (O(1) amortized per recorded error).
  • should_alert: amortized O(L) time. Looking up prefix in the hash map takes O(L) time, popping expired front entries takes amortized O(1) time, and checking len(timestamps) > threshold takes O(1) time.
  • Space: O(P + W). The dictionary holds at most P prefix keys and W timestamps in total; each prefix retains at most the timestamps from the 600 seconds preceding its most recent call, and prefixes emptied during should_alert are deleted immediately.

Edge cases

  • Exact boundary timestamps (timestamp - 600 and timestamp): Both endpoints belong to [timestamp - 600, timestamp], so _evict_expired pops only when timestamps[0] < timestamp - 600 (strict <), keeping an error at 400 when queried at 1000 and dropping it at 1001.
  • Count equal to threshold: Does not alert because the rule requires strictly greater (len(timestamps) > threshold); conversely, threshold = 0 alerts 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 at timestamp = 1101.
  • Long quiet gap before a query (stale data): A query hours later pops every old timestamp, deletes the empty deque from prefix_timestamps, and returns False; subsequent errors start fresh.
  • Unknown or never-errored prefix: .get(prefix) returns None and immediately returns False without inserting an empty key into prefix_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 > for threshold triggers false alerts on ties, and using <= instead of < in _evict_expired wrongly drops errors at timestamp - 600.
  • Using list.pop(0) instead of deque.popleft(): Shifting a k-element Python list on each pop degrades burst eviction from O(k) to O(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) inside should_alert: Indexing self.prefix_timestamps[prefix] on a read-only query allocates an empty deque for every nonexistent prefix queried, slowly leaking dictionary keys.
  • Storing AlertMonitor as a module-level global: In alert_monitor(operations, arguments), always instantiate monitor = 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 with bisect.insort(times, timestamp) and count [timestamp - 600, timestamp] via bisect_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 most D seconds, you can safely evict timestamps older than max_timestamp_seen - D - 600.
  • Fixed-size per-second circular ring buffer: Store a 601-slot array (slot_second, count) per prefix indexed by timestamp % 601. That caps memory per prefix at 601 integers even if a prefix receives 50,000 errors per second, trading O(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 behind now - 600, even if should_alert is 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 as 60 ten-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_SECONDS from 600 to 86400 keeps the exact deque logic O(1) amortized, but storing raw timestamps for 24 hours multiplies per-prefix RAM by 144x (864,000 ints at 10 errors/sec). Instead, bucket errors into 1,440 one-minute counters (or 8,640 ten-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 losing 24 hours 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 / INCRBY updates with a TTL to a sharded store like Redis, where should_alert sums 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

Similar questions

More Addepar interview questions

All 3 Addepar questions →