Pluggable Multi-Tenant Pipeline for Event Enrichment and Suppression
Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen
Problem Statement
Security monitoring systems ingest continuous telemetry records across many customer organizations (tenants). Before promoting an incoming record to an analyst alert, an in-memory processor runs two sequential phases:
- Contextual enrichment: Pluggable enrichers inspect the record and populate additional fields inside its
attributesdictionary in place. - Alert suppression: Pluggable suppression rules inspect the enriched record and decide whether it represents benign noise that should be discarded.
Plugins may apply across the entire platform (tenant_id=None) or only to a single organization (tenant_id="<id>"), and callers may register new plugins dynamically between events.
Implement the following classes and methods:
Event: A data container with fieldstenant_id: str,event_type: str,timestamp: int, andattributes: Dict[str, Any](defaulting to a fresh{}per instance when omitted).Enricher: Base interface declaringenrich(self, event: Event) -> None. Any duck-typed object with a callableenrichattribute must be accepted even if it does not subclassEnricher.SuppressionRule: Base interface declaringshould_suppress(self, event: Event) -> bool. Any duck-typed object with a callableshould_suppressattribute must be accepted even if it does not subclassSuppressionRule.SecurityPipeline:register_enricher(self, enricher: Enricher, tenant_id: Optional[str] = None) -> None: Validates thatenricherexposes a callableenrichmethod (raisingTypeErrorimmediately otherwise). Registers globally whentenant_id is None, or exclusively fortenant_idfor any string value (including"").register_suppression_rule(self, rule: SuppressionRule, tenant_id: Optional[str] = None) -> None: Validates thatruleexposes a callableshould_suppressmethod (raisingTypeErrorimmediately otherwise). Registers globally whentenant_id is None, or exclusively fortenant_idotherwise.process(self, event: Event) -> Optional[Event]:- Enrichment phase: Invoke all global enrichers in registration order, then all enrichers registered for
event.tenant_idin registration order. Every applicable enricher finishes before any suppression rule is called. - Suppression phase: Evaluate all global suppression rules in registration order, then all rules registered for
event.tenant_idin registration order. On the first rule that returnsTrue, immediately stop evaluating remaining rules and returnNone. If no rule returnsTrue, return the sameeventinstance. - Fault isolation and fail-open behavior:
- If an enricher raises an
Exception, append{"stage": "enrich", "plugin": <class name>, "error": "<ExceptionType>: <message>"}toevent.attributes["pipeline_errors"]and continue running subsequent plugins. - If a suppression rule raises an
Exceptionor returns anything other than abool(isinstance(result, bool)— note that integers such as1are notbool), record an entry under"stage": "suppress"inevent.attributes["pipeline_errors"](recordingTypeErrorfor non-boolean return values), treat that rule as non-matching (fail open), and continue checking remaining rules. - Do not add the
"pipeline_errors"key toevent.attributeswhen zero errors occur.
- If an enricher raises an
- Enrichment phase: Invoke all global enrichers in registration order, then all enrichers registered for
Examples
Example 1
class ServiceAccountEnricher:
def enrich(self, event: Event) -> None:
actor = str(event.attributes.get("actor", ""))
event.attributes["is_bot"] = actor.startswith("svc-")
class BotTrafficSuppressionRule:
def should_suppress(self, event: Event) -> bool:
return event.attributes.get("is_bot") is True
pipeline = SecurityPipeline()
pipeline.register_enricher(ServiceAccountEnricher()) # global
pipeline.register_suppression_rule(BotTrafficSuppressionRule(), tenant_id="org_north")
ev_north = Event(
tenant_id="org_north",
event_type="api_call",
timestamp=1700000100,
attributes={"actor": "svc-backup"},
)
out_north = pipeline.process(ev_north)
# out_north -> None
ev_south = Event(
tenant_id="org_south",
event_type="api_call",
timestamp=1700000105,
attributes={"actor": "svc-backup"},
)
out_south = pipeline.process(ev_south)
# out_south -> ev_south, with attributes == {"actor": "svc-backup", "is_bot": True}
Walk-through: Both events run through the global ServiceAccountEnricher, setting "is_bot": True in place. Next, "org_north" has BotTrafficSuppressionRule registered, which sees "is_bot" is True, short-circuits, and causes process(ev_north) to return None. Because "org_south" has no suppression rules registered, process(ev_south) returns ev_south with its enriched attributes and no "pipeline_errors" key.
Example 2
class FailingGeoEnricher:
def enrich(self, event: Event) -> None:
raise RuntimeError("geoip timeout")
class EnvTagEnricher:
def enrich(self, event: Event) -> None:
event.attributes["env"] = "staging"
class InvalidReturnRule:
def should_suppress(self, event: Event):
return "drop" # invalid: must be a bool
pipeline = SecurityPipeline()
pipeline.register_enricher(FailingGeoEnricher())
pipeline.register_enricher(EnvTagEnricher(), tenant_id="org_west")
pipeline.register_suppression_rule(InvalidReturnRule())
ev = Event(
tenant_id="org_west",
event_type="token_create",
timestamp=1700000200,
attributes={"user": "dana"},
)
out = pipeline.process(ev)
# out -> ev (not suppressed)
# ev.attributes["env"] == "staging"
# len(ev.attributes["pipeline_errors"]) == 2
Walk-through: FailingGeoEnricher raises RuntimeError, which is recorded under "stage": "enrich" while allowing EnvTagEnricher to still tag "env": "staging". During suppression, InvalidReturnRule returns "drop" instead of a bool; the pipeline logs a TypeError under "stage": "suppress", fails open rather than dropping a potentially real alert, and returns ev.
Constraints
- Only
tenant_id is Nonedenotes global scope; any string (including"") targets that exacttenant_id. - Processing an event for one tenant should run in
O(E + R)pipeline overhead (whereEandRare the numbers of enrichers and rules applicable to that event), independent of how many other tenants have plugins registered. - Standard
Exceptionsubclasses raised by plugins are caught and logged inevent.attributes["pipeline_errors"];KeyboardInterruptandSystemExitmust not be swallowed.
Step-by-step walkthrough
Restate the problem and clarify edge-case rules
Security platforms receive a continuous stream of raw activity logs (
Eventobjects) from many customer organizations (tenants). Before turning an event into a security alert, our pipeline runs two distinct stages:- Enrichment: Plugins called enrichers add useful context into
event.attributes(for example checking whetheractorbelongs to an automatedsvc-service account). - Suppression: Plugins called suppression rules inspect the enriched event and return
Trueif it is a known false positive that should be dropped (processreturnsNone), orFalseif it should keep going (processreturns theEvent).
Both enrichers and rules can be registered globally (
tenant_id=None, applying to every organization) or per-tenant (tenant_id="org_north", applying only to that organization). Let's state the exact edge-case contracts before writing code:- Duck typing for plugins: In Python, duck typing means accepting any object that provides the required method (
enrichorshould_suppress), even if it does not inherit fromEnricherorSuppressionRule(just like the prompt's example classes!). Passing an object without that callable method raisesTypeErrorright at registration time. - Only
Nonemeans global: Even an empty string""is treated as a specific tenant ID, not global. - Strict stage ordering: All applicable enrichers (global in registration order, then tenant in registration order) finish before any suppression rule runs. Then global rules run, followed by tenant rules, stopping immediately (short-circuiting) on the first
True. - Fault isolation & failing open: If an enricher or rule raises an
Exception, we append{"stage": ..., "plugin": ..., "error": ...}toevent.attributes["pipeline_errors"](creating that key only when an error actually happens) and keep going. If a suppression rule crashes or returns a non-bool(like"yes"or1), we fail open — meaning we treat it as "do not suppress" so a buggy filter can never silently hide a real attack.
- Enrichment: Plugins called enrichers add useful context into
Model the event and plugin contracts
Let's start with
Eventand the two plugin base classes. Noticefield(default_factory=dict)onEvent.attributes: if everyEventshared a single default dictionary{}in memory, mutating one event's attributes would corrupt every other event! Callingdictper instance guarantees every event owns a fresh dictionary.from typing import Any, Dict from dataclasses import dataclass, field @dataclass class Event: tenant_id: str event_type: str timestamp: int # Use default_factory=dict so every Event instance gets its own fresh dict. attributes: Dict[str, Any] = field(default_factory=dict) class Enricher: """Plugin that adds context to an event. Any object with an `enrich` method is accepted.""" def enrich(self, event: Event) -> None: raise NotImplementedError class SuppressionRule: """Plugin that drops known-benign events. Any object with a `should_suppress` method is accepted.""" def should_suppress(self, event: Event) -> bool: raise NotImplementedErrorKey idea: separate global lists and per-tenant dicts
How should
SecurityPipelinestore registered plugins? Imagine 10,000 customer tenants with 5 rules each (50,000rules total). If we stored(tenant_id, rule)pairs in one giant list, every single event would scan all50,000entries just to find the handful that apply to it!Instead, we store one list for global plugins plus one dictionary mapping
tenant_id -> listfor tenant-specific plugins:Registry inside SecurityPipeline: _global_enrichers : [GlobalEnricher1, GlobalEnricher2] _tenant_enrichers : { "org_north": [OrgNorthEnricher1], "org_south": [OrgSouthEnricher1, OrgSouthEnricher2], } When an event arrives for "org_north": applicable = _global_enrichers + _tenant_enrichers.get("org_north", []) = [GlobalEnricher1, GlobalEnricher2, OrgNorthEnricher1]This layout gives us three wins at once:
- Fast
O(1)dictionary lookup: Processing an event for"org_north"never touches"org_south"or the other 9,998 tenants. - Exact execution order for free: Python lists preserve insertion order, and concatenating
global_plugins + tenant_pluginsputs every global plugin ahead of every tenant plugin. - Safe per-event snapshot: Using
+allocates a brand-new list for the current event. If another caller registers a new plugin midway throughprocess(event), the active loop finishes cleanly on its snapshot withoutRuntimeErroror half-applied rules.
- Fast
Validate and register plugins
Both registration methods validate the plugin up front using
callable(getattr(plugin, method_name, None))and route it usingif tenant_id is None:. Be careful not to writeif not tenant_id:— in Pythonnot ""isTrue, which would accidentally turntenant_id=""into a global plugin!from typing import Any, Dict, List, Optional class SecurityPipeline: """In-memory pipeline: enrich every event, then drop it if a suppression rule matches.""" def __init__(self) -> None: # _global_enrichers: [enricher, ...] run for every event in registration order. self._global_enrichers: List[Any] = [] # _tenant_enrichers: {tenant_id: [enricher, ...]} run after global enrichers for that tenant. self._tenant_enrichers: Dict[str, List[Any]] = {} # _global_rules: [rule, ...] evaluated for every event in registration order. self._global_rules: List[Any] = [] # _tenant_rules: {tenant_id: [rule, ...]} evaluated after global rules for that tenant. self._tenant_rules: Dict[str, List[Any]] = {} def register_enricher(self, enricher: Enricher, tenant_id: Optional[str] = None) -> None: # Check duck-typed method presence up front so bad registrations fail immediately. if not callable(getattr(enricher, "enrich", None)): raise TypeError(f"{type(enricher).__name__} has no enrich(event) method") # Check `is None` explicitly because "" (empty string) is a valid tenant_id. if tenant_id is None: self._global_enrichers.append(enricher) else: self._tenant_enrichers.setdefault(tenant_id, []).append(enricher) def register_suppression_rule(self, rule: SuppressionRule, tenant_id: Optional[str] = None) -> None: if not callable(getattr(rule, "should_suppress", None)): raise TypeError(f"{type(rule).__name__} has no should_suppress(event) method") if tenant_id is None: self._global_rules.append(rule) else: self._tenant_rules.setdefault(tenant_id, []).append(rule) def _plugins_for( self, global_plugins: List[Any], by_tenant: Dict[str, List[Any]], tenant_id: str, ) -> List[Any]: """Return global plugins followed by this tenant's plugins as a fresh snapshot list.""" tenant_plugins = by_tenant.get(tenant_id, []) return global_plugins + tenant_pluginsPhase 1: Run enrichers with isolated error capture
Inside
process(event), each enricher call is wrapped in its owntry ... except Exceptionblock inside theforloop. If we placedtryoutside the loop, the first broken enricher would skip every healthy enricher registered after it!Two important Python details here:
- Catch
Exception, not bareexcept:orBaseException: System signals likeKeyboardInterruptandSystemExitinherit fromBaseExceptionand must still be allowed to stop the process cleanly. - Create
pipeline_errorslazily withsetdefault: When everything succeeds,event.attributesstays clean with no"pipeline_errors": []clutter, matching the prompt's expected output. And storing strings ({"stage", "plugin", "error"}) rather than rawExceptionobjects keeps the event JSON-serializable.
def _record_error(event: Event, stage: str, plugin: Any, exc: Exception) -> None: """Append a serializable error entry to event.attributes['pipeline_errors'].""" # Create 'pipeline_errors' lazily so clean events never get an empty error key. # Each entry has shape: {"stage": "enrich"|"suppress", "plugin": str, "error": str}. errors = event.attributes.setdefault("pipeline_errors", []) errors.append({ "stage": stage, "plugin": type(plugin).__name__, "error": f"{type(exc).__name__}: {exc}", })- Catch
Phase 2: Evaluate suppression rules with short-circuiting and fail-open safety
Once every applicable enricher has finished, we loop through
rules(global first, then tenant):- If
rule.should_suppress(event)returnsTrue, we immediatelyreturn None— later rules are never called (short-circuit evaluation). - What if a buggy rule returns
"yes",1, or a dictionary instead ofTrue/False? In Python,if should_drop:treats any non-empty string or dict as truthy and would drop every alert! Checkingif not isinstance(should_drop, bool):catches non-booleans (note that in Pythonisinstance(1, bool)isFalse, whileisinstance(True, bool)isTrue), logs the error under"suppress", andcontinues to the next rule (failing open).
def run_suppression_phase(event: Event, rules: List[Any]) -> Optional[Event]: for rule in rules: try: should_drop = rule.should_suppress(event) if not isinstance(should_drop, bool): raise TypeError(f"should_suppress returned {type(should_drop)!r}, expected bool") except Exception as exc: # Fail open: a broken rule must never silently hide a real security alert. _record_error(event, "suppress", rule, exc) continue if should_drop: return None return event- If
Walk through Sample 1 and Sample 2
First, trace Example 1, where
ServiceAccountEnricheris registered globally andBotTrafficSuppressionRuleis registered only for"org_north":ev_north: tenant_id="org_north", attributes={"actor": "svc-backup"} 1. Snapshot: enrichers = [ServiceAccountEnricher] + [] rules = [] + [BotTrafficSuppressionRule] 2. Phase 1 (Enrich): ServiceAccountEnricher sets attributes["is_bot"] = True 3. Phase 2 (Suppress): BotTrafficSuppressionRule reads is_bot == True -> returns True Short-circuit! process(ev_north) -> None ev_south: tenant_id="org_south", attributes={"actor": "svc-backup"} 1. Snapshot: enrichers = [ServiceAccountEnricher] + [] rules = [] + [] ("org_south" has no tenant rules) 2. Phase 1 (Enrich): ServiceAccountEnricher sets attributes["is_bot"] = True 3. Phase 2 (Suppress): 0 rules to run -> process(ev_south) -> ev_south attributes == {"actor": "svc-backup", "is_bot": True}Next, trace Example 2 on
ev(tenant_id="org_west"):FailingGeoEnricherraisesRuntimeError("geoip timeout"),_record_errorappends{"stage": "enrich", "plugin": "FailingGeoEnricher", "error": "RuntimeError: geoip timeout"}, and"org_west"'sEnvTagEnricherstill runs and sets"env": "staging". ThenInvalidReturnRulereturns"drop", triggering aTypeErrorrecorded under"stage": "suppress", failing open soprocess(ev)returnsev.Complete solution
from typing import Any, Dict, List, Optional from dataclasses import dataclass, field @dataclass class Event: tenant_id: str event_type: str timestamp: int # Use default_factory=dict so every Event instance gets its own fresh dict. attributes: Dict[str, Any] = field(default_factory=dict) class Enricher: """Plugin that adds context to an event. Any object with an `enrich` method is accepted.""" def enrich(self, event: Event) -> None: raise NotImplementedError class SuppressionRule: """Plugin that drops known-benign events. Any object with a `should_suppress` method is accepted.""" def should_suppress(self, event: Event) -> bool: raise NotImplementedError def _record_error(event: Event, stage: str, plugin: Any, exc: Exception) -> None: """Append a serializable error entry to event.attributes['pipeline_errors'].""" # Create 'pipeline_errors' lazily so clean events never get an empty error key. # Each entry has shape: {"stage": "enrich"|"suppress", "plugin": str, "error": str}. errors = event.attributes.setdefault("pipeline_errors", []) errors.append({ "stage": stage, "plugin": type(plugin).__name__, "error": f"{type(exc).__name__}: {exc}", }) class SecurityPipeline: """In-memory pipeline: enrich every event, then drop it if a suppression rule matches.""" def __init__(self) -> None: # _global_enrichers: [enricher, ...] run for every event in registration order. self._global_enrichers: List[Any] = [] # _tenant_enrichers: {tenant_id: [enricher, ...]} run after global enrichers for that tenant. self._tenant_enrichers: Dict[str, List[Any]] = {} # _global_rules: [rule, ...] evaluated for every event in registration order. self._global_rules: List[Any] = [] # _tenant_rules: {tenant_id: [rule, ...]} evaluated after global rules for that tenant. self._tenant_rules: Dict[str, List[Any]] = {} def register_enricher(self, enricher: Enricher, tenant_id: Optional[str] = None) -> None: # Check duck-typed method presence up front so bad registrations fail immediately. if not callable(getattr(enricher, "enrich", None)): raise TypeError(f"{type(enricher).__name__} has no enrich(event) method") # Check `is None` explicitly because "" (empty string) is a valid tenant_id. if tenant_id is None: self._global_enrichers.append(enricher) else: self._tenant_enrichers.setdefault(tenant_id, []).append(enricher) def register_suppression_rule(self, rule: SuppressionRule, tenant_id: Optional[str] = None) -> None: if not callable(getattr(rule, "should_suppress", None)): raise TypeError(f"{type(rule).__name__} has no should_suppress(event) method") if tenant_id is None: self._global_rules.append(rule) else: self._tenant_rules.setdefault(tenant_id, []).append(rule) def _plugins_for( self, global_plugins: List[Any], by_tenant: Dict[str, List[Any]], tenant_id: str, ) -> List[Any]: """Return global plugins followed by this tenant's plugins as a fresh snapshot list.""" tenant_plugins = by_tenant.get(tenant_id, []) return global_plugins + tenant_plugins def process(self, event: Event) -> Optional[Event]: # Snapshot both plugin lists up front so registrations during processing # only affect subsequent events and never mutate a list mid-iteration. enrichers = self._plugins_for(self._global_enrichers, self._tenant_enrichers, event.tenant_id) rules = self._plugins_for(self._global_rules, self._tenant_rules, event.tenant_id) # Phase 1: Run all global enrichers, then tenant enrichers, before any rule checks. for enricher in enrichers: try: enricher.enrich(event) except Exception as exc: # Isolate plugin failures inside the loop so remaining enrichers still run. _record_error(event, "enrich", enricher, exc) # Phase 2: Evaluate global rules, then tenant rules; short-circuit on the first True. for rule in rules: try: should_drop = rule.should_suppress(event) # Require an actual Python bool so truthy values like "yes" or 1 cannot # accidentally suppress security events. Notice isinstance(1, bool) is False. if not isinstance(should_drop, bool): raise TypeError(f"should_suppress returned {type(should_drop)!r}, expected bool") except Exception as exc: # Fail open: a broken rule must never silently hide a real security alert. _record_error(event, "suppress", rule, exc) continue if should_drop: return None return event✅ Submit now — all tests should pass.
Intuition & how it works
Think of SecurityPipeline like a shared office-building mailroom serving dozens of companies (tenants). Every incoming package (Event) goes through two stations in strict order: first labelers (Enrichers) attach sticky notes with helpful context (building-wide scanners first, then that specific company's mail clerk), and second inspectors (SuppressionRules) check whether the package is harmless junk mail (building-wide rules first, then that company's rules). As soon as one inspector says "drop it" (True), the package is recycled immediately (return None); if no inspector drops it, the labeled package reaches the security desk (return event).
Why do naive implementations break? Putting all tenants' plugins into one flat list forces every event to check thousands of unrelated tenant rules, and running plugins in raw registration order lets a suppression rule check for a sticky note before a later enricher has attached it. Worse, putting a single try/except around the whole loop skips healthy plugins whenever one third-party plugin throws an error, and letting a broken suppression rule drop events would silently blind analysts to real attacks.
Walk through a concrete 2-event trace where ServiceAccountEnricher is global and BotTrafficSuppressionRule is registered only for "org_north":
ev_north(tenant_id="org_north",actor="svc-backup"): Lookup grabs[ServiceAccountEnricher]for enrichment and[BotTrafficSuppressionRule]for suppression. Phase 1 setsattributes["is_bot"] = True. Phase 2 runsBotTrafficSuppressionRule, getsTrue, short-circuits, and returnsNone.ev_south(tenant_id="org_south",actor="svc-backup"): Lookup grabs[ServiceAccountEnricher]and[]("org_south"has no rules). Phase 1 setsattributes["is_bot"] = True. Phase 2 has zero rules to run and returnsev_southwith its enriched attributes intact.
Complexity
Let N be the total number of registered plugins across all tenants, E be the number of enrichers applicable to the current event (len(global_enrichers) + len(tenant_enrichers[tenant_id])), and R be the number of suppression rules applicable to the current event (len(global_rules) + len(tenant_rules[tenant_id])).
register_enricher/register_suppression_rule—O(1)average time: Each call performs onegetattrcheck, at most one hash-table dictionary lookup (setdefault), and one amortizedO(1)listappend.process(event)—O(E + R)pipeline overhead (plus each invoked plugin's own runtime): Dictionary lookup byevent.tenant_idtakesO(1)average time regardless of how many thousands of other tenants exist, copying the two snapshot lists copiesE + Robject references, Phase 1 calls each of theEenrichers once, and Phase 2 calls at mostRrules (fewer whenever an early rule returnsTrue).- Space —
O(N)persistent registry space, plusO(E + R)temporary per-event space: The four registry containers store each registered plugin reference once (O(N)),processallocates two short-lived snapshot lists of total lengthE + R, andpipeline_errorsgrows only with the number of failed plugins (O(failures)).
Edge cases
- Tenant with zero tenant-specific plugins:
by_tenant.get(tenant_id, [])returns[]without mutating the dictionary, so only global plugins run. - Empty string
tenant_id="": Treated as a distinct tenant rather than global because registration checksif tenant_id is None:instead ofif not tenant_id:. - Clean run with zero plugin errors:
"pipeline_errors"is never added toevent.attributesbecausesetdefaultruns only inside_record_error. - Broken rule or non-boolean return (
1,"yes",None,numpy.bool_): Rejected byisinstance(should_drop, bool), recorded under"stage": "suppress", and skipped (fail open) so subsequent rules still evaluate and real alerts are never silently dropped. - Enricher mutates one key then raises an exception: Earlier in-place writes on
event.attributesremain visible, the error is logged inpipeline_errors, and the next enricher still executes. - Suppressed event mutated in place: Enrichment runs before suppression, so the caller's
eventobject retains enriched attributes (and anypipeline_errors) even whenprocess(event)returnsNone. - Plugin registered mid-flight during
process(event):_plugins_forcreates a new snapshot list via+at the start ofprocess, so active loops never crash or see partial updates; the new plugin takes effect on the next event.
Common mistakes
- Wrapping the entire
for enricher in enrichers:loop in a singletry/except: One failing enricher aborts the loop and skips every subsequent global and tenant enricher. - Catching
BaseException(or bareexcept:): SwallowsKeyboardInterruptandSystemExit, preventing graceful worker shutdowns. - Checking
isinstance(plugin, Enricher)at registration: Breaks duck typing and rejects plain classes (includingServiceAccountEnricherin Example 1!) that implementenrich(event)without subclassingEnricher. - Using
if not tenant_id:to detect global registrations: Misclassifiestenant_id=""as global and leaks that tenant's rules onto every other organization. - Storing
(tenant_id, plugin)tuples in a single flat list: Degradesprocess(event)fromO(E + R)toO(N)across all tenants' plugins. - Checking
if rule.should_suppress(event):withoutisinstance(..., bool): Allows buggy truthy return values like"false"or{"suppress": False}to evaluate as truthy and drop real security alerts! - Storing raw
Exceptioninstances insideevent.attributes: Exception objects cannot be serialized to JSON and pin stack-frame local variables in memory.
Alternative approaches
- Copy-on-write immutable registry: If
processruns millions of times per second andregister_*runs rarely, store pre-concatenated immutable tuples per tenant and rebuild them on registration using an atomic reference swap (repointing one variable in a single step), eliminating theO(E + R)list copy insideprocess. - Explicit attribute dependency graph (DAG): Have each enricher declare
readsandwritesattribute keys so the pipeline topologically sorts enrichers automatically — preventing registration-order bugs and revealing independent enrichers that can run in parallel.
Follow-up questions
-
How could worker processes pick up updated plugin and rule configurations from remote storage on the fly without process restarts or lost events? Store rule bundles as immutable versioned snapshots (for example
s3://configs/rules-v42.json), and have a background thread on each worker poll or subscribe to version notifications. Whenv43appears, the background thread parses, validates, instantiates, and smoke-tests a brand-new registry object completely off to the side, then performs an atomic pointer swap (self._active_registry = new_registry— replacing one object reference in a single indivisible step). In-flight events keep thev42registry reference they grabbed at the start ofprocess, zero events are dropped, every processed event logs itsregistry_versionfor auditing, and new suppression rules can run in shadow mode (logging matches without dropping alerts) before going live. -
When enrichers call slow external services over the network, how would you keep throughput high and prevent cascading slowdowns? Group independent
async def enrich(...)plugins into stages and run each stage concurrently withasyncio.gatherso three200 mslookups finish in~200 msinstead of600 ms, while wrapping every external call in a strict timeout (asyncio.wait_for). Put a TTL cache (a key-value cache whose entries expire after a fixed time-to-live, such as 5 minutes for domain reputation) and cross-event request batching in front of external APIs to cut network calls by 80–95%. Finally, protect each upstream vendor with a circuit breaker — a wrapper that trips "open" afterKconsecutive timeouts and fails fast for30 swithout waiting — and tag skipped fields so suppression rules depending on missing enrichment data fail open rather than misclassifying events. -
How would you let customer admins author custom suppression filters safely without executing untrusted Python code? Never run
eval()orexec()on tenant-supplied Python (sandbox escapes via object introspection are notorious, and infinite loops can hang workers). Instead, accept a domain-specific expression language — a restricted, non-Turing-complete rule format with no loops, imports, or I/O, such as Google's Common Expression Language (CEL), JSON Logic, or a typed JSON AST ({"all": [{"field": "attributes.is_bot", "op": "eq", "value": True}]}). Validate every rule at save time (rejecting unknown fields/operators, deep nesting, oversized lists, and empty condition lists whereall([])would returnTrueand suppress 100% of a tenant's alerts!), compile it into an object withshould_suppress(event) -> bool, and register it intoSecurityPipelineunchanged.
```python class SafeJsonRule: """Evaluates {"all": [{"attr": "is_bot", "eq": True}, ...]} safely."""
def __init__(self, conditions: list) -> None:
if not conditions or len(conditions) > 20:
raise ValueError("rule must contain between 1 and 20 conditions")
self.conditions = conditions
def should_suppress(self, event: Event) -> bool:
for cond in self.conditions:
if event.attributes.get(cond["attr"]) != cond["eq"]:
return False
return True
```
Follow-up questions
- How could worker processes pick up updated plugin and rule configurations from remote storage on the fly without process restarts or lost events?
- When enrichers call slow external services over the network, how would you keep throughput high and prevent cascading slowdowns?
- How would you let customer admins author custom suppression filters safely without executing untrusted Python code?
Similar questions
- 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
- Transactional Shopping Cart with Nested Scopes