KatInterview

Streaming Keyword-Set Matcher for Interleaved Rules and Events

System DesignModel answer
HardModel answerSystem Designinverted-indexstream-processingscaling

Last 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:

  1. Each new watch phrase gets the next integer ID, starting at 1. Emit an acknowledgment of the form ACK: <phrase>; ID=<n>.
  2. 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 (fail does not match failed).
  • 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:

  1. Implement the processor and state its complexity.
  2. How would you change the design to handle a very large volume of data?
  3. 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.