KatInterview

Non-Blocking Concurrent Log Writer with Bounded Buffer

Data Structure DesignModel answer
MediumModel answerData Structure Designconcurrencyproducer-consumerbounded-queue

Last 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

  1. Thread safety. Any number of threads may call log concurrently. Nothing may be corrupted, duplicated, or silently lost.
  2. Ordering. Messages should reach the sink in the order the log calls were made. If thread A's call finishes before thread B's call begins, A's message must appear first.
  3. Low caller latency. Callers should not wait on sink.write except when the system is genuinely overloaded.
  4. Bounded memory. If the sink slows down, memory use must stay capped by buffer_size rather than growing without limit.
  5. Durability on exit. Every message that was accepted must be written to the sink before shutdown returns.

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 shutdown being called?
  • How do you avoid losing a message when log and shutdown race?
  • What if sink.write throws, or log is called after shutdown?

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?