Streaming Keyword-Set Matcher for Interleaved Rules and Events
System DesignModel answerLast updated
Build a processor for a stream of subscriptions and log events that assigns IDs, acknowledges each subscription, tags matching events, and scales to heavy traffic with deletions.
You receive a single ordered stream of text lines. Each line starts with one of two prefixes:
Q:registers a watch phrase (a set of words to look for).L:is a log line to be checked against the watch phrases registered so far.
Design and implement a processor that does the following:
- Each new watch phrase gets the next integer ID, starting at 1. Emit an acknowledgment of the form
ACK: <phrase>; ID=<n>. - For each log line, find all watch phrases that match it and emit
M: <log text>; Q=<id1>,<id2>,...with IDs in ascending order. If nothing matches, emit nothing.
Matching rules:
- A phrase is a set of words. A log matches if it contains every word of the phrase, in any order.
- Comparison is case-insensitive and on whole words only (
faildoes not matchfailed). - A phrase applies only to log lines that appear after it in the stream.
- Output echoes the original text, not a normalized version.
Example:
Q: database -> ACK: database; ID=1
Q: Stacktrace -> ACK: Stacktrace; ID=2
Q: loading failed -> ACK: loading failed; ID=3
L: Database service started -> M: Database service started; Q=1
Q: snapshot loading -> ACK: snapshot loading; ID=4
Q: fail -> ACK: fail; ID=5
L: Started processing events -> (nothing)
L: Loading main DB snapshot -> M: Loading main DB snapshot; Q=4
L: Loading snapshot failed no stacktrace -> M: ...; Q=2,3,4
Discuss and answer:
- Implement the processor and state its complexity.
- How would you change the design to handle a very large volume of data?
- How would you support deleting a phrase in your implementation, and which inefficiencies would you need to fix?
State any assumptions you make (duplicate phrases, empty phrases, malformed lines).
Hints
Hint 1
Checking every phrase against every log line is too slow. Think about indexing from words to the phrases that contain them.
Hint 2
For each log line, count how many distinct words of each candidate phrase are present, and compare that count with the phrase's number of distinct words.
Hint 3
For scale, notice that phrases are few and logs are many: replicate the phrase index and partition the logs. For deletion, think about removing postings eagerly versus tombstoning, and cleaning up empty posting sets.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Clarify the contract
- Words are split on whitespace and lowercased. A phrase is a set of distinct words, so repeated words are irrelevant.
- A log matches a phrase if the phrase's set is a subset of the log's word set. Whole tokens only.
- The stream is ordered, so a phrase never matches earlier logs.
- Assumptions I would confirm: a repeated phrase (same word set) reuses its ID; an empty phrase is rejected (otherwise it would match everything); malformed lines are skipped or reported.
Approach: inverted index with hit counting
The naive method tests every phrase against every log, costing O(#phrases x phrase length) per log. Instead:
index: word -> set of phrase IDsneed[id]: number of distinct words in the phrase- For a log, take its distinct lowercase words. For each word, increment
hits[id]for each ID in that word's posting set. - A phrase matches exactly when
hits[id] == need[id].
Correctness: each distinct log word is visited once and each ID appears at most once per posting set, so hits[id] equals the number of phrase words present in the log. It equals need[id] iff all of them are present. Phrases enter the index only when read, which gives the "later logs only" rule for free.
Complexity:
- Add phrase with k words: O(k).
- Process log with w words: O(w + P + m log m), where P is the total size of the posting lists touched and m is the number of matches (sorting). It does not depend on the total number of phrases, only on how common the log's words are.
- Space: O(total words across phrases).
from collections import defaultdict
class Processor:
def __init__(self):
self.next_id = 1
self.index = defaultdict(set)
self.need = {}
self.key_to_id = {}
self.id_to_key = {}
@staticmethod
def _words(s):
return frozenset(s.lower().split())
def add(self, text):
key = self._words(text)
if not key:
return "ERR: empty query"
qid = self.key_to_id.get(key)
if qid is None:
qid = self.next_id
self.next_id += 1
self.key_to_id[key] = qid
self.id_to_key[qid] = key
self.need[qid] = len(key)
for w in key:
self.index[w].add(qid)
return f"ACK: {text}; ID={qid}"
def match(self, text):
hits = defaultdict(int)
for w in self._words(text):
for qid in self.index.get(w, ()):
hits[qid] += 1
return sorted(q for q, c in hits.items() if c == self.need[q])
def process(self, lines):
for raw in lines:
line = raw.strip()
if line.startswith("Q:"):
yield self.add(line[2:].strip())
elif line.startswith("L:"):
text = line[2:].strip()
ids = self.match(text)
if ids:
yield f"M: {text}; Q={','.join(map(str, ids))}"
Using a generator keeps memory proportional to the phrase state, not the stream length.
Scaling to very large volume
The workload is typically few phrases, enormous numbers of logs.
- Stream, do not buffer. Consume from a durable log (for example a partitioned message queue) and emit results incrementally.
- Partition logs, replicate phrases. The index is small, so every worker holds a full copy. Logs are sharded by host, tenant or round-robin. Throughput scales roughly linearly with workers.
- Preserve "only later logs" semantics. Publish phrase additions and deletions on a control stream with sequence numbers. Each worker applies a change when its log position passes that sequence number (or tag each log with the latest phrase version it must see). Without this, workers could disagree about which phrases existed at a given log.
- Shard the index if phrases are too many (tens of millions). Partition phrases by ID or by rarest word; every log fans out to all shards, and results are merged and sorted.
- Reduce per-log cost. Skip very common words by indexing each phrase under its rarest word only (then verify the full subset), tokenize once, and use compact integer word IDs and bitsets or sorted arrays for postings. Batch logs to amortize overhead.
- Ordering of output: if the output must follow input order, keep a per-partition order or attach sequence numbers and merge downstream.
Supporting deletion
Eager removal (shown in the code idea below) removes the ID from each word's posting set, the need entry, and the dedup maps:
def delete(self, qid):
key = self.id_to_key.pop(qid, None)
if key is None:
return False
del self.key_to_id[key]
del self.need[qid]
for w in key:
self.index[w].discard(qid)
if not self.index[w]:
del self.index[w]
return True
Cost is O(k) with hash sets. Inefficiencies to address:
- Posting lists as sorted arrays: deletion is O(n) per list. Use tombstones (a
deletedflag checked at match time) and compact periodically in the background. - Dead keys: empty posting sets must be dropped, or the index grows without bound.
- ID reuse: never reuse IDs, or old acknowledgments become ambiguous. Keep the counter monotonic.
- Shared phrases: if duplicates share one ID, you need reference counts or per-subscriber IDs so one deletion does not remove another user's phrase.
- Distributed case: deletion is a control-stream event with a sequence number, applied consistently across workers, so a log is never matched against a phrase that was deleted before it.
- In-flight logs: with tombstones, matching must check liveness at the log's sequence position.
Common mistakes
- Substring matching instead of whole-word matching.
- Counting duplicate words twice, which breaks the
hits == needcheck. - Letting an empty phrase match everything.
- Matching new phrases against earlier logs.
- Forgetting that the cost of scanning a very common word's posting list dominates, and not mentioning rarest-word indexing.
- Replicating logs instead of phrases when scaling.
Validation
Property-test against the naive subset check on random streams, replay production-like traffic to measure p99 latency per log, and test deletion by comparing the index against a rebuild from the live phrase set.