KatInterview

Build a Multi-Sink Logging Pipeline with Fault Isolation

System DesignModel answer
MediumModel answerSystem Designconcurrencyloggingsystem-design

Last 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 AsyncHandler wraps any sync handler without changing the LogHandler interface.
  • 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.