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:

  1. Contextual enrichment: Pluggable enrichers inspect the record and populate additional fields inside its attributes dictionary in place.
  2. 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 fields tenant_id: str, event_type: str, timestamp: int, and attributes: Dict[str, Any] (defaulting to a fresh {} per instance when omitted).
  • Enricher: Base interface declaring enrich(self, event: Event) -> None. Any duck-typed object with a callable enrich attribute must be accepted even if it does not subclass Enricher.
  • SuppressionRule: Base interface declaring should_suppress(self, event: Event) -> bool. Any duck-typed object with a callable should_suppress attribute must be accepted even if it does not subclass SuppressionRule.
  • SecurityPipeline:
    • register_enricher(self, enricher: Enricher, tenant_id: Optional[str] = None) -> None: Validates that enricher exposes a callable enrich method (raising TypeError immediately otherwise). Registers globally when tenant_id is None, or exclusively for tenant_id for any string value (including "").
    • register_suppression_rule(self, rule: SuppressionRule, tenant_id: Optional[str] = None) -> None: Validates that rule exposes a callable should_suppress method (raising TypeError immediately otherwise). Registers globally when tenant_id is None, or exclusively for tenant_id otherwise.
    • process(self, event: Event) -> Optional[Event]:
      1. Enrichment phase: Invoke all global enrichers in registration order, then all enrichers registered for event.tenant_id in registration order. Every applicable enricher finishes before any suppression rule is called.
      2. Suppression phase: Evaluate all global suppression rules in registration order, then all rules registered for event.tenant_id in registration order. On the first rule that returns True, immediately stop evaluating remaining rules and return None. If no rule returns True, return the same event instance.
      3. Fault isolation and fail-open behavior:
        • If an enricher raises an Exception, append {"stage": "enrich", "plugin": <class name>, "error": "<ExceptionType>: <message>"} to event.attributes["pipeline_errors"] and continue running subsequent plugins.
        • If a suppression rule raises an Exception or returns anything other than a bool (isinstance(result, bool) — note that integers such as 1 are not bool), record an entry under "stage": "suppress" in event.attributes["pipeline_errors"] (recording TypeError for non-boolean return values), treat that rule as non-matching (fail open), and continue checking remaining rules.
        • Do not add the "pipeline_errors" key to event.attributes when zero errors occur.

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 None denotes global scope; any string (including "") targets that exact tenant_id.
  • Processing an event for one tenant should run in O(E + R) pipeline overhead (where E and R are the numbers of enrichers and rules applicable to that event), independent of how many other tenants have plugins registered.
  • Standard Exception subclasses raised by plugins are caught and logged in event.attributes["pipeline_errors"]; KeyboardInterrupt and SystemExit must not be swallowed.

Step-by-step walkthrough

  1. Restate the problem and clarify edge-case rules

    Security platforms receive a continuous stream of raw activity logs (Event objects) from many customer organizations (tenants). Before turning an event into a security alert, our pipeline runs two distinct stages:

    1. Enrichment: Plugins called enrichers add useful context into event.attributes (for example checking whether actor belongs to an automated svc- service account).
    2. Suppression: Plugins called suppression rules inspect the enriched event and return True if it is a known false positive that should be dropped (process returns None), or False if it should keep going (process returns the Event).

    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 (enrich or should_suppress), even if it does not inherit from Enricher or SuppressionRule (just like the prompt's example classes!). Passing an object without that callable method raises TypeError right at registration time.
    • Only None means 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": ...} to event.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" or 1), we fail open — meaning we treat it as "do not suppress" so a buggy filter can never silently hide a real attack.
  2. Model the event and plugin contracts

    Let's start with Event and the two plugin base classes. Notice field(default_factory=dict) on Event.attributes: if every Event shared a single default dictionary {} in memory, mutating one event's attributes would corrupt every other event! Calling dict per 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 NotImplementedError
    
  3. Key idea: separate global lists and per-tenant dicts

    How should SecurityPipeline store registered plugins? Imagine 10,000 customer tenants with 5 rules each (50,000 rules total). If we stored (tenant_id, rule) pairs in one giant list, every single event would scan all 50,000 entries just to find the handful that apply to it!

    Instead, we store one list for global plugins plus one dictionary mapping tenant_id -> list for 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:

    1. Fast O(1) dictionary lookup: Processing an event for "org_north" never touches "org_south" or the other 9,998 tenants.
    2. Exact execution order for free: Python lists preserve insertion order, and concatenating global_plugins + tenant_plugins puts every global plugin ahead of every tenant plugin.
    3. Safe per-event snapshot: Using + allocates a brand-new list for the current event. If another caller registers a new plugin midway through process(event), the active loop finishes cleanly on its snapshot without RuntimeError or half-applied rules.
  4. Validate and register plugins

    Both registration methods validate the plugin up front using callable(getattr(plugin, method_name, None)) and route it using if tenant_id is None:. Be careful not to write if not tenant_id: — in Python not "" is True, which would accidentally turn tenant_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_plugins
    
  5. Phase 1: Run enrichers with isolated error capture

    Inside process(event), each enricher call is wrapped in its own try ... except Exception block inside the for loop. If we placed try outside the loop, the first broken enricher would skip every healthy enricher registered after it!

    Two important Python details here:

    • Catch Exception, not bare except: or BaseException: System signals like KeyboardInterrupt and SystemExit inherit from BaseException and must still be allowed to stop the process cleanly.
    • Create pipeline_errors lazily with setdefault: When everything succeeds, event.attributes stays clean with no "pipeline_errors": [] clutter, matching the prompt's expected output. And storing strings ({"stage", "plugin", "error"}) rather than raw Exception objects 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}",
        })
    
  6. 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) returns True, we immediately return None — later rules are never called (short-circuit evaluation).
    • What if a buggy rule returns "yes", 1, or a dictionary instead of True/False? In Python, if should_drop: treats any non-empty string or dict as truthy and would drop every alert! Checking if not isinstance(should_drop, bool): catches non-booleans (note that in Python isinstance(1, bool) is False, while isinstance(True, bool) is True), logs the error under "suppress", and continues 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
    
  7. Walk through Sample 1 and Sample 2

    First, trace Example 1, where ServiceAccountEnricher is registered globally and BotTrafficSuppressionRule is 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"): FailingGeoEnricher raises RuntimeError("geoip timeout"), _record_error appends {"stage": "enrich", "plugin": "FailingGeoEnricher", "error": "RuntimeError: geoip timeout"}, and "org_west"'s EnvTagEnricher still runs and sets "env": "staging". Then InvalidReturnRule returns "drop", triggering a TypeError recorded under "stage": "suppress", failing open so process(ev) returns ev.

  8. 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":

  1. ev_north (tenant_id="org_north", actor="svc-backup"): Lookup grabs [ServiceAccountEnricher] for enrichment and [BotTrafficSuppressionRule] for suppression. Phase 1 sets attributes["is_bot"] = True. Phase 2 runs BotTrafficSuppressionRule, gets True, short-circuits, and returns None.
  2. ev_south (tenant_id="org_south", actor="svc-backup"): Lookup grabs [ServiceAccountEnricher] and [] ("org_south" has no rules). Phase 1 sets attributes["is_bot"] = True. Phase 2 has zero rules to run and returns ev_south with 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 one getattr check, at most one hash-table dictionary lookup (setdefault), and one amortized O(1) list append.
  • process(event) — O(E + R) pipeline overhead (plus each invoked plugin's own runtime): Dictionary lookup by event.tenant_id takes O(1) average time regardless of how many thousands of other tenants exist, copying the two snapshot lists copies E + R object references, Phase 1 calls each of the E enrichers once, and Phase 2 calls at most R rules (fewer whenever an early rule returns True).
  • Space — O(N) persistent registry space, plus O(E + R) temporary per-event space: The four registry containers store each registered plugin reference once (O(N)), process allocates two short-lived snapshot lists of total length E + R, and pipeline_errors grows 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 checks if tenant_id is None: instead of if not tenant_id:.
  • Clean run with zero plugin errors: "pipeline_errors" is never added to event.attributes because setdefault runs only inside _record_error.
  • Broken rule or non-boolean return (1, "yes", None, numpy.bool_): Rejected by isinstance(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.attributes remain visible, the error is logged in pipeline_errors, and the next enricher still executes.
  • Suppressed event mutated in place: Enrichment runs before suppression, so the caller's event object retains enriched attributes (and any pipeline_errors) even when process(event) returns None.
  • Plugin registered mid-flight during process(event): _plugins_for creates a new snapshot list via + at the start of process, 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 single try/except: One failing enricher aborts the loop and skips every subsequent global and tenant enricher.
  • Catching BaseException (or bare except:): Swallows KeyboardInterrupt and SystemExit, preventing graceful worker shutdowns.
  • Checking isinstance(plugin, Enricher) at registration: Breaks duck typing and rejects plain classes (including ServiceAccountEnricher in Example 1!) that implement enrich(event) without subclassing Enricher.
  • Using if not tenant_id: to detect global registrations: Misclassifies tenant_id="" as global and leaks that tenant's rules onto every other organization.
  • Storing (tenant_id, plugin) tuples in a single flat list: Degrades process(event) from O(E + R) to O(N) across all tenants' plugins.
  • Checking if rule.should_suppress(event): without isinstance(..., bool): Allows buggy truthy return values like "false" or {"suppress": False} to evaluate as truthy and drop real security alerts!
  • Storing raw Exception instances inside event.attributes: Exception objects cannot be serialized to JSON and pin stack-frame local variables in memory.

Alternative approaches

  • Copy-on-write immutable registry: If process runs millions of times per second and register_* 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 the O(E + R) list copy inside process.
  • Explicit attribute dependency graph (DAG): Have each enricher declare reads and writes attribute 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. When v43 appears, 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 the v42 registry reference they grabbed at the start of process, zero events are dropped, every processed event logs its registry_version for 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 with asyncio.gather so three 200 ms lookups finish in ~200 ms instead of 600 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" after K consecutive timeouts and fails fast for 30 s without 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() or exec() 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 where all([]) would return True and suppress 100% of a tenant's alerts!), compile it into an object with should_suppress(event) -> bool, and register it into SecurityPipeline unchanged.

```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

Similar questions

More Abnormal Ai interview questions

All 1 Abnormal Ai questions →