Streaming Network Log Intrusion Detection with Sliding Windows

Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen

Problem Statement

Security telemetry pipelines ingest high-volume text logs recording outbound and inbound network flows, evaluating streaming threshold rules to surface suspicious activity such as horizontal host discovery or connection floods. Implement a streaming log parser and sliding-window rule engine that scans log lines in chronological order and emits structured alerts.

Log Line Format & Parsing (parse_line)

Each raw line begins with a whitespace-delimited ISO-8601 timestamp followed by space-separated key=value attributes:

2025-07-14T08:15:00Z src=192.168.4.12 dst=172.16.0.10 proto=TCP

Implement parse_line(line: str) -> Optional[Event] returning Event(ts, fields):

  • ts (float): UTC seconds since the Unix epoch. Timestamps may end with Z/z, carry an explicit offset (e.g., +02:00), or omit a timezone (treat timezone-naive timestamps as UTC).
  • fields (Dict[str, str]): dictionary of key=value pairs after the timestamp. Ignore extra tokens that do not contain = or that have an empty key or value.
  • Both src and dst are required and must be valid IPv4 or IPv6 addresses, normalized to canonical string form (for instance, '0:0:0:0:0:0:0:1' normalizes to '::1') so equivalent spellings count as a single address.
  • Return None when a line is blank, lacks a valid leading timestamp, omits src or dst, or contains an invalid IP address.

Sliding-Window Rules & Alert Semantics

  • WindowRule(name, key_field, threshold, window_seconds, value_field=None):
    • Validates threshold >= 1 and window_seconds > 0 (raising ValueError otherwise).
    • Partitions events by event.fields[key_field]. When an event arrives at timestamp t, the active window is the half-open interval (t - window_seconds, t]: earlier events for that key with timestamp <= t - window_seconds have expired, whereas events strictly greater than t - window_seconds (including timestamp ties at t) remain active.
    • If value_field is provided (e.g., "dst"), the window count is the number of distinct values of event.fields[value_field] among active events for that key. If value_field is None, the window count is the total number of active events for that key. Events missing key_field (or value_field when set) do not update counts.
  • fan_out_rule(threshold=10, window_seconds=600):
    • Default horizontal-scan rule (WindowRule("fan_out", "src", threshold, window_seconds, value_field="dst")), triggering when a single source IP contacts strictly more than 10 (at least 11) distinct destination IPs within 600 seconds.
  • One alert per episode (Detector, detect_attacks, format_alert):
    • Detector(rules=None) defaults to [fan_out_rule()] and counts skipped bad lines in self.malformed.
    • For each (rule, key) pair, emit Alert(rule, key, start, end, count) on the exact event that pushes the active count from <= threshold to threshold + 1, where start is the oldest timestamp still inside the active window, end is the triggering event's timestamp, and count == threshold + 1.
    • Suppress duplicate alerts while that key remains above threshold; re-arm only once a subsequent event for that key observes count <= threshold (or after the key ages out completely).
    • detector.tracked_keys() returns the total number of (rule, key) window states held in RAM; any key whose latest event is <= t_latest - window_seconds must be evicted.
    • detect_attacks(lines, rules=None) streams lines through Detector(rules) and returns all emitted Alert records in order; format_alert(alert) formats an alert as "{rule} key={key} count={count} window={start_utc}..{end_utc}" using %Y-%m-%dT%H:%M:%SZ.

Examples

Example 1

lines = [
    "2025-07-14T08:15:00Z src=192.168.4.12 dst=172.16.0.10 proto=TCP",
    "2025-07-14T08:15:15Z src=192.168.4.12 dst=172.16.0.11 proto=TCP",
    "2025-07-14T08:15:25Z src=192.168.4.12 dst=172.16.0.10 proto=TCP",
    "2025-07-14T08:15:40Z src=192.168.4.12 dst=172.16.0.12 proto=TCP",
    "2025-07-14T08:15:50Z src=192.168.4.12 dst=172.16.0.13 proto=TCP",
    "2025-07-14T08:16:10Z src=192.168.4.12 dst=172.16.0.14 proto=TCP",
]
alerts = detect_attacks(lines, [fan_out_rule(threshold=2, window_seconds=60)])
formatted = [format_alert(a) for a in alerts]

Output:

["fan_out key=192.168.4.12 count=3 window=2025-07-14T08:15:00Z..2025-07-14T08:15:40Z"]

Walk-through: With threshold=2 and window_seconds=60, source 192.168.4.12 reaches 2 distinct destinations by 08:15:15Z. Repeating 172.16.0.10 at 08:15:25Z keeps the distinct count at 2. Contacting 172.16.0.12 at 08:15:40Z pushes the distinct count to 3, firing one alert spanning 08:15:00Z..08:15:40Z. The 08:15:50Z and 08:16:10Z events stay in the same above-threshold episode (even after 08:15:00Z ages out at 08:16:10Z, 172.16.0.10 remains active via 08:15:25Z), so no duplicate alert is emitted.

Example 2

rule = WindowRule("syn_burst", key_field="src", threshold=2, window_seconds=30, value_field=None)
detector = Detector([rule])
stream = [
    "2025-07-14T09:00:00Z src=0:0:0:0:0:0:0:1 dst=198.51.100.7 port=22",
    "2025-07-14T09:00:10Z src=::1 dst=198.51.100.7 port=22",
    "corrupted-line-without-timestamp",
    "2025-07-14T09:00:30Z src=::1 dst=198.51.100.7 port=22",
    "2025-07-14T09:00:35Z src=::1 dst=198.51.100.7 port=22",
]
emitted = []
for raw in stream:
    emitted.extend(detector.process_line(raw))

Output:

[format_alert(a) for a in emitted] == ["syn_burst key=::1 count=3 window=2025-07-14T09:00:10Z..2025-07-14T09:00:35Z"]
detector.malformed == 1

Walk-through: 0:0:0:0:0:0:0:1 and ::1 canonicalize to the same source "::1", while the corrupted line increments detector.malformed to 1. At 09:00:30Z, the 09:00:00Z event is 30 seconds old (<= 09:00:30Z - 30s) and expires, leaving 2 active events (<= 2). The 09:00:35Z event brings (09:00:05Z, 09:00:35Z] to 3 total events and emits the alert starting at 09:00:10Z.

Constraints

  • Stream lines incrementally in O(1) amortized window-update work per rule per line without loading the entire input into memory.
  • Evict per-key state whenever a key has no events inside (t_latest - window_seconds, t_latest], keeping detector.tracked_keys() proportional only to recently active keys.
  • If an out-of-order event arrives with event.ts < latest_ts, clamp its effective timestamp to latest_ts so sliding-window invariants remain monotonic.

Step-by-step walkthrough

  1. Clarify the log contract, window boundaries, and alert policy

    Before writing code for an open-ended security engineering prompt, pin down every boundary condition from the clarifying questions — each choice changes what alerts fire:

    • Streaming log format: Each line starts with an ISO-8601 timestamp followed by key=value tokens including src and dst. We iterate over lines lazily (Iterable[str]) so a 50 GB log file never has to fit in RAM.
    • Malformed lines: Skip and count them in detector.malformed instead of raising an exception — a single truncated log line must never crash a security monitor.
    • Sliding window (t - W, t], not fixed clock buckets: Fixed 10-minute buckets (10:00–10:10, 10:10–10:20) miss a burst of 6 destinations at 10:09:55 plus 5 destinations at 10:10:05. A sliding window ending at timestamp t keeps events strictly newer than t - 600 (old_ts > t - 600), so events 600 seconds apart do not share a window, events 599 seconds apart do, and multiple connections in the exact same second all count.
    • Strict threshold (> 10 means 11+ distinct destinations): Forty connections to the same 10 servers stay quiet; the 11th distinct destination triggers the alert.
    • One alert per episode: Emit an alert on the exact event that pushes a source from <= 10 to 11, stay silent while that source remains above 10, and re-arm only after an event of that source sees its active count fall back to <= 10.

    We represent parsed lines and emitted alerts with lightweight NamedTuple records:

    from typing import Dict, NamedTuple
    
    
    class Event(NamedTuple):
        # Parsed log line, e.g. Event(ts=1752480900.0, fields={"src": "192.168.4.12", "dst": "172.16.0.10"})
        ts: float               # seconds since the Unix epoch in UTC
        fields: Dict[str, str]  # every key=value token on the line (with canonical src and dst)
    
    
    class Alert(NamedTuple):
        # Emitted once per attack episode when count crosses from <= threshold to threshold + 1
        rule: str     # name of the rule that fired, e.g. "fan_out"
        key: str      # entity key that triggered the rule, e.g. "192.168.4.12"
        start: float  # timestamp of the oldest event currently inside the active window
        end: float    # timestamp of the event that pushed count above threshold
        count: int    # count at trigger time (always threshold + 1)
    
  2. Parse log lines defensively (UTC timestamps and canonical IPs)

    Security parsers face three classic pitfalls in real logs:

    1. Timezone drift: Calling .timestamp() on a timezone-naive Python datetime interprets it in the server's local timezone, making mixed naive and +00:00 lines jump by hours! Always attach timezone.utc when no offset is present, and normalize trailing "Z" to "+00:00".
    2. Equivalent IP spellings: In IPv6, 0:0:0:0:0:0:0:1 and ::1 are the exact same destination. Comparing raw strings would count them as two distinct hosts; normalizing through ipaddress.ip_address(...) turns both into "::1" and simultaneously rejects invalid IPs like 10.0.0.999.
    3. Unexpected extra tokens: Ignore stray tokens without = rather than dropping an entire attack line.
    from typing import Dict, Optional
    from datetime import datetime, timezone
    import ipaddress
    
    
    def parse_timestamp(text: str) -> Optional[float]:
        """Parse an ISO-8601 timestamp string into UTC Unix epoch seconds, or None if invalid."""
        # Replace trailing 'Z'/'z' with '+00:00' for compatibility across Python versions
        if text.endswith(("Z", "z")):
            text = text[:-1] + "+00:00"
        try:
            moment = datetime.fromisoformat(text)
        except ValueError:
            return None
        # Treat timezone-naive timestamps as UTC rather than silently using the host's local timezone
        if moment.tzinfo is None:
            moment = moment.replace(tzinfo=timezone.utc)
        return moment.timestamp()
    
    
    def normalize_ip(text: str) -> Optional[str]:
        """Return canonical IPv4/IPv6 text ('0:0:0:0:0:0:0:1' -> '::1'), or None if invalid."""
        try:
            parsed_ip = ipaddress.ip_address(text)
        except ValueError:
            return None
        return str(parsed_ip)
    
    
    def parse_line(line: str) -> Optional[Event]:
        """Parse '<ISO-8601 timestamp> key=value ...' into an Event, or None if malformed."""
        tokens = line.split()
        if not tokens:
            return None
    
        # Phase 1: First token must be a valid timestamp
        ts = parse_timestamp(tokens[0])
        if ts is None:
            return None
    
        # Phase 2: Extract key=value pairs; ignore free-text tokens without '='
        fields: Dict[str, str] = {}
        for token in tokens[1:]:
            key, sep, value = token.partition("=")
            if sep and key and value:
                fields[key] = value
    
        # Phase 3: Require and canonicalize both src and dst IP addresses so equivalent
        # spellings of the same IPv6 address are counted as one destination, not two
        if "src" not in fields or "dst" not in fields:
            return None
        canonical_src = normalize_ip(fields["src"])
        canonical_dst = normalize_ip(fields["dst"])
        if canonical_src is None or canonical_dst is None:
            return None
    
        fields["src"] = canonical_src
        fields["dst"] = canonical_dst
        return Event(ts, fields)
    
  3. Why a naive first version grinds to a halt on large logs

    A brute-force implementation that passes tiny unit tests usually stores every (ts, dst) per source in a Python list and rebuilds the set of recent destinations on every incoming line:

    Line 1,000 arrives -> scans events 1..1,000 to build set()
    Line 1,001 arrives -> scans events 1..1,001 ALL OVER AGAIN (999 identical checks!)
    Line 1,002 arrives -> scans events 1..1,002 ALL OVER AGAIN (1,000 identical checks!)
    

    Three problems compound at scale: - Quadratic time (O(N^2)): If one chatty server generates H log lines, rescanning its history takes 1 + 2 + ... + H = O(H^2) steps. Even breaking at the 10-minute boundary still repeats O(W) work per line (W = events inside one 10-minute window, easily tens of thousands for a busy proxy). - Unbounded memory (O(N)): Appending to history[src] without evicting old events or idle IPs keeps the entire log in RAM. - Permanent suppression: Storing alerted_ips in a plain set silences a source forever after its first burst, missing a second attack hours later.

  4. Slide a per-source `deque` and reference `Counter` in `O(1)` amortized time

    Instead of rebuilding the window from scratch, notice that between one line and the next for the same source, only two tiny things change: one new event enters on the right, and zero or more old events expire on the left.

    Why can't we just store a deque of events plus a Python set of active destinations? Because a source can hit the same destination twice inside the window ((t=0, .10) and (t=25, .10) in Example 1). When (t=0, .10) expires at t=70, .10 is still inside the window via (t=25, .10)! A reference counter (collections.Counter mapping dst -> how many in-window events point to dst) solves this cleanly:

    1. Evict expired events from the left of a deque while front_ts <= event.ts - W: decrement counts[old_dst] -= 1, and delete old_dst from counts when its count hits 0.
    2. Append the new event (event.ts, dst) to the right of the deque and increment counts[dst] += 1.
    3. Read distinct destinations in O(1) as len(counts)!

    Watch this on the 6 events of Example 1 (src=192.168.4.12, threshold = 2 so 3+ distinct destinations alert, window = 60s after 08:15:00Z):

    Event       Evicted (ts <= now-60)  Active deque                                counts                         len(counts)
    t=0,  .10   none                    [(0,.10)]                                   {.10:1}                        1
    t=15, .11   none                    [(0,.10),(15,.11)]                          {.10:1,.11:1}                  2
    t=25, .10   none                    [(0,.10),(15,.11),(25,.10)]                 {.10:2,.11:1}                  2 (repeat!)
    t=40, .12   none                    [(0,.10),(15,.11),(25,.10),(40,.12)]        {.10:2,.11:1,.12:1}            3 -> ALERT!
    t=50, .13   none                    [(0,.10),(15,.11),(25,.10),(40,.12),(50,.13)] {.10:2,.11:1,.12:1,.13:1}    4 (silent)
    t=70, .14   (0,.10) since 0 <= 10   [(15,.11),(25,.10),(40,.12),(50,.13),(70,.14)] {.10:1,.11:1,.12:1,.13:1,.14:1} 5 (silent:
                                        (.10 stays active via (25,.10)!)                                           same burst)
    

    Every event is pushed to the deque once and popped once, so sliding the window takes O(1) amortized time per event regardless of how many thousands of connections sit inside the 10-minute window!

  5. Generalize into one `WindowRule` configuration for any attack rule

    Most sliding-window security rules share the exact same skeleton: "group by key_field; inside window_seconds, alert if total events (value_field=None) or distinct values of value_field exceed threshold." Separating stateless rule configuration (WindowRule) from per-key state (_WindowState) lets fan-out scans, DDoS fan-in (key_field="dst", value_field="src"), port scans (key_field="src", value_field="port"), and brute-force floods (key_field="src", value_field=None) share one engine:

    from typing import Optional
    from collections import Counter, deque
    
    
    class WindowRule:
        def __init__(
            self,
            name: str,
            key_field: str,
            threshold: int,
            window_seconds: float,
            value_field: Optional[str] = None,
        ):
            if threshold < 1 or window_seconds <= 0:
                raise ValueError("threshold must be >= 1 and window_seconds > 0")
            self.name = name
            self.key_field = key_field
            self.threshold = threshold
            self.window = window_seconds
            self.value_field = value_field
    
    
    def fan_out_rule(threshold: int = 10, window_seconds: float = 600) -> WindowRule:
        """Default rule: one source IP contacting more than `threshold` distinct destinations."""
        return WindowRule("fan_out", "src", threshold, window_seconds, value_field="dst")
    
    
    class _WindowState:
        """Sliding-window state for a single (rule, key) pair."""
    
        def __init__(self):
            # events: deque of (timestamp, tracked_value) ordered from oldest to newest
            self.events = deque()
            # counts: Counter mapping tracked_value -> number of in-window events carrying it
            self.counts = Counter()
            # in_alert: True once this burst alerted; resets to False only when count <= threshold
            self.in_alert = False
            # last_ts: timestamp of the newest event recorded for this key
            self.last_ts = 0.0
    
  6. Bound memory by evicting idle keys from an `OrderedDict`

    What if 5,000,000 internet scanners each send a single packet at 09:00 and never appear again? Without key eviction, states would hold 5,000,000 dead _WindowState objects forever!

    Any key whose last_ts <= event.ts - rule.window has zero events left in any future window, so we can forget it completely. By storing key -> _WindowState inside an OrderedDict (a dictionary that remembers insertion order and moves any key to the back in O(1) via move_to_end), keys stay sorted from least-recently active at the front to most-recently active at the back:

    OrderedDict `states` when new event arrives at t = 700 (cutoff = 700 - 600 = 100):
      front ──> [192.168.4.1: last_ts=12] -> [192.168.4.2: last_ts=85] -> [192.168.4.8: last_ts=450] <── back
                     <= 100: pop!                 <= 100: pop!                 > 100: STOP immediately!
    

    Wait — could deleting an idle key lose state.in_alert = True and cause a duplicate alert? No! Because WindowRule enforces threshold >= 1, if that source ever returns later with an empty window, its very first new packet has current_count == 1 <= threshold, which would reset state.in_alert = False anyway!

    from collections import OrderedDict
    
    
    def _drop_idle(states: "OrderedDict[str, _WindowState]", cutoff: float) -> None:
        while states:
            oldest_key = next(iter(states))
            if states[oldest_key].last_ts > cutoff:
                break
            del states[oldest_key]
    
    
    def _apply_rule(
        rule: WindowRule,
        states: "OrderedDict[str, _WindowState]",
        event: Event,
    ) -> Optional[Alert]:
        cutoff = event.ts - rule.window
        _drop_idle(states, cutoff)
    
        key = event.fields.get(rule.key_field)
        if key is None:
            return None
    
        tracked_value: Optional[str] = None
        if rule.value_field is not None:
            tracked_value = event.fields.get(rule.value_field)
            if tracked_value is None:
                return None
    
        state = states.get(key)
        if state is None:
            state = _WindowState()
            states[key] = state
        else:
            states.move_to_end(key)
    
        while state.events and state.events[0][0] <= cutoff:
            _, old_value = state.events.popleft()
            state.counts[old_value] -= 1
            if state.counts[old_value] == 0:
                del state.counts[old_value]
    
        state.events.append((event.ts, tracked_value))
        state.counts[tracked_value] += 1
        state.last_ts = event.ts
    
        if rule.value_field is None:
            current_count = len(state.events)
        else:
            current_count = len(state.counts)
    
        if current_count <= rule.threshold:
            state.in_alert = False
            return None
        if state.in_alert:
            return None
    
        state.in_alert = True
        window_start = state.events[0][0]
        return Alert(rule.name, key, window_start, event.ts, current_count)
    
  7. Wrap the streaming `Detector` and benchmark the speedup

    Detector holds one OrderedDict per rule, tracks malformed and late counters, and exposes process_line for live or file-based streaming. If a slightly out-of-order line arrives (event.ts < self.latest), clamping its timestamp to self.latest preserves monotonic order without dropping the connection (while the follow-ups show a full min-heap reorder buffer).

    Benchmarking the O(1) amortized sliding window against the naive window-rescanning detector on dense logs (100 events/sec inside a single 10-minute window) shows the asymptotic gap clearly:

    Input lines    Sliding window    Naive rescan    Parsing alone
         5,000          0.018 s          0.150 s          0.017 s
        10,000          0.036 s          0.556 s          0.029 s
        20,000          0.070 s          2.228 s          0.060 s
        40,000          0.141 s          8.525 s          0.117 s
    

    Doubling the log size doubles our detector's runtime (2x linear scaling, with ~85% of time spent simply parsing strings) while quadrupling the naive rescan (4x quadratic blowup, already 60x slower at just 40,000 lines).

  8. Design targeted test cases for every boundary

    A thorough test suite targets every off-by-one and state-management edge case:

    • Threshold boundaries: 10 distinct destinations emit []; adding an 11th emits one Alert with count = 11 and exact [start, end] timestamps.
    • Repeated destinations: 40 connections cycling across 10 hosts emit [], catching implementations that accidentally count total packets instead of distinct IPs.
    • Exact window edge and fixed-bucket straddle: 10 hosts at t = 0 plus 1 new host at t = 600 emit [] (600 <= 600 expired), whereas t = 599 fires; 6 hosts at t = 590..595 plus 5 hosts at t = 605..609 straddle a 10-minute clock boundary and fire cleanly.
    • Episode reset and source isolation: 15 destinations in one burst fire once, stay silent at 12..15, reset after dropping <= 10, and fire again on a second burst at t = 700..709, while an interleaved second source IP never pollutes the first.
    • Malformed inputs & IPv6 normalization: blank lines, invalid IPs (999.1.1.1), missing dst, and 0:0:0:0:0:0:0:1 vs ::1.
    • Multi-rule reuse, randomized differential testing, and memory bounds: cross-checking 120 random logs against a simple O(N^2) reference oracle, verifying tracked_keys() drops 1,000 idle IPs once time advances past 600s, and timing 20,000 dense lines.
  9. Complete solution

    from typing import Dict, Iterable, List, NamedTuple, Optional
    from collections import Counter, OrderedDict, deque
    from datetime import datetime, timezone
    import ipaddress
    
    
    class Event(NamedTuple):
        # Parsed log line, e.g. Event(ts=1752480900.0, fields={"src": "192.168.4.12", "dst": "172.16.0.10"})
        ts: float               # seconds since the Unix epoch in UTC
        fields: Dict[str, str]  # every key=value token on the line (with canonical src and dst)
    
    
    class Alert(NamedTuple):
        # Emitted once per attack episode when count crosses from <= threshold to threshold + 1
        rule: str     # name of the rule that fired, e.g. "fan_out"
        key: str      # entity key that triggered the rule, e.g. "192.168.4.12"
        start: float  # timestamp of the oldest event currently inside the active window
        end: float    # timestamp of the event that pushed count above threshold
        count: int    # count at trigger time (always threshold + 1)
    
    
    class WindowRule:
        """Alert when one key exceeds `threshold` events (or distinct values of `value_field`)
        inside any sliding window of length `window_seconds`.
    
        The active window ending at timestamp `t` is the half-open interval `(t - window_seconds, t]`,
        meaning events with `old_ts <= t - window_seconds` have expired, while events strictly after
        `t - window_seconds` (including ties at `t`) count toward the window.
        """
    
        def __init__(
            self,
            name: str,
            key_field: str,
            threshold: int,
            window_seconds: float,
            value_field: Optional[str] = None,
        ):
            if threshold < 1 or window_seconds <= 0:
                raise ValueError("threshold must be >= 1 and window_seconds > 0")
            self.name = name
            self.key_field = key_field
            self.threshold = threshold
            self.window = window_seconds
            # value_field=None counts total events; value_field="dst" counts distinct destinations
            self.value_field = value_field
    
    
    def fan_out_rule(threshold: int = 10, window_seconds: float = 600) -> WindowRule:
        """Default rule: one source IP contacting more than `threshold` distinct destinations."""
        return WindowRule("fan_out", "src", threshold, window_seconds, value_field="dst")
    
    
    def parse_timestamp(text: str) -> Optional[float]:
        """Parse an ISO-8601 timestamp string into UTC Unix epoch seconds, or None if invalid."""
        # Replace trailing 'Z'/'z' with '+00:00' for compatibility across Python versions
        if text.endswith(("Z", "z")):
            text = text[:-1] + "+00:00"
        try:
            moment = datetime.fromisoformat(text)
        except ValueError:
            return None
        # Treat timezone-naive timestamps as UTC rather than silently using the host's local timezone
        if moment.tzinfo is None:
            moment = moment.replace(tzinfo=timezone.utc)
        return moment.timestamp()
    
    
    def normalize_ip(text: str) -> Optional[str]:
        """Return canonical IPv4/IPv6 text ('0:0:0:0:0:0:0:1' -> '::1'), or None if invalid."""
        try:
            parsed_ip = ipaddress.ip_address(text)
        except ValueError:
            return None
        return str(parsed_ip)
    
    
    def parse_line(line: str) -> Optional[Event]:
        """Parse '<ISO-8601 timestamp> key=value ...' into an Event, or None if malformed."""
        tokens = line.split()
        if not tokens:
            return None
    
        # Phase 1: First token must be a valid timestamp
        ts = parse_timestamp(tokens[0])
        if ts is None:
            return None
    
        # Phase 2: Extract key=value pairs; ignore free-text tokens without '='
        fields: Dict[str, str] = {}
        for token in tokens[1:]:
            key, sep, value = token.partition("=")
            if sep and key and value:
                fields[key] = value
    
        # Phase 3: Require and canonicalize both src and dst IP addresses so equivalent
        # spellings of the same IPv6 address are counted as one destination, not two
        if "src" not in fields or "dst" not in fields:
            return None
        canonical_src = normalize_ip(fields["src"])
        canonical_dst = normalize_ip(fields["dst"])
        if canonical_src is None or canonical_dst is None:
            return None
    
        fields["src"] = canonical_src
        fields["dst"] = canonical_dst
        return Event(ts, fields)
    
    
    class _WindowState:
        """Sliding-window state for a single (rule, key) pair."""
    
        def __init__(self):
            # events: deque of (timestamp, tracked_value) ordered from oldest to newest
            self.events = deque()
            # counts: Counter mapping tracked_value -> number of in-window events carrying it
            self.counts = Counter()
            # in_alert: True once this burst alerted; resets to False only when count <= threshold
            self.in_alert = False
            # last_ts: timestamp of the newest event recorded for this key
            self.last_ts = 0.0
    
    
    def _drop_idle(states: "OrderedDict[str, _WindowState]", cutoff: float) -> None:
        """Evict keys whose newest event is at or before `cutoff` (`event.ts - rule.window`).
    
        `states` is maintained in non-decreasing order of `last_ts` (least-recently active first),
        so stopping at the first non-expired front entry makes eviction O(1) amortized per event.
        Dropping idle state is also safe for `in_alert`: because `threshold >= 1`, any returning
        key starts with a single event (`count == 1 <= threshold`), which resets `in_alert` anyway.
        """
        while states:
            oldest_key = next(iter(states))
            if states[oldest_key].last_ts > cutoff:
                break
            del states[oldest_key]
    
    
    def _apply_rule(
        rule: WindowRule,
        states: "OrderedDict[str, _WindowState]",
        event: Event,
    ) -> Optional[Alert]:
        """Advance one rule's sliding windows with `event` and return an Alert on a new crossing."""
        # Events at or before `cutoff` are >= rule.window seconds old and fall outside (cutoff, ts]
        cutoff = event.ts - rule.window
        _drop_idle(states, cutoff)
    
        key = event.fields.get(rule.key_field)
        if key is None:
            return None
    
        tracked_value: Optional[str] = None
        if rule.value_field is not None:
            tracked_value = event.fields.get(rule.value_field)
            if tracked_value is None:
                return None
    
        # Fetch or create per-key state and move it to the back (most-recently active)
        state = states.get(key)
        if state is None:
            state = _WindowState()
            states[key] = state
        else:
            states.move_to_end(key)
    
        # Phase 1: Evict expired events from the front; use `<= cutoff` so events exactly
        # `window_seconds` apart do NOT share a window
        while state.events and state.events[0][0] <= cutoff:
            _, old_value = state.events.popleft()
            state.counts[old_value] -= 1
            # Must delete zero-count keys because Counter keeps `key: 0` after subtraction!
            if state.counts[old_value] == 0:
                del state.counts[old_value]
    
        # Phase 2: Append the incoming event to the back of the sliding window
        state.events.append((event.ts, tracked_value))
        state.counts[tracked_value] += 1
        state.last_ts = event.ts
    
        # Phase 3: Read current window count in O(1) and apply one-alert-per-episode logic
        if rule.value_field is None:
            current_count = len(state.events)
        else:
            current_count = len(state.counts)
    
        if current_count <= rule.threshold:
            # Count is back at or below threshold, ending any prior attack episode
            state.in_alert = False
            return None
    
        if state.in_alert:
            # Already alerted during the current above-threshold episode; suppress duplicates
            return None
    
        state.in_alert = True
        window_start = state.events[0][0]
        return Alert(rule.name, key, window_start, event.ts, current_count)
    
    
    class Detector:
        """Streaming detector: feed log lines in timestamp order and receive alerts immediately."""
    
        def __init__(self, rules: Optional[List[WindowRule]] = None):
            if rules is None:
                rules = [fan_out_rule()]
            self.rules = rules
            # states[i]: OrderedDict[key_str, _WindowState] ordered by activity time for rules[i]
            self.states: List["OrderedDict[str, _WindowState]"] = [
                OrderedDict() for _ in rules
            ]
            self.malformed = 0               # count of unparseable lines skipped
            self.late = 0                    # count of out-of-order lines clamped to `self.latest`
            self.latest: Optional[float] = None
    
        def process_line(self, line: str) -> List[Alert]:
            event = parse_line(line)
            if event is None:
                self.malformed += 1
                return []
            return self.process_event(event)
    
        def process_event(self, event: Event) -> List[Alert]:
            # Keep stream clock monotonic so OrderedDict order and deque order stay valid
            if self.latest is not None and event.ts < self.latest:
                self.late += 1
                event = Event(self.latest, event.fields)
            self.latest = event.ts
    
            alerts: List[Alert] = []
            for rule, rule_states in zip(self.rules, self.states):
                alert = _apply_rule(rule, rule_states, event)
                if alert is not None:
                    alerts.append(alert)
            return alerts
    
        def tracked_keys(self) -> int:
            """Total number of active `(rule, key)` windows currently held in memory."""
            total_keys = 0
            for rule_states in self.states:
                total_keys += len(rule_states)
            return total_keys
    
    
    def detect_attacks(
        lines: Iterable[str],
        rules: Optional[List[WindowRule]] = None,
    ) -> List[Alert]:
        """Stream `lines` through a `Detector` and return all alerts in emission order."""
        detector = Detector(rules)
        all_alerts: List[Alert] = []
        for line in lines:
            all_alerts.extend(detector.process_line(line))
        return all_alerts
    
    
    def format_alert(alert: Alert) -> str:
        """Format an Alert as '<rule> key=<k> count=<c> window=<start_iso>..<end_iso>'."""
        start_str = datetime.fromtimestamp(alert.start, timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
        end_str = datetime.fromtimestamp(alert.end, timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
        return f"{alert.rule} key={alert.key} count={alert.count} window={start_str}..{end_str}"
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of a security guard watching badge swipes to catch anyone entering more than 10 distinct server rooms within any rolling 10-minute span. Instead of rewinding the entire day's security tape from the start every time someone badges a door, the guard keeps a short rolling list per active badge (collections.deque, a double-ended queue supporting O(1) appends at the back and O(1) pops from the front) plus a reference counter (collections.Counter, tracking how many active swipes inside the 10-minute window hit each room). When a swipe arrives at t = 612s, the guard crosses off entries at or before t = 12s from the front, deletes any room whose count drops to 0, appends the new swipe at the back, and checks len(counts) in instant O(1) time! To keep memory bounded across millions of quiet source IPs, active per-source states live inside an OrderedDict (a dictionary sorted by recent activity) so idle sources drop off the front in O(1) amortized time too.

Three obvious shortcuts break down here. First, re-scanning a source's connection history on every line repeats nearly identical work over and over, degrading to O(N * W) or O(N^2) time (8.5s vs 0.14s on just 40,000 lines). Second, slicing time into fixed 10-minute clock buckets (08:10–08:20, 08:20–08:30) misses an attack split across 08:19:50 and 08:20:05. Third, storing active destinations in a plain set without reference counts deletes .10 too early when an attacker visits .10 at t = 0 and again at t = 25, and t = 0 expires first!

Here is how the detector processes the 6 events of Example 1 (src=192.168.4.12, threshold = 2, window = 60s after 08:15:00Z):

Arrival     Expired (<= now-60)   Window deque                                       counts                         Distinct   Action
t=0,  .10   none                  [(0,.10)]                                          {.10:1}                           1       quiet
t=15, .11   none                  [(0,.10),(15,.11)]                                 {.10:1,.11:1}                     2       quiet
t=25, .10   none                  [(0,.10),(15,.11),(25,.10)]                        {.10:2,.11:1}                     2       repeat .10
t=40, .12   none                  [(0,.10),(15,.11),(25,.10),(40,.12)]               {.10:2,.11:1,.12:1}               3       ALERT (0..40)!
t=50, .13   none                  [(0,.10),(15,.11),(25,.10),(40,.12),(50,.13)]      {.10:2,.11:1,.12:1,.13:1}         4       in_alert=True
t=70, .14   pop (0,.10)           [(15,.11),(25,.10),(40,.12),(50,.13),(70,.14)]     {.10:1,.11:1,.12:1,.13:1,.14:1}   5       in_alert=True

Complexity

Let N be the number of log lines, L be the character length of a line, R be the number of WindowRule instances, and E_2W be the maximum number of events arriving within 2 * W seconds across all active keys.

  • Time: O(N * (L + R)) total (O(L + R) amortized per log line). Splitting and validating each line's timestamp and two IP addresses scans its L characters once. Then, for each of the R rules, every event is appended to its key's deque at most once and popped at most once across the entire run, and every key state inserted into OrderedDict is moved/evicted in O(1) amortized hash-map operations. Even if one quiet-then-active line pops 500 expired events at once, those 500 pops were already paid for when the 500 events arrived (amortized analysis, meaning the average cost per operation over any sequence of N events has a strict constant upper bound).
  • Space: O(R * E_2W) working memory (independent of total log size N). The input Iterable[str] is streamed one line at a time. _drop_idle deletes any key whose newest event is older than now - W, and a surviving active key (whose newest event is after now - W) can hold un-popped events in its deque dating back at most to now - 2 * W. Thus memory tracks active traffic volume over 2 * W, never total file size.

Edge cases

  • Exact threshold (10 vs 11): Ten distinct destinations stay quiet (count <= threshold); the 11th emits a single Alert with count = 11.
  • Repeated connections to the same destinations: Forty hits to 10 destinations increment counts[dst] values without increasing len(counts).
  • Exact window boundary (600s vs 599s) and timestamp ties: Because the active window is (t - 600, t], state.events[0][0] <= t - 600 evicts events 600s old while keeping events 599s old and keeping simultaneous events at t.
  • Burst straddling a round clock mark (10:09:50 to 10:10:09): Caught seamlessly because the window slides with every event rather than resetting on 10-minute clock boundaries.
  • Episode deduplication and subsequent attacks: in_alert suppresses duplicate alerts while count remains > 10, resets to False as soon as an event of that key observes count <= 10 (or after the key goes idle past W seconds), and fires cleanly on a later attack burst.
  • Equivalent IPv6 representations: 0:0:0:0:0:0:0:1 and ::1 both canonicalize to "::1" via ipaddress.ip_address, preventing an attacker or dual-format logger from double-counting one host.
  • Malformed lines and empty streams: Blank lines, non-IP strings (10.0.0.999), missing src/dst, and unparseable timestamps increment detector.malformed without interrupting detection on surrounding valid lines.
  • Timezone offsets and naive timestamps: +02:00, Z, and timezone-naive ISO strings all convert consistently to UTC Unix seconds.

Common mistakes

  • Forgetting del state.counts[old_value] when a destination's count reaches 0. In Python, Counter({"a": 1}) becomes Counter({"a": 0}) after counts["a"] -= 1, so len(counts) remains 1 forever and causes false alerts on long-expired destinations!
  • Using list.pop(0) instead of collections.deque.popleft(). Removing index 0 of a Python list shifts every remaining element left in O(W) time, quietly reintroducing quadratic slowdowns on busy sources.
  • Using a set instead of a reference Counter. Popping (t=0, d1) and calling active_set.remove(d1) corrupts the count whenever a newer (t=5, d1) is still inside the window.
  • Calling .timestamp() on a timezone-naive datetime. Python interprets naive datetime objects in the machine's local timezone rather than UTC, shifting timestamps when mixed with +00:00 lines or run across servers in different regions.
  • Never evicting idle source keys. Keeping an empty _WindowState for every source IP ever seen leaks gigabytes of RAM on day-long internet border logs.
  • Alerting on every packet above 10 (alert storm) or only once per source forever (blind to repeat attacks). Tracking episode state (in_alert) avoids both extremes.

Alternative approaches

  • Last-seen OrderedDict per key (for distinct-value rules only): Instead of storing every connection in a deque, map dst -> latest_ts inside a per-source OrderedDict, calling move_to_end(dst) on repeats and popping expired dst entries from the front. That shrinks per-source memory from O(events in window) to O(distinct destinations in window), though it cannot evaluate total-event rules (value_field=None), which is why our shared deque + Counter state handles both rule types uniformly.
  • Time-bucketed HyperLogLog sketches (massive approximate scale): A HyperLogLog sketch estimates distinct cardinality in ~1–2 KB of fixed memory with ~2% relative error. Merging 1-minute sketches approximates 10-minute fan-out at petabyte scale, at the cost of slight boundary fuzziness around small thresholds like 10.

Follow-up questions

  • How can the detector stay accurate when log records arrive with minor timestamp jitter? Place a bounded watermark reorder buffer in front of Detector: push incoming events into a min-heap (heapq, keyed by (event.ts, arrival_seq)) while tracking max_ts_seen, and pop-and-process every heap top whose timestamp is <= max_ts_seen - max_lateness (for example, 30 seconds of allowed network jitter). That hands events to Detector in exact timestamp order at the cost of at most 30 seconds of alert latency, with a flush() step at EOF to drain the final 30 seconds.
import heapq


class ReorderBuffer:
    def __init__(self, detector, max_lateness: float = 30.0):
        self.detector = detector
        self.max_lateness = max_lateness
        self.heap = []  # min-heap of (event.ts, seq, event)
        self.seq = 0    # preserves arrival order among equal timestamps
        self.max_ts = None

    def push(self, event):
        heapq.heappush(self.heap, (event.ts, self.seq, event))
        self.seq += 1
        if self.max_ts is None or event.ts > self.max_ts:
            self.max_ts = event.ts
        alerts = []
        watermark = self.max_ts - self.max_lateness
        while self.heap and self.heap[0][0] <= watermark:
            _, _, ready_event = heapq.heappop(self.heap)
            alerts.extend(self.detector.process_event(ready_event))
        return alerts

    def flush(self):
        alerts = []
        while self.heap:
            _, _, ready_event = heapq.heappop(self.heap)
            alerts.extend(self.detector.process_event(ready_event))
        return alerts
  • If log volume exceeds a single host's capacity, how should you shard the workload across machines? Partition the stream by hashing each rule's key_field (hash(src) % num_workers for fan-out; a separate shuffle keyed by dst for fan-in rules), so every event for 192.168.4.12 lands on the same worker in timestamp order with zero cross-worker coordination. Alternatively, if historical logs sit in hourly object-store files (08:00–09:00, 09:00–10:00), you can process each hour in parallel if each worker silently warms up on the preceding 2 * W (20 minutes, 08:40–09:00) before emitting alerts from 09:00 onward: the first 10 minutes (08:40–08:50) makes counts exact for events inside 08:50–09:00 (e_last), and exact counts at e_last guarantee in_alert (True iff count(e_last) > threshold) matches a continuous run at 09:00 (whereas warming up only 08:50–09:00 would miss 6 hosts at 08:46 + 5 hosts at 08:55, leave in_alert = False, and double-fire on 6 more hosts at 09:00).
  • How can you support a connection-flood rule counting total events per source while reusing the same sliding-window engine? Pass WindowRule("conn_flood", key_field="src", threshold=1000, window_seconds=60, value_field=None) into Detector([fan_out_rule(), conn_flood_rule]). Because _apply_rule uses the exact same deque eviction loop and simply branches on len(state.events) when value_field is None vs len(state.counts) when value_field is set, zero window-maintenance code is duplicated and both rules run in a single pass over the log.
  • What architectural changes are needed to run this batch scanner continuously on a live event stream? Detector.process_line already operates event-by-event in O(1) amortized time and bounded O(E_2W) RAM, so wrap one ReorderBuffer(Detector(rules)) consumer per Kafka/Kinesis partition (partitioned by key_field). For production resilience, add periodic state checkpoints (saving (kafka_offset, serialized_states) to RocksDB/S3 so crashes recover mid-window without losing history), attach deterministic idempotency keys (f"{alert.rule}:{alert.key}:{int(alert.end)}") so downstream alert sinks deduplicate replays after a worker restart, and advance idle eviction via periodic wall-clock heartbeats even on low-traffic partitions.

Follow-up questions

Similar questions

More Fireworks interview questions

All 2 Fireworks questions →