Build a Multi-Sink Logging Pipeline with Fault Isolation
System DesignModel answerLast updated
Design a thread-safe in-process logger that fans out immutable log records to independent handlers with isolated failures, runtime reconfiguration, and bounded async buffering.
The Problem
You are building a logging library for a long-running server process. A single Logger instance receives log calls from application code and fans each record out to one or more registered LogHandler sinks — for example, a console sink, a rolling-file sink, and a remote observability endpoint.
The library must meet four hard requirements:
1. Records are immutable after creation.
Once the logger constructs a LogRecord, no handler — and no caller — may change its contents. A handler that mutates a record must not affect what any other handler sees.
2. A misbehaving handler cannot hurt anyone else. If a handler raises an exception (e.g., a network timeout, a serialization error), the logger must catch and report it silently, then continue dispatching to the remaining handlers. The calling thread must never see an exception from a handler.
3. Handlers can be added or removed while logging is in flight.
A background thread may call remove_handler("stale_sink") at the same moment an application thread is fanning out a new record. This must not corrupt the handler registry, cause a deadlock, or silently drop the registration change.
4. Slow sinks must not stall fast ones. An HTTP-based handler that does a network round-trip per record must not block the console handler. Asynchronous handlers buffer incoming records up to a configurable capacity. When that buffer is full, the handler executes a caller-chosen overflow strategy:
DROP_NEWEST— silently discard the incoming record.DROP_OLDEST— evict the oldest buffered record to make room.BLOCK— wait up to a timeout for space, then drop if none appears.
Interface to implement
from enum import Enum
from typing import Any, Dict, Optional
class LogLevel(Enum):
DEBUG = 10
INFO = 20
WARN = 30
ERROR = 40
class OverflowPolicy(Enum):
DROP_NEWEST = "DROP_NEWEST"
DROP_OLDEST = "DROP_OLDEST"
BLOCK = "BLOCK"
class LogRecord:
"""Immutable snapshot of one log event."""
def __init__(
self,
level: LogLevel,
message: str,
timestamp: float,
metadata: Optional[Dict[str, Any]] = None,
): ...
class LogHandler:
def __init__(self, min_level: LogLevel = LogLevel.INFO): ...
def emit(self, record: LogRecord) -> None:
"""Deliver the record. Must not let exceptions propagate."""
raise NotImplementedError
def close(self) -> None:
"""Drain buffers and free resources."""
pass
class Logger:
def __init__(self, min_level: LogLevel = LogLevel.INFO): ...
def add_handler(self, name: str, handler: LogHandler) -> None: ...
def remove_handler(self, name: str) -> Optional[LogHandler]: ...
def log(self, level: LogLevel, message: str, **kwargs: Any) -> None: ...
Example
logger = Logger(min_level=LogLevel.DEBUG)
console = ConsoleHandler(min_level=LogLevel.INFO)
broken = AlwaysFailingHandler(min_level=LogLevel.DEBUG)
logger.add_handler("console", broken) # fails on every emit
logger.add_handler("console", console) # ValueError: name already taken
logger.add_handler("broken", broken)
logger.log(LogLevel.INFO, "session started", user_id=99)
# broken silently fails; console still prints the record
logger.remove_handler("broken")
logger.log(LogLevel.WARN, "high memory usage")
# only console receives this one
What you should cover in your answer
- How you enforce immutability (including nested mutable values in
metadata). - The concurrency strategy for the handler registry — specifically how you avoid holding a lock while dispatching.
- How
AsyncHandlerwraps any sync handler without changing theLogHandlerinterface. - How each overflow policy works and how drop events are tracked.
- Shutdown semantics: what happens to records already in the buffer when
close()is called. - Any edge cases you would handle differently in a production library.
Hints
Hint 1
A frozen dataclass blocks attribute assignment, but freezing the dataclass does not freeze a dict passed as metadata — you need to recursively convert mutable containers into read-only equivalents such as MappingProxyType and tuple before storing them.
Hint 2
Copy-on-write is the key to lock-free dispatch: under a write lock you build a brand-new mapping and publish it with a single reference swap. The dispatching thread reads the current reference once into a local variable, so it iterates a stable snapshot even if a concurrent writer swaps in a new mapping mid-loop.
Hint 3
AsyncHandler should be a wrapper, not a subclass of your concrete handlers. It owns a bounded queue and a background worker thread. The three overflow policies differ only in what happens when queue.put fails: DROP_NEWEST catches the Full exception and discards, DROP_OLDEST pops from the front before retrying, and BLOCK calls put with a timeout and then drops if time runs out.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Each requirement maps cleanly to one mechanism. Keeping them separate makes the design easier to reason about and test independently.
| Requirement | Mechanism |
|---|---|
| Immutable records | Frozen dataclass + recursive _freeze() on metadata |
| Isolated failures | Per-handler try/except inside the dispatch loop |
| Safe reconfiguration | Copy-on-write registry published with one reference swap |
| Bounded backpressure | AsyncHandler wrapper with a bounded queue and worker thread |
Two details separate strong answers from average ones. First, dispatch happens outside any lock — a slow or re-entrant handler cannot deadlock add_handler. Second, async behavior is a decorator, not a base class. You wrap SlowHttpHandler in AsyncHandler; fast handlers like ConsoleHandler are never affected.
Immutability
Use @dataclass(frozen=True) to block attribute assignment on LogRecord. That alone is not enough: a dict stored in metadata is still mutable from the outside. The fix is a recursive _freeze function applied in __post_init__:
dict→MappingProxyType(read-only view, no copy needed for the proxy itself)list/tuple→tuplewith each element frozenset/frozenset→frozensetwith each element frozen- Scalars (str, int, float, bool, bytes, None, Enum) → returned as-is
- Anything else →
copy.deepcopy; fall back torepr()if that fails
The defensive deep-copy of the incoming dict before freezing breaks aliasing with the caller, so mutating the caller's dict after log() returns has no effect on the stored record.
Concurrent registry mutation
The handler registry is stored as an immutable MappingProxyType. All writes (add_handler, remove_handler) take a short write lock, copy the mapping into a plain dict, make the change, then publish a new MappingProxyType with a single reference assignment:
with self._write_lock:
updated = dict(self._handlers)
updated[name] = handler
self._handlers = MappingProxyType(updated) # atomic publish in CPython
The dispatch path reads self._handlers once into a local variable before iterating. That local snapshot remains valid even if a writer swaps in a new mapping mid-loop. The one benign race: a handler removed during an in-flight log() may receive that one record. That is acceptable — the alternative (holding a lock during dispatch) risks deadlock.
Failure isolation and re-entrancy
Each handler gets its own try/except block. Errors are written to stderr via a helper that never routes back through the logger (which would risk infinite recursion). A thread-local re-entrancy flag drops any log() call made from inside a handler for the same reason.
AsyncHandler
AsyncHandler wraps any LogHandler without subclassing it. It owns a queue.Queue(maxsize=capacity) and a daemon worker thread that pulls records and calls the inner handler's emit. The three overflow policies differ only in their queue-full behavior:
DROP_NEWEST:queue.put_nowait(record)— catchqueue.Full, increment drop counter.DROP_OLDEST: drain one item from the head withqueue.get_nowait(), then retryput_nowait.BLOCK:queue.put(record, timeout=block_timeout)— catchqueue.Fullafter timeout, drop.
Every drop increments an atomic counter accessible via handler.drop_count. In production you would expose this as a metric.
Shutdown semantics
close() sets a closed flag, then sends a sentinel object onto the queue. The worker exits only after draining everything ahead of the sentinel. This guarantees that every record accepted before close() reaches the inner handler. Calling emit() after close() counts as a drop.
Full Python implementation
import copy
import queue
import sys
import threading
import time
from dataclasses import dataclass, field
from enum import Enum
from types import MappingProxyType
from typing import Any, Dict, Mapping, Optional
# ---------------------------------------------------------------------------
# Enumerations
# ---------------------------------------------------------------------------
class LogLevel(Enum):
DEBUG = 10
INFO = 20
WARN = 30
ERROR = 40
class OverflowPolicy(Enum):
DROP_NEWEST = "DROP_NEWEST"
DROP_OLDEST = "DROP_OLDEST"
BLOCK = "BLOCK"
# ---------------------------------------------------------------------------
# Immutable record
# ---------------------------------------------------------------------------
_SCALARS = (str, int, float, bool, bytes, type(None))
def _freeze(value: Any) -> Any:
"""Recursively convert value to an immutable, unaliased equivalent."""
if isinstance(value, _SCALARS) or isinstance(value, Enum):
return value
if isinstance(value, Mapping):
return MappingProxyType({k: _freeze(v) for k, v in value.items()})
if isinstance(value, (list, tuple)):
return tuple(_freeze(v) for v in value)
if isinstance(value, (set, frozenset)):
return frozenset(_freeze(v) for v in value)
try:
return copy.deepcopy(value)
except Exception:
return repr(value)
@dataclass(frozen=True)
class LogRecord:
level: LogLevel
message: str
timestamp: float
metadata: Optional[Mapping[str, Any]] = field(default=None)
def __post_init__(self) -> None:
# Break aliasing with the caller, then freeze recursively.
raw = dict(self.metadata) if self.metadata else {}
object.__setattr__(self, "metadata", _freeze(raw))
# ---------------------------------------------------------------------------
# Base handler
# ---------------------------------------------------------------------------
class LogHandler:
def __init__(self, min_level: LogLevel = LogLevel.INFO):
self.min_level = min_level
def accepts(self, record: LogRecord) -> bool:
return record.level.value >= self.min_level.value
def emit(self, record: LogRecord) -> None:
raise NotImplementedError
def close(self) -> None:
pass
# ---------------------------------------------------------------------------
# Concrete handlers
# ---------------------------------------------------------------------------
class ConsoleHandler(LogHandler):
def emit(self, record: LogRecord) -> None:
print(
f"{record.timestamp:.3f} {record.level.name:<5} "
f"{record.message} {dict(record.metadata)}",
flush=True,
)
# ---------------------------------------------------------------------------
# Async wrapper
# ---------------------------------------------------------------------------
_SENTINEL = object()
class AsyncHandler(LogHandler):
"""Wraps any LogHandler with a bounded queue and a dedicated worker thread."""
def __init__(
self,
inner: LogHandler,
capacity: int = 1_000,
overflow: OverflowPolicy = OverflowPolicy.DROP_NEWEST,
block_timeout: float = 0.1,
):
super().__init__(min_level=inner.min_level)
self._inner = inner
self._overflow = overflow
self._block_timeout = block_timeout
self._q: queue.Queue = queue.Queue(maxsize=capacity)
self._drop_count = 0
self._closed = False
self._worker = threading.Thread(target=self._run, daemon=True)
self._worker.start()
@property
def drop_count(self) -> int:
return self._drop_count
def emit(self, record: LogRecord) -> None:
if self._closed:
self._drop_count += 1
return
try:
if self._overflow is OverflowPolicy.DROP_NEWEST:
self._q.put_nowait(record)
elif self._overflow is OverflowPolicy.DROP_OLDEST:
try:
self._q.put_nowait(record)
except queue.Full:
try:
self._q.get_nowait() # evict oldest
except queue.Empty:
pass
self._q.put_nowait(record)
else: # BLOCK
self._q.put(record, timeout=self._block_timeout)
except queue.Full:
self._drop_count += 1
def close(self) -> None:
self._closed = True
self._q.put(_SENTINEL) # wake the worker so it can drain and exit
self._worker.join()
self._inner.close()
def _run(self) -> None:
while True:
item = self._q.get()
if item is _SENTINEL:
break
try:
if self._inner.accepts(item):
self._inner.emit(item)
except Exception as exc:
_report_error(f"AsyncHandler inner={self._inner!r}", exc)
# ---------------------------------------------------------------------------
# Internal error reporter
# ---------------------------------------------------------------------------
def _report_error(source: str, exc: BaseException) -> None:
try:
print(f"[logging-internal] {source}: {exc!r}", file=sys.stderr)
except Exception:
pass
# ---------------------------------------------------------------------------
# Logger
# ---------------------------------------------------------------------------
class Logger:
def __init__(self, min_level: LogLevel = LogLevel.INFO):
self.min_level = min_level
self._write_lock = threading.Lock()
# Published atomically; never mutated after publication.
self._handlers: Mapping[str, LogHandler] = MappingProxyType({})
self._local = threading.local() # re-entrancy guard
# --- Registration -------------------------------------------------------
def add_handler(self, name: str, handler: LogHandler) -> None:
with self._write_lock:
if name in self._handlers:
raise ValueError(f"handler {name!r} is already registered")
updated = dict(self._handlers)
updated[name] = handler
self._handlers = MappingProxyType(updated)
def remove_handler(self, name: str) -> Optional[LogHandler]:
with self._write_lock:
if name not in self._handlers:
return None
updated = dict(self._handlers)
handler = updated.pop(name)
self._handlers = MappingProxyType(updated)
return handler
# --- Logging ------------------------------------------------------------
def log(self, level: LogLevel, message: str, **kwargs: Any) -> None:
# Level filter — avoid building the record if nothing will use it.
if level.value < self.min_level.value:
return
# Re-entrancy guard: a handler that logs back through this logger
# would cause infinite recursion.
if getattr(self._local, "in_log", False):
return
self._local.in_log = True
try:
try:
record = LogRecord(
level=level,
message=message,
timestamp=time.time(),
metadata=kwargs or None,
)
except Exception as exc:
_report_error("LogRecord construction", exc)
return
# Snapshot the registry once — dispatch outside any lock.
snapshot = self._handlers
for name, handler in snapshot.items():
try:
if handler.accepts(record):
handler.emit(record)
except Exception as exc:
_report_error(f"handler {name!r}", exc)
finally:
self._local.in_log = False
Complexity
log()— O(H + M) where H is the number of handlers and M is the metadata depth. No locks are acquired on the hot path.add_handler/remove_handler— O(H) to copy the registry. Reconfiguration is rare, so this is acceptable.AsyncHandler.emit— O(1) amortized.- Space — O(H) for the registry plus O(capacity) per async handler.
Common mistakes
- Freezing the dataclass but not its fields.
frozen=Trueonly blocks direct attribute assignment. A mutable dict inmetadatais still writable without the recursive_freezestep. - Holding the registry lock during dispatch. This creates a deadlock potential any time a handler calls back into
add_handleror takes time, and it serializes all logging threads behind each other. - Making AsyncHandler a subclass of each concrete handler. Inheritance couples the async machinery to the sink implementation. A wrapper keeps them independent and lets you mix sync and async sinks freely.
- Flushing the queue before the sentinel. If
close()simply signals the worker to stop, records already enqueued are silently lost. Draining to the sentinel guarantees delivery. - Routing internal errors back through the logger. Writing handler errors to the same logger risks infinite recursion;
stderris the safe escape hatch.