Non-Blocking Concurrent Log Writer with Bounded Buffer
Data Structure DesignModel answerLast updated
Build a thread-safe logger whose callers never wait on slow sink I/O, preserving submission order, bounding memory, and flushing every accepted message on shutdown.
Concurrent Log Writer
You are building a small logging component for an application where many threads emit messages at the same time. The final destination is a Sink, an object with a single method write(message: str). That call performs blocking I/O and can be slow.
Design an EventLogger that accepts messages from any thread and delivers them to the sink, subject to the rules below.
Interface
class EventLogger:
def __init__(self, sink: Sink, buffer_size: int):
...
def log(self, message: str) -> None:
"""Accept a message for delivery to the sink."""
def shutdown(self) -> None:
"""Deliver everything still pending, then stop the logger."""
Rules
- Thread safety. Any number of threads may call
logconcurrently. Nothing may be corrupted, duplicated, or silently lost. - Ordering. Messages should reach the sink in the order the
logcalls were made. If thread A's call finishes before thread B's call begins, A's message must appear first. - Low caller latency. Callers should not wait on
sink.writeexcept when the system is genuinely overloaded. - Bounded memory. If the sink slows down, memory use must stay capped by
buffer_sizerather than growing without limit. - Durability on exit. Every message that was accepted must be written to the sink before
shutdownreturns.
Example
Thread A calls log("A"), and shortly afterwards thread B calls log("B"). The sink must see "A" and then "B".
What to discuss
- What should happen when the buffer is full: block the caller or drop the message? Justify the choice and describe the alternative.
- What happens if the process ends abruptly without
shutdownbeing called? - How do you avoid losing a message when
logandshutdownrace? - What if
sink.writethrows, orlogis called aftershutdown?
Describe your design, explain why it is correct, state its complexity, and provide code.
Hints
Hint 1
Treat this as a producer-consumer problem: callers should only hand messages off, and a single dedicated worker should be the only code that ever touches the sink.
Hint 2
A bounded FIFO queue gives you ordering, internal synchronization, and backpressure at once. Think about what the sentinel value can do to signal 'stop after everything before me'.
Hint 3
Consider the race where `log` checks a closed flag, gets preempted, and `shutdown` enqueues its stop marker first. How could a small lock around the check-and-enqueue step prevent a message from landing behind the marker?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a bounded producer-consumer pipeline with a single consumer.
- Producers (any thread calling
log) place the message on a thread-safe, bounded FIFO queue and return. They never callsink.write. - One consumer, a dedicated background thread, repeatedly takes a message from the queue and calls
sink.write. Because only one thread writes, the sink does not need to be thread-safe. - Shutdown marks the logger closed, enqueues a unique sentinel object behind all accepted messages, and joins the worker. The worker drains everything ahead of the sentinel and then exits.
The queue capacity is buffer_size. When the sink is slow the queue fills, which caps memory and creates backpressure on callers.
Why it is correct
- Thread safety: the queue is internally synchronized, and the sink is touched by exactly one thread.
- Ordering: FIFO queue plus one consumer means the sink sees messages in enqueue order. "Order of calls" is only well defined at a linearization point, and the enqueue is that point. If A's
logreturns before B's starts, A is ahead of B. For truly simultaneous calls, either order is valid. - No loss at shutdown: suppose
logsees "not closed" and is preempted, thenshutdownenqueues the sentinel, thenlogenqueues its message behind it. That message would never be written. The fix is a small lock that makes "check closed + enqueue" atomic with respect to "set closed + enqueue sentinel". Every accepted message is then strictly ahead of the sentinel. - No deadlock: a producer may hold that lock while blocked on a full queue. This is safe because the consumer never takes the lock, so it keeps draining and the producer eventually proceeds.
shutdownsimply waits its turn.
Complexity
log: O(1), blocking only when the buffer is full.- Worker: O(1) overhead per message plus the cost of
sink.write. - Space: O(
buffer_size), regardless of sink speed.
Buffer full: block or drop?
There is no universal answer, so state the trade-off.
- Block (default here): lossless and applies backpressure, but a stuck sink can stall the application.
- Drop with
put_nowait: callers never stall, but data is lost. Count drops and report them. - A common hybrid: block for ERROR-level messages, drop DEBUG/INFO.
Abrupt termination
- Make the worker a daemon thread and register
shutdownwithatexit. Python joins non-daemon threads before runningatexithandlers, so a non-daemon worker would wait forever for a shutdown that never comes. atexitcovers normal exit and unhandled exceptions. It does not coverSIGKILL,os._exit, or power loss. Buffered messages are lost in those cases by design. Only synchronous or write-ahead-log style writes survive them, at the cost of latency.
Other edge cases
sink.writeraises: catch the exception in the worker so one bad write does not kill the thread and silently stop all logging.logaftershutdown: raise an error so the caller knows the message was rejected.- Repeated
shutdown: make it idempotent. - Re-entrancy: if the sink calls
log, a full queue can deadlock. Ashutdowncall from the worker thread must not join itself.
Code
import atexit
import queue
import sys
import threading
_SENTINEL = object()
class EventLogger:
def __init__(self, sink, buffer_size: int, drop_when_full: bool = False):
if buffer_size <= 0:
raise ValueError("buffer_size must be positive")
self._sink = sink
self._queue = queue.Queue(maxsize=buffer_size)
self._drop_when_full = drop_when_full
self._dropped = 0
self._closed = False
self._lock = threading.Lock() # atomic (closed-check + enqueue) vs. shutdown
self._worker = threading.Thread(target=self._run, name="EventLogger", daemon=True)
self._worker.start()
atexit.register(self.shutdown)
def log(self, message: str) -> None:
with self._lock:
if self._closed:
raise RuntimeError("EventLogger has been shut down")
if self._drop_when_full:
try:
self._queue.put_nowait(message)
except queue.Full:
self._dropped += 1
else:
self._queue.put(message) # backpressure if sink is slow
def _run(self) -> None:
while True:
item = self._queue.get()
if item is _SENTINEL:
return
try:
self._sink.write(item)
except Exception as exc:
print(f"EventLogger: sink.write failed: {exc!r}", file=sys.stderr)
def shutdown(self, timeout: float | None = None) -> None:
with self._lock:
if not self._closed:
self._closed = True
self._queue.put(_SENTINEL) # behind every accepted message
if threading.current_thread() is not self._worker:
self._worker.join(timeout)
if self._dropped:
print(f"EventLogger: dropped {self._dropped} messages", file=sys.stderr)
try:
atexit.unregister(self.shutdown)
except Exception:
pass
@property
def dropped(self) -> int:
return self._dropped
Throughput improvements
- If the sink supports batch writes, the worker can block on one
get(), then drain more withget_nowait()and issue a single write for the batch. - The producer-side lock serializes enqueues, but the queue already serializes on its own mutex, so the extra cost is small.
- At extreme scale, use per-thread buffers or a lock-free ring buffer (Disruptor style) with sequence numbers to merge entries in order.
Common mistakes
- Calling
sink.writedirectly fromlogunder a lock, which makes every caller pay for I/O. - Using an unbounded queue, which turns a slow sink into an out-of-memory failure.
- Checking a
closedflag without holding a lock shared with the sentinel enqueue, which loses messages in a race. - Using a non-daemon worker with
atexit, which hangs at exit. - Letting an exception from
sink.writeterminate the worker.
Follow-up ideas
- Log levels: filter in the producer before enqueueing, so suppressed messages cost almost nothing and use no buffer space. Store the threshold in one attribute that a config watcher swaps atomically.
- Persist before return: asynchrony no longer helps. Write synchronously, or use group commit where many callers wait on one shared flush, trading a little latency for throughput.