Design a Thread-Safe Log Rotating Sink
Data Structure DesignModel answerLast 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:
- 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. - 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_bytestotal file size (unless the file is currently empty, in which case a record larger thanmax_bytesmust 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.
- The active file reaches a maximum line limit
- Thread Safety: Concurrent
write()invocations from multiple threads must be thread-safe without corrupting data structures, line counts, or interleaving serialized JSON output. - Context Manager Protocol: Supports standard Python
withstatements via__enter__and__exit__. - State Management & Exceptions:
- Must raise a custom exception
SinkClosedErrorifwrite()is invoked afterclose()has been called. - Re-opening a closed sink must raise
SinkClosedError. - Idempotent
close()andopen()semantics (callingopen()multiple times on an active sink is a no-op; callingclose()multiple times does not raise errors).
- Must raise a custom exception
- Liskov Substitution: Operates transparently as a substitute for
RecordSinkinsidePipeline.
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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Architectural Overview & Approach
To implement RotatingFileSink, we need to uphold object-oriented subtyping principles while managing concurrent I/O access and file rotation invariants.
-
Serialization Outside the Lock: Serializing dictionary records to compact JSON (
json.dumps(..., separators=(',', ':'))) and encoding to UTF-8 is CPU-bound. Doing this step before acquiring the mutual exclusion lock minimizes lock contention, allowing multiple producer threads to format records in parallel. -
Atomic State & Rotation: The critical section guarded by
threading.Lock()contains:- Validating state transitions (
_opened,_closed). - Checking whether the active file violates
max_linesormax_bytes. - Creating a new file handle if rotation is required.
- Writing the byte payload to disk and updating byte/line counters.
- Validating state transitions (
-
Size vs Character Count: File bounds strictly rely on byte lengths, not string length, since multi-byte UTF-8 sequences (such as non-ASCII characters) consume varying byte sizes on disk.
-
Lifecycle Semantics:
NEW$\rightarrow$open()$\rightarrow$OPENED$\rightarrow$close()$\rightarrow$CLOSED.- Writing before
open()raisesRuntimeError. - Writing or re-opening when
CLOSEDraisesSinkClosedError. close()is idempotent.
Python Implementation
import json
import os
import threading
from abc import ABC, abstractmethod
class RecordSink(ABC):
@abstractmethod
def open(self) -> None:
pass
@abstractmethod
def write(self, record: dict) -> None:
pass
@abstractmethod
def close(self) -> None:
pass
class SinkClosedError(RuntimeError):
"""Raised when an operation is performed on a closed sink."""
pass
class RotatingFileSink(RecordSink):
def __init__(self, directory: str, prefix: str, max_lines: int, max_bytes: int) -> None:
if max_lines <= 0 or max_bytes <= 0:
raise ValueError("max_lines and max_bytes must be positive integers.")
self._directory = directory
self._prefix = prefix
self._max_lines = max_lines
self._max_bytes = max_bytes
self._lock = threading.Lock()
self._is_opened = False
self._is_closed = False
self._file_handle = None
self._file_index = 0
self._current_lines = 0
self._current_bytes = 0
self._created_files: list[str] = []
def open(self) -> None:
with self._lock:
if self._is_closed:
raise SinkClosedError("Cannot re-open a closed RotatingFileSink.")
if self._is_opened:
return
os.makedirs(self._directory, exist_ok=True)
self._is_opened = True
def write(self, record: dict) -> None:
# Pre-process serialization outside critical section
payload = (json.dumps(record, separators=(",", ":"), ensure_ascii=False) + "\n").encode("utf-8")
payload_len = len(payload)
with self._lock:
if self._is_closed:
raise SinkClosedError("Cannot write to a closed RotatingFileSink.")
if not self._is_opened:
raise RuntimeError("Sink must be opened before writing.")
if self._file_handle is None or self._should_rotate(payload_len):
self._rotate_file()
self._file_handle.write(payload)
self._file_handle.flush()
self._current_lines += 1
self._current_bytes += payload_len
def close(self) -> None:
with self._lock:
if self._is_closed:
return
self._is_closed = True
if self._file_handle is not None:
self._file_handle.close()
self._file_handle = None
def __enter__(self) -> "RotatingFileSink":
self.open()
return self
def __exit__(self, exc_type, exc_val, exc_tb) -> bool:
self.close()
return False # Propagate inner exceptions
@property
def created_files(self) -> list[str]:
with self._lock:
return list(self._created_files)
def _should_rotate(self, incoming_bytes: int) -> bool:
if self._current_lines >= self._max_lines:
return True
# Allow single record exceeding max_bytes if current file is empty
if self._current_bytes > 0 and (self._current_bytes + incoming_bytes > self._max_bytes):
return True
return False
def _rotate_file(self) -> None:
if self._file_handle is not None:
self._file_handle.close()
self._file_handle = None
self._file_index += 1
filename = f"{self._prefix}_{self._file_index:05d}.log"
filepath = os.path.join(self._directory, filename)
self._file_handle = open(filepath, "wb")
self._created_files.append(filepath)
self._current_lines = 0
self._current_bytes = 0
Complexity Analysis
- Time Complexity:
write(): $\mathcal{O}(S)$ per invocation, where $S$ is the size of the record dictionary being serialized. Lock acquisition and counter checks run in $\mathcal{O}(1)$ time. File rotation requires an $\mathcal{O}(1)$ open/close operation.open()/close(): $\mathcal{O}(1)$.
- Space Complexity:
- Memory overhead per record write is $\mathcal{O}(S)$ to store the UTF-8 serialized byte array before flushing to disk. Sink metadata state uses $\mathcal{O}(F)$ auxiliary space where $F$ is the total number of rotated files tracked.
Verification & Thread-Safety Testing Example
Below is a runnable test verifying both rotation bounds and thread safety under concurrent execution:
import json
import os
import shutil
import tempfile
import threading
def test_rotating_sink():
temp_dir = tempfile.mkdtemp()
try:
# Max 2 lines or 100 bytes per file
sink = RotatingFileSink(directory=temp_dir, prefix="test", max_lines=2, max_bytes=100)
# Test Context Manager
with sink:
num_threads = 4
records_per_thread = 5
def worker(thread_id):
for i in range(records_per_thread):
sink.write({"thread": thread_id, "seq": i})
threads = [
threading.Thread(target=worker, args=(t,))
for t in range(num_threads)
]
for t in threads:
t.start()
for t in threads:
t.join()
# Check rotation behavior
created = sink.created_files
assert len(created) >= 10, f"Expected at least 10 rotated files, got {len(created)}"
# Verify line content integrity across all output files
total_records = 0
for path in created:
with open(path, "rb") as f:
lines = f.readlines()
assert len(lines) <= 2, f"File {path} exceeded line cap with {len(lines)} lines"
for line in lines:
data = json.loads(line.decode("utf-8"))
assert "thread" in data and "seq" in data
total_records += 1
assert total_records == num_threads * records_per_thread
print("All assertions passed successfully!")
finally:
shutil.rmtree(temp_dir)
if __name__ == "__main__":
test_rotating_sink()