KatInterview

Design a Thread-Safe Log Rotating Sink

Data Structure DesignModel answer
MediumModel answerData Structure Designobject-oriented-designconcurrencyfile-io

Last updated

Implement a thread-safe, size-bounded rotating file sink class adhering to Liskov substitution and Python context manager protocols.

You are integrating a new logging sink into an existing execution framework. The system defines an abstract base class as follows:

from abc import ABC, abstractmethod

class RecordSink(ABC):
    @abstractmethod
    def open(self) -> None:
        """Initialize resources required for writing."""
        pass

    @abstractmethod
    def write(self, record: dict) -> None:
        """Write a single dictionary record to the sink."""
        pass

    @abstractmethod
    def close(self) -> None:
        """Release all allocated resources."""
        pass

An existing consumer engine (Pipeline) manages the sink life cycle by calling open() once, invoking write(record) for every incoming event, and finishing with close(). The engine source code cannot be modified.

Your task is to implement a concrete class RotatingFileSink(RecordSink) that satisfies these specifications:

  1. Formatting & Encoding: Serializes each dictionary record as a single-line, compact JSON string without unnecessary whitespace (separators=(',', ':')), appended with a newline (\n), and encoded in standard UTF-8.
  2. Rotation Rules: Rotates to a new file whenever:
    • The active file reaches a maximum line limit max_lines, or
    • Appending the current record would exceed max_bytes total file size (unless the file is currently empty, in which case a record larger than max_bytes must still be written to its own single file).
    • Filenames follow the format {prefix}_{index:05d}.log (e.g., app_00001.log). Files should be lazily instantiated upon the first record write.
  3. Thread Safety: Concurrent write() invocations from multiple threads must be thread-safe without corrupting data structures, line counts, or interleaving serialized JSON output.
  4. Context Manager Protocol: Supports standard Python with statements via __enter__ and __exit__.
  5. State Management & Exceptions:
    • Must raise a custom exception SinkClosedError if write() is invoked after close() has been called.
    • Re-opening a closed sink must raise SinkClosedError.
    • Idempotent close() and open() semantics (calling open() multiple times on an active sink is a no-op; calling close() multiple times does not raise errors).
  6. Liskov Substitution: Operates transparently as a substitute for RecordSink inside Pipeline.

Provide the complete Python implementation including SinkClosedError, RotatingFileSink, and code demonstrating multi-threaded safety and rotation logic.

Hints

Hint 1

Serialize JSON data outside the synchronization lock to avoid blocking other writing threads during string formatting.

Hint 2

Ensure line and byte limits are checked atomically inside the lock before performing the write operation.

Hint 3

Measure byte length post-UTF-8 encoding rather than Python character length to accurately evaluate file size bounds.