Design a Multi-Tenant Security Event Enrichment Engine
Data Structure DesignModel answerLast updated
Design and implement an in-memory pipeline to enrich telemetry events and evaluate dynamic suppression rules with multi-tenant scoping and fault tolerance.
You are building an in-memory security telemetry processing engine. The engine ingests streaming security events (such as login requests, administrative actions, or network connections), enriches them with threat context, and filters out non-critical alerts using rule-based suppression.
Engine Requirements
-
EventData Structure: Contains fields:tenant_id(str),event_type(str),timestamp(int), andattributes(dict). -
Extensible Component Interfaces:
Enricher: Defines anenrich(event: Event) -> Nonemethod that mutatesevent.attributesin place or appends context metadata.SuppressionRule: Defines ashould_suppress(event: Event) -> boolmethod that returnsTrueif the event should be dropped.
-
SecurityPipelineExecution Engine:register_enricher(enricher: Enricher, tenant_id: Optional[str] = None) -> None: Registers an enricher globally (iftenant_idisNone) or for a specific tenant.register_suppression_rule(rule: SuppressionRule, tenant_id: Optional[str] = None) -> None: Registers a suppression rule globally or for a specific tenant.process(event: Event) -> Optional[Event]: Executes applicable enrichment and suppression logic in two distinct phases:- Phase 1: Enrichment: Execute all applicable global enrichers in order of registration, followed by all tenant-specific enrichers in order of registration.
- Phase 2: Suppression: Evaluate all applicable global suppression rules in order of registration, followed by tenant-specific suppression rules in order of registration.
- If any suppression rule returns
True, immediately stop evaluating further rules and returnNone. If all suppression rules pass without suppressing, return the modifiedEvent.
Fault Isolation & Edge Cases
- Enrichment Resilience: If an enricher raises an exception, catch the error, record an entry under
event.attributes["pipeline_errors"], and continue executing remaining enrichers. Do not allow plugin exceptions to crash the pipeline. - Suppression Resilience: If a suppression rule raises an exception, log/record the error and treat the rule evaluation as
False(fail-open) so legitimate alerts are not dropped by buggy rules. - Duck Typing: Accept any object implementing the required method signature (
enrichorshould_suppress), even if it does not explicitly inherit from the base interface.
Hints
Hint 1
Use separate lists for global plugins and dictionary-backed lists (keyed by tenant_id) for tenant-scoped plugins to preserve registration order while guaranteeing O(1) tenant lookup.
Hint 2
Execute all enrichers to completion before commencing the suppression phase so that suppression rules evaluate fully-populated event attributes.
Hint 3
Isolate plugin execution with try-except blocks, recording failures in event.attributes['pipeline_errors'] to ensure non-blocking pipeline operations.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach and Architectural Strategy
This problem tests clean object-oriented design, extensibility, multi-tenant isolation, and fault tolerance.
1. Data Model & Registration Storage
To preserve strict execution order while maintaining $O(1)$ tenant lookup:
- Global enrichers and suppression rules are stored in standard lists (
_global_enrichers,_global_rules). - Tenant-scoped plugins are stored in dictionary maps mapping
tenant_idto lists (_tenant_enrichers,_tenant_rules). Using standard dictionaries with.get(tenant_id, [])avoids unwanted side effects (e.g.,defaultdictcreating empty keys for unknown tenants).
2. Execution Phases & Ordering
Processing follows a two-phase execution pipeline:
- Enrichment Phase: Executes all global enrichers sequentially, followed by tenant-specific enrichers. Mutates
event.attributesin place. - Suppression Phase: Evaluates global rules sequentially, followed by tenant-specific rules. The first rule returning
Trueshort-circuits the pipeline, returningNone.
3. Error Handling Policy
- Enricher Exceptions: Recorded into
event.attributes["pipeline_errors"]as a list of dicts containing the component phase, plugin name, and error message. Pipeline processing continues. - Suppression Exceptions: Handled with a fail-open strategy. If a rule fails during evaluation, record the error in
pipeline_errorsand treat the evaluation result asFalse. This ensures buggy suppression logic does not lead to dropped alert events.
Python 3 Implementation
from __future__ import annotations
import logging
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional
logger = logging.getLogger(__name__)
@dataclass
class Event:
tenant_id: str
event_type: str
timestamp: int
attributes: Dict[str, Any] = field(default_factory=dict)
class Enricher(ABC):
@abstractmethod
def enrich(self, event: Event) -> None:
"""Mutate event.attributes in place."""
pass
class SuppressionRule(ABC):
@abstractmethod
def should_suppress(self, event: Event) -> bool:
"""Return True if the event should be suppressed."""
pass
class SecurityPipeline:
ERRORS_KEY = "pipeline_errors"
def __init__(self) -> None:
self._global_enrichers: List[Any] = []
self._tenant_enrichers: Dict[str, List[Any]] = {}
self._global_rules: List[Any] = []
self._tenant_rules: Dict[str, List[Any]] = {}
def _validate_interface(self, instance: Any, method_name: str) -> None:
if not hasattr(instance, method_name) or not callable(getattr(instance, method_name)):
raise TypeError(f"Registered object must implement callable '{method_name}' method.")
def register_enricher(self, enricher: Enricher, tenant_id: Optional[str] = None) -> None:
self._validate_interface(enricher, "enrich")
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:
self._validate_interface(rule, "should_suppress")
if tenant_id is None:
self._global_rules.append(rule)
else:
self._tenant_rules.setdefault(tenant_id, []).append(rule)
def _get_applicable_plugins(self, global_list: List[Any], tenant_map: Dict[str, List[Any]], tenant_id: str) -> List[Any]:
return global_list + tenant_map.get(tenant_id, [])
def _record_error(self, event: Event, phase: str, plugin: Any, exception: Exception) -> None:
if event.attributes is None:
event.attributes = {}
if self.ERRORS_KEY not in event.attributes or not isinstance(event.attributes[self.ERRORS_KEY], list):
event.attributes[self.ERRORS_KEY] = []
event.attributes[self.ERRORS_KEY].append({
"phase": phase,
"plugin": plugin.__class__.__name__,
"error": str(exception)
})
logger.error(f"Pipeline error in {phase} phase for plugin {plugin.__class__.__name__}: {exception}")
def process(self, event: Event) -> Optional[Event]:
if event.attributes is None:
event.attributes = {}
# Phase 1: Enrichment
enrichers = self._get_applicable_plugins(self._global_enrichers, self._tenant_enrichers, event.tenant_id)
for enricher in enrichers:
try:
enricher.enrich(event)
except Exception as exc:
self._record_error(event, "enrichment", enricher, exc)
# Phase 2: Suppression
rules = self._get_applicable_plugins(self._global_rules, self._tenant_rules, event.tenant_id)
for rule in rules:
try:
suppress = bool(rule.should_suppress(event))
if suppress:
return None
except Exception as exc:
self._record_error(event, "suppression", rule, exc)
return event
Complexity Analysis
- Time Complexity:
- Registration: $O(1)$ amortized per plugin.
- Processing: Let $G_e, G_s$ be the number of global enrichers and suppression rules, and $T_e, T_s$ be the number of tenant-specific enrichers and suppression rules. Processing runs in $O(G_e + T_e + G_s + T_s)$ time plus the execution time of individual plugin logic. Suppression short-circuits on the first match.
- Space Complexity:
- Memory storage for rules and enrichers is $O(N)$ where $N$ is the total number of registered plugins across all tenants.
- Processing overhead per event is $O(1)$ auxiliary memory (excluding error logging attributes appended to failed events).