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 withZ/z, carry an explicit offset (e.g.,+02:00), or omit a timezone (treat timezone-naive timestamps as UTC).fields(Dict[str, str]): dictionary ofkey=valuepairs after the timestamp. Ignore extra tokens that do not contain=or that have an empty key or value.- Both
srcanddstare 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
Nonewhen a line is blank, lacks a valid leading timestamp, omitssrcordst, or contains an invalid IP address.
Sliding-Window Rules & Alert Semantics
WindowRule(name, key_field, threshold, window_seconds, value_field=None):- Validates
threshold >= 1andwindow_seconds > 0(raisingValueErrorotherwise). - Partitions events by
event.fields[key_field]. When an event arrives at timestampt, the active window is the half-open interval(t - window_seconds, t]: earlier events for that key with timestamp<= t - window_secondshave expired, whereas events strictly greater thant - window_seconds(including timestamp ties att) remain active. - If
value_fieldis provided (e.g.,"dst"), the window count is the number of distinct values ofevent.fields[value_field]among active events for that key. Ifvalue_fieldisNone, the window count is the total number of active events for that key. Events missingkey_field(orvalue_fieldwhen set) do not update counts.
- Validates
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 than10(at least11) distinct destination IPs within600seconds.
- Default horizontal-scan rule (
- One alert per episode (
Detector,detect_attacks,format_alert):Detector(rules=None)defaults to[fan_out_rule()]and counts skipped bad lines inself.malformed.- For each
(rule, key)pair, emitAlert(rule, key, start, end, count)on the exact event that pushes the active count from<= thresholdtothreshold + 1, wherestartis the oldest timestamp still inside the active window,endis the triggering event's timestamp, andcount == threshold + 1. - Suppress duplicate alerts while that key remains above
threshold; re-arm only once a subsequent event for that key observescount <= 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_secondsmust be evicted.detect_attacks(lines, rules=None)streamslinesthroughDetector(rules)and returns all emittedAlertrecords 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
linesincrementally inO(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], keepingdetector.tracked_keys()proportional only to recently active keys. - If an out-of-order event arrives with
event.ts < latest_ts, clamp its effective timestamp tolatest_tsso sliding-window invariants remain monotonic.
Step-by-step walkthrough
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=valuetokens includingsrcanddst. We iterate over lines lazily (Iterable[str]) so a50 GBlog file never has to fit in RAM. - Malformed lines: Skip and count them in
detector.malformedinstead 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 of6destinations at10:09:55plus5destinations at10:10:05. A sliding window ending at timestamptkeeps events strictly newer thant - 600(old_ts > t - 600), so events600seconds apart do not share a window, events599seconds apart do, and multiple connections in the exact same second all count. - Strict threshold (
> 10means11+distinct destinations): Forty connections to the same10servers stay quiet; the11thdistinct destination triggers the alert. - One alert per episode: Emit an alert on the exact event that pushes a source from
<= 10to11, stay silent while that source remains above10, 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
NamedTuplerecords: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)- Streaming log format: Each line starts with an ISO-8601 timestamp followed by
Parse log lines defensively (UTC timestamps and canonical IPs)
Security parsers face three classic pitfalls in real logs:
- Timezone drift: Calling
.timestamp()on a timezone-naive Pythondatetimeinterprets it in the server's local timezone, making mixed naive and+00:00lines jump by hours! Always attachtimezone.utcwhen no offset is present, and normalize trailing"Z"to"+00:00". - Equivalent IP spellings: In IPv6,
0:0:0:0:0:0:0:1and::1are the exact same destination. Comparing raw strings would count them as two distinct hosts; normalizing throughipaddress.ip_address(...)turns both into"::1"and simultaneously rejects invalid IPs like10.0.0.999. - 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)- Timezone drift: Calling
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 generatesHlog lines, rescanning its history takes1 + 2 + ... + H = O(H^2)steps. Even breaking at the 10-minute boundary still repeatsO(W)work per line (W= events inside one 10-minute window, easily tens of thousands for a busy proxy). - Unbounded memory (O(N)): Appending tohistory[src]without evicting old events or idle IPs keeps the entire log in RAM. - Permanent suppression: Storingalerted_ipsin a plainsetsilences a source forever after its first burst, missing a second attack hours later.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
dequeof events plus a Pythonsetof 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 att=70,.10is still inside the window via(t=25, .10)! A reference counter (collections.Countermappingdst -> how many in-window events point to dst) solves this cleanly:- Evict expired events from the left of a
dequewhilefront_ts <= event.ts - W: decrementcounts[old_dst] -= 1, and deleteold_dstfromcountswhen its count hits0. - Append the new event
(event.ts, dst)to the right of thedequeand incrementcounts[dst] += 1. - Read distinct destinations in
O(1)aslen(counts)!
Watch this on the 6 events of Example 1 (
src=192.168.4.12,threshold = 2so3+distinct destinations alert,window = 60safter08: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
dequeonce and popped once, so sliding the window takesO(1)amortized time per event regardless of how many thousands of connections sit inside the 10-minute window!- Evict expired events from the left of a
Generalize into one `WindowRule` configuration for any attack rule
Most sliding-window security rules share the exact same skeleton: "group by
key_field; insidewindow_seconds, alert if total events (value_field=None) or distinct values ofvalue_fieldexceedthreshold." 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.0Bound memory by evicting idle keys from an `OrderedDict`
What if
5,000,000internet scanners each send a single packet at09:00and never appear again? Without key eviction,stateswould hold5,000,000dead_WindowStateobjects forever!Any key whose
last_ts <= event.ts - rule.windowhas zero events left in any future window, so we can forget it completely. By storingkey -> _WindowStateinside anOrderedDict(a dictionary that remembers insertion order and moves any key to the back inO(1)viamove_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 = Trueand cause a duplicate alert? No! BecauseWindowRuleenforcesthreshold >= 1, if that source ever returns later with an empty window, its very first new packet hascurrent_count == 1 <= threshold, which would resetstate.in_alert = Falseanyway!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)Wrap the streaming `Detector` and benchmark the speedup
Detectorholds oneOrderedDictper rule, tracksmalformedandlatecounters, and exposesprocess_linefor live or file-based streaming. If a slightly out-of-order line arrives (event.ts < self.latest), clamping its timestamp toself.latestpreserves 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 (100events/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 sDoubling the log size doubles our detector's runtime (
2xlinear scaling, with ~85% of time spent simply parsing strings) while quadrupling the naive rescan (4xquadratic blowup, already60xslower at just40,000lines).Design targeted test cases for every boundary
A thorough test suite targets every off-by-one and state-management edge case:
- Threshold boundaries:
10distinct destinations emit[]; adding an11themits oneAlertwithcount = 11and exact[start, end]timestamps. - Repeated destinations:
40connections cycling across10hosts emit[], catching implementations that accidentally count total packets instead of distinct IPs. - Exact window edge and fixed-bucket straddle:
10hosts att = 0plus1new host att = 600emit[](600 <= 600expired), whereast = 599fires;6hosts att = 590..595plus5hosts att = 605..609straddle a 10-minute clock boundary and fire cleanly. - Episode reset and source isolation:
15destinations in one burst fire once, stay silent at12..15, reset after dropping<= 10, and fire again on a second burst att = 700..709, while an interleaved second source IP never pollutes the first. - Malformed inputs & IPv6 normalization: blank lines, invalid IPs (
999.1.1.1), missingdst, and0:0:0:0:0:0:0:1vs::1. - Multi-rule reuse, randomized differential testing, and memory bounds: cross-checking
120random logs against a simpleO(N^2)reference oracle, verifyingtracked_keys()drops1,000idle IPs once time advances past600s, and timing20,000dense lines.
- Threshold boundaries:
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 itsLcharacters once. Then, for each of theRrules, every event is appended to its key'sdequeat most once and popped at most once across the entire run, and every key state inserted intoOrderedDictis moved/evicted inO(1)amortized hash-map operations. Even if one quiet-then-active line pops500expired events at once, those500pops were already paid for when the500events arrived (amortized analysis, meaning the average cost per operation over any sequence ofNevents has a strict constant upper bound). - Space:
O(R * E_2W)working memory (independent of total log sizeN). The inputIterable[str]is streamed one line at a time._drop_idledeletes any key whose newest event is older thannow - W, and a surviving active key (whose newest event is afternow - W) can hold un-popped events in itsdequedating back at most tonow - 2 * W. Thus memory tracks active traffic volume over2 * W, never total file size.
Edge cases
- Exact threshold (
10vs11): Ten distinct destinations stay quiet (count <= threshold); the11themits a singleAlertwithcount = 11. - Repeated connections to the same destinations: Forty hits to
10destinations incrementcounts[dst]values without increasinglen(counts). - Exact window boundary (
600svs599s) and timestamp ties: Because the active window is(t - 600, t],state.events[0][0] <= t - 600evicts events600sold while keeping events599sold and keeping simultaneous events att. - Burst straddling a round clock mark (
10:09:50to10: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_alertsuppresses duplicate alerts whilecountremains> 10, resets toFalseas soon as an event of that key observescount <= 10(or after the key goes idle pastWseconds), and fires cleanly on a later attack burst. - Equivalent IPv6 representations:
0:0:0:0:0:0:0:1and::1both canonicalize to"::1"viaipaddress.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), missingsrc/dst, and unparseable timestamps incrementdetector.malformedwithout 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 reaches0. In Python,Counter({"a": 1})becomesCounter({"a": 0})aftercounts["a"] -= 1, solen(counts)remains1forever and causes false alerts on long-expired destinations! - Using
list.pop(0)instead ofcollections.deque.popleft(). Removing index0of a Pythonlistshifts every remaining element left inO(W)time, quietly reintroducing quadratic slowdowns on busy sources. - Using a
setinstead of a referenceCounter. Popping(t=0, d1)and callingactive_set.remove(d1)corrupts the count whenever a newer(t=5, d1)is still inside the window. - Calling
.timestamp()on a timezone-naivedatetime. Python interprets naivedatetimeobjects in the machine's local timezone rather than UTC, shifting timestamps when mixed with+00:00lines or run across servers in different regions. - Never evicting idle source keys. Keeping an empty
_WindowStatefor 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
OrderedDictper key (for distinct-value rules only): Instead of storing every connection in adeque, mapdst -> latest_tsinside a per-sourceOrderedDict, callingmove_to_end(dst)on repeats and popping expireddstentries from the front. That shrinks per-source memory fromO(events in window)toO(distinct destinations in window), though it cannot evaluate total-event rules (value_field=None), which is why our shareddeque + Counterstate handles both rule types uniformly. - Time-bucketed HyperLogLog sketches (massive approximate scale): A HyperLogLog sketch estimates distinct cardinality in ~
1–2 KBof fixed memory with ~2%relative error. Merging 1-minute sketches approximates10-minute fan-out at petabyte scale, at the cost of slight boundary fuzziness around small thresholds like10.
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 trackingmax_ts_seen, and pop-and-process every heap top whose timestamp is<= max_ts_seen - max_lateness(for example,30seconds of allowed network jitter). That hands events toDetectorin exact timestamp order at the cost of at most30seconds of alert latency, with aflush()step at EOF to drain the final30seconds.
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_workersfor fan-out; a separate shuffle keyed bydstfor fan-in rules), so every event for192.168.4.12lands 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 preceding2 * W(20minutes,08:40–09:00) before emitting alerts from09:00onward: the first10minutes (08:40–08:50) makes counts exact for events inside08:50–09:00(e_last), and exact counts ate_lastguaranteein_alert(Trueiffcount(e_last) > threshold) matches a continuous run at09:00(whereas warming up only08:50–09:00would miss6hosts at08:46+5hosts at08:55, leavein_alert = False, and double-fire on6more hosts at09: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)intoDetector([fan_out_rule(), conn_flood_rule]). Because_apply_ruleuses the exact samedequeeviction loop and simply branches onlen(state.events)whenvalue_field is Nonevslen(state.counts)whenvalue_fieldis 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_linealready operates event-by-event inO(1)amortized time and boundedO(E_2W)RAM, so wrap oneReorderBuffer(Detector(rules))consumer per Kafka/Kinesis partition (partitioned bykey_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
- How can the detector stay accurate when log records arrive with minor timestamp jitter?
- If log volume exceeds a single host's capacity, how should you shard the workload across machines?
- How can you support a connection-flood rule counting total events per source while reusing the same sliding-window engine?
- What architectural changes are needed to run this batch scanner continuously on a live event stream?
Similar questions
- Mutual-Connection Friend Suggestions and Ranking Evaluation
- 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
- Library Hold-Queue and Loan Reminder Notification Manager