Build a Thread-Safe Batched Log Writer
Data Structure DesignModel answerLast 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:
-
Thread Safety: The
log(message)method must be callable from multiple threads simultaneously without race conditions or data corruption. -
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.
-
Automatic Flushing: Buffered messages should be written to disk when either:
- The buffer accumulates
max_buffer_sizemessages flush_interval_msmilliseconds have elapsed since the last write- The user explicitly calls
flush()
- The buffer accumulates
-
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
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Solution Approach
This problem requires coordinating multiple producer threads (callers of log) with a single consumer (disk writer) while maintaining ordering and performance.
Architecture
The design uses a producer-consumer pattern with a background flusher thread:
- Producers (threads calling
log) acquire a lock, append formatted entries to an in-memory list, and immediately release the lock. Lock hold time is O(1). - Consumer (background thread) sleeps on a condition variable and wakes when the buffer reaches
max_buffer_sizeor when the time threshold expires. - Buffer swapping: To write, the consumer atomically swaps the full buffer for an empty one while holding the lock, then writes the swapped batch to disk outside the lock. This lets producers continue adding entries during the write.
Ordering Guarantees
Per-thread ordering is automatic: since all appends happen under one lock, the buffer maintains a total order consistent with each thread's execution sequence. Entries from thread A arrive in the order thread A submitted them.
Cross-thread ordering follows ingestion order. We timestamp each entry while holding the buffer lock, ensuring timestamps never reorder. The file reflects the exact sequence entries entered the buffer.
Critical insight: If multiple flushers could write concurrently, batch 2 might reach the file before batch 1. We prevent this by holding an I/O lock across both the swap and the write, serializing all flush operations.
Synchronization Strategy
Two locks coordinate access:
- Buffer lock (
_lock): Guards the in-memory buffer, closed flag, and last-flush timestamp. Producers hold this only during append. - I/O lock (
_io_lock): Serializes swap-and-write operations to ensure batches reach the file in order.
Lock acquisition order is always _io_lock then _lock—never reversed—preventing deadlock.
Two condition variables manage coordination:
_wake: Wakes the background flusher when the buffer is ready_space: Wakes blocked producers when buffer space becomes available
Backpressure Policy
We set a capacity limit at 10 × max_buffer_size. When the buffer is full, producers block on the _space condition variable until the flusher makes room. This bounds memory usage while never dropping data. Producers wait rather than losing messages.
Alternative policies:
- Drop with counter: Increment a dropped-message counter and return immediately
- Unbounded: Risk memory exhaustion but never block producers
Error Handling
If a disk write fails:
- The failed batch is re-inserted at the front of the buffer, preserving order
- The background thread logs the error and retries with exponential backoff
- An explicit
flush()orclose()re-raises the exception to the caller
Data is never silently lost. Note: A partial write followed by retry may duplicate lines (at-least-once delivery).
Shutdown Sequence
close() follows this protocol:
- Acquire buffer lock and set
_closedflag, preventing newlog()calls - Wake the background thread via
_wake.notify_all() - Wake any blocked producers via
_space.notify_all()(they'll see_closedand raise) - Join the background thread (wait for it to finish draining)
- Perform a final flush under I/O lock to catch any residual entries
- Close the file handle
Subsequent close() calls are idempotent (return immediately). Calls to log() after closure raise ValueError.
Complexity
log()time: O(1) amortized (one list append under lock, plus O(len(message)) formatting)- Flush time: O(B) for B bytes in the batch, amortized across up to
max_buffer_sizeentries - Space: O(capacity), bounded by the backpressure limit
Implementation
import threading
import time
class ConcurrentFileLogger:
def __init__(self, file_path: str, max_buffer_size: int = 1000, flush_interval_ms: int = 200):
if max_buffer_size < 1 or flush_interval_ms < 1:
raise ValueError("max_buffer_size and flush_interval_ms must be positive")
self._file = open(file_path, "a", encoding="utf-8")
self._max = max_buffer_size
self._capacity = max_buffer_size * 10
self._interval = flush_interval_ms / 1000.0
self._buf = []
self._lock = threading.Lock()
self._wake = threading.Condition(self._lock)
self._space = threading.Condition(self._lock)
self._io_lock = threading.RLock()
self._closed = False
self._last_flush = time.monotonic()
self._last_error = None
self._worker = threading.Thread(target=self._background_flusher, daemon=True)
self._worker.start()
def log(self, message: str) -> None:
sanitized = message.replace("\n", "\\n")
with self._lock:
# Wait if buffer is at capacity
while not self._closed and len(self._buf) >= self._capacity:
self._space.wait()
if self._closed:
raise ValueError("Cannot log to a closed logger")
timestamp = time.time()
thread_name = threading.current_thread().name
entry = f"{timestamp:.6f} [{thread_name}] {sanitized}\n"
self._buf.append(entry)
# Wake flusher if we've hit the size threshold
if len(self._buf) >= self._max:
self._wake.notify()
def flush(self) -> None:
self._write_batch()
def close(self) -> None:
with self._lock:
if self._closed:
return
self._closed = True
self._wake.notify_all()
self._space.notify_all()
self._worker.join()
with self._io_lock:
try:
self._write_batch()
finally:
self._file.close()
def _background_flusher(self) -> None:
while True:
with self._lock:
# Wait for signal or timeout
elapsed = time.monotonic() - self._last_flush
timeout = max(0, self._interval - elapsed)
self._wake.wait(timeout)
if self._closed:
# Drain remaining buffer and exit
self._write_batch()
break
# Check if we should flush
should_flush = (
len(self._buf) >= self._max or
time.monotonic() - self._last_flush >= self._interval
)
if should_flush:
self._write_batch()
def _write_batch(self) -> None:
with self._io_lock:
if self._file.closed:
return
# Atomically swap buffers
with self._lock:
batch, self._buf = self._buf, []
self._last_flush = time.monotonic()
self._space.notify_all()
if not batch:
return
try:
self._file.write("".join(batch))
self._file.flush()
except Exception as e:
# Reinsert failed batch at front
with self._lock:
self._buf = batch + self._buf
self._last_error = e
raise
Edge Cases Handled
- Empty flush: If the buffer is empty, no write occurs but the timer resets
- Repeated I/O failures: Background thread retries; buffer fills and blocks producers
- Double close: Second call returns immediately
- Flush during close: Both serialize on
_io_lock; order is deterministic - Log after close: Raises
ValueErrorimmediately - Invalid parameters: Constructor validates and raises
ValueError
This design achieves high throughput by batching writes, minimizes lock contention by keeping critical sections brief, and guarantees correctness through careful synchronization and lock ordering.