KatInterview

Build a Thread-Safe Batched Log Writer

Data Structure DesignModel answer
MediumModel answerData Structure Designconcurrencythreadingproducer-consumer

Last updated

Create a logger that safely accepts messages from multiple threads, buffers them in memory, and writes batches to disk based on size or time triggers.

Problem

Applications running high-volume workloads often need to write log entries from many concurrent threads. Writing each message individually to disk creates severe performance bottlenecks due to I/O latency and lock contention.

Your task is to build a thread-safe logger that collects log entries in memory and periodically writes them to a file in batches, reducing the number of disk operations while maintaining safe concurrent access.

Requirements

Build a ConcurrentFileLogger class with these behaviors:

  1. Thread Safety: The log(message) method must be callable from multiple threads simultaneously without race conditions or data corruption.

  2. Message Ordering: Messages submitted from a single thread must maintain their submission order in the output file. Messages from different threads should be ordered by their arrival time to the logger.

  3. Automatic Flushing: Buffered messages should be written to disk when either:

    • The buffer accumulates max_buffer_size messages
    • flush_interval_ms milliseconds have elapsed since the last write
    • The user explicitly calls flush()
  4. Graceful Termination: The close() method must write all remaining buffered messages and cleanly stop any background operations.

Interface

class ConcurrentFileLogger:
    def __init__(self, file_path: str, max_buffer_size: int = 1000, flush_interval_ms: int = 200):
        """
        Create a logger writing to file_path.
        - max_buffer_size: trigger flush after this many messages
        - flush_interval_ms: trigger flush after this many milliseconds
        """
        pass

    def log(self, message: str) -> None:
        """
        Add a message to the buffer. Safe to call from any thread.
        """
        pass

    def flush(self) -> None:
        """
        Write all currently buffered messages to disk immediately.
        """
        pass

    def close(self) -> None:
        """
        Write remaining messages, close the file, and stop background threads.
        """
        pass

Example

import threading

logger = ConcurrentFileLogger("output.log", max_buffer_size=10, flush_interval_ms=500)

def write_logs(worker_id):
    for i in range(5):
        logger.log(f"Worker-{worker_id}: entry {i}")

workers = [threading.Thread(target=write_logs, args=(n,)) for n in range(3)]
for w in workers: w.start()
for w in workers: w.join()

logger.close()
# output.log contains all 15 entries with consistent ordering per worker

Additional Considerations

  • Memory Management: Decide how to handle situations where log messages arrive faster than they can be written to disk.
  • Error Recovery: Plan for disk write failures without losing data or breaking future logging.
  • Lifecycle: Handle cases like calling close() multiple times or attempting to log after closure.

Hints

Hint 1

This is a classic producer-consumer pattern—producers add messages while a consumer writes them to disk

Hint 2

To minimize lock contention, keep the critical section brief when adding messages; perform disk I/O outside locks whenever possible

Hint 3

Consider using a background thread that wakes periodically or when the buffer reaches capacity