# Implement a Thread-Safe Batching Logger

> A thread-safe batching logger: one writer, batches for speed, no lost lines at shutdown, explained for your AI interview.

**In short:** Many threads put log lines on a thread-safe queue and carry on at once. One background thread writes them in batches, so lines never mix and the file gets far fewer writes. A stop marker and an exit hook make sure the last lines are written when the program ends.

AI and LLM interview question Q480, Coding and practical. Advanced, occasional (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/implement-a-thread-safe-batching-logger

## Say it in 30 seconds

I would use one queue and one writer thread. Each thread calls log, which puts the line on a thread-safe queue and returns straight away. The writer collects up to 100 lines, or whatever has arrived after half a second, and writes them in one go. Only that thread touches the file, so lines never mix. At shutdown I put a stop marker at the end of the queue and wait, so the last lines still get written.

## Say it in 2 minutes

Picture a payments service with 64 worker threads. Every checkout, refund and fraud check writes an audit line, and at peak that is a few thousand lines a second. If each thread opened the file and wrote its own line, the threads would pile up at the file lock and the disk would take a small write for every line. The logger has to be safe for all those threads, and cheap to call.

My design has three parts. Callers put each line on a queue.Queue, which handles the locking, so their own code needs no lock. One background thread takes lines off, collects up to 100 of them, and writes the batch in one call. It is the only thread that touches the file, so two lines can never interleave. A half-second limit on each batch stops a quiet system from holding a line for ever.

The hard part is shutdown. Lines still in the queue when the program exits are lost unless the writer empties them first. So close() puts a stop marker at the end of the queue and waits for the writer to finish. I would also name the trade-offs out loud: an unbounded queue hides a slow disk until memory runs out, so in production I would cap it and let callers feel the back pressure.

## What is a thread-safe batching logger, in plain words?

A logger writes down what a program does, so people can check it later. A batching logger holds messages for a moment and writes them as one group. Thread-safe means many workers can call it at the same time and the lines still come out whole.

Picture a hospital pharmacy. Nurses from every ward drop prescriptions into one tray. One pharmacist takes them out in order, bundles a batch and files it once. The nurses never queue at the filing cabinet, and no two prescriptions get mixed up. An AI platform has the same shape: a hundred parallel agents each produce audit lines, and writing every line to disk on its own is slow and messy.

- **Thread:** One of several workers running inside the same program at the same time.
- **Queue:** A line where items wait their turn. Python's queue.Queue lets many threads add and take items safely.
- **Batch:** Several items handled in one go, such as one file write for twenty lines.
- **Stop marker:** A special item put at the end of the queue, so the writer knows to finish up.
- **Lock:** A rule that lets only one thread use a shared thing at a time.

Python's own logging module is already thread-safe, so why build one? Because each handler (the part of Python logging that sends a record to a file or screen) still locks its own I/O, and a plain handler writes each line on its own. A batcher turns many small writes into a few large ones.

## Why not let every thread write straight to the file?

You can, and it stays safe. Each handler takes a lock around its I/O, so two threads can't tangle their lines.

> "The logging module is intended to be thread-safe without any special work needing to be done by its clients." (Python logging docs)
>
> "each handler also creates a lock to serialize access to its underlying I/O" (Python logging docs)

- **Direct: Every thread writes.** Simple and safe, but threads queue at the same lock, and each line costs its own trip to the disk.
- **Batched: Hand off, then one writer.** Callers put a line on a queue and return. One writer sends a whole group of lines in one write.

The cost of the direct way is the waiting. At 2,000 lines a second, that is 2,000 locks and 2,000 small writes every second. A batcher moves the waiting out of the request path, so callers only pay for a quick put.

*Diagram, Many threads in, one writer out: Many threads drop lines into one queue and carry on at once. One writer thread collects a batch, until it is full or a short wait is up, and writes it in one call. Only that writer touches the file.*
1. The checkout thread puts its line on the queue and goes back to work.
2. The refund thread does the same.
3. The fraud check thread does the same.
4. The writer takes the next lines off the queue, in order.
5. Once the batch is full or the wait is up, the writer moves on to write it.
6. One call sends the whole batch to the log file.

## How does the batch get written safely?

The locking lives in the queue, not in your code. Python's queue module is built for passing items between threads safely, and its Queue class handles the locks.

1. **Put:** Each thread calls log(), which puts its line on the queue. That takes a moment, and the thread goes back to its work.
2. **Collect:** The writer takes the first line, then keeps taking lines until it has 100 or until half a second has passed since the first one.
3. **Write:** The writer sends the whole batch to the file in one call. No other thread touches the file, so lines can't mix.
4. **Repeat:** It goes back to the queue and waits for the next batch.

The deadline matters. Without one, a quiet system would hold its first line until 99 more arrive, which could take hours. So the writer waits for the next line only until the deadline, then writes what it has.

Only the writer owns the file. Callers share the queue and nothing else, so there is no lock around the file to get wrong.

## What does a small working version look like?

This version uses only the standard library. It starts a worker thread, then four threads each log three lines. The demo waits up to 60 seconds, so every batch fills to four and the output is the same on every run. A real service would use about half a second.

```python
import atexit, queue, threading, time
class BatchingLogger:
    def __init__(self, sink, max_batch=100, max_wait=0.5):
        self.q, self.sink, self.max_batch, self.max_wait = queue.Queue(), sink, max_batch, max_wait
        self.worker = threading.Thread(target=self._run, daemon=True)
        self.worker.start()
        atexit.register(self.close)
    def log(self, line):  # any thread may call this
        self.q.put(line)
    def close(self):  # write what is queued, then stop
        self.q.put(None)
        self.worker.join()
    def _run(self):  # one thread writes, so lines never interleave
        while True:
            batch = [self.q.get()]
            deadline = time.monotonic() + self.max_wait
            while batch[-1] is not None and len(batch) < self.max_batch:
                try:
                    batch.append(self.q.get(timeout=max(0, deadline - time.monotonic())))
                except queue.Empty:
                    break
            lines = [b for b in batch if b is not None]
            if lines: self.sink(lines)
            if None in batch: return
batches = []; logger = BatchingLogger(sink=batches.append, max_batch=4, max_wait=60)
threads = [threading.Thread(target=lambda n=n: [logger.log(f"{n}-{i}") for i in range(3)]) for n in range(4)]
for t in threads: t.start()
for t in threads: t.join()
logger.close()
print([len(b) for b in batches], sum(map(len, batches)))
```

Output:

```text
[4, 4, 4] 12
```

The output shows 12 lines in three batches of four. The sink, the function that receives each batch, was called three times instead of twelve. Each line arrived once, and no line was cut in half, because only the writer thread calls the sink.

> **Tip:** Test with many threads and count the lines at the end. A test with one thread can pass even when the design is wrong.

## What happens at shutdown, and can lines get lost?

Yes, if you are careless. Lines still in the queue when the program exits are lost unless the writer empties them first. So close() puts a stop marker at the end of the queue, and waits for the writer to reach it.

*Diagram, Shutdown: the last lines still get written: close() adds a stop marker behind every queued line. The writer works through the lines in order and stops only at the marker, so lines logged before close() are written when the program exits normally.*
1. close() adds a stop marker to the end of the queue.
2. The marker sits behind every line that was logged before it.
3. The writer writes those lines, then stops at the marker.

> "Daemon threads are abruptly stopped at shutdown" (Python threading docs)
>
> "upon normal program termination (for instance, if sys.exit() is called or the main module's execution completes)" (Python atexit docs)

The code covers both sides. The worker is a daemon thread, a background thread that Python can stop at exit without waiting for it, so a forgotten logger can't keep the program alive for ever. Daemon threads are stopped abruptly, so close() is also registered with atexit, a Python hook that runs code when the program exits normally. That hook runs while the worker is still alive, so the queue is emptied first. close() calls join(), which waits until that thread has finished. If a program never calls close(), atexit still runs it on a normal exit, so the last lines are written.

> **Tip:** A hard kill (a power cut, or the kill signal SIGKILL) or an os._exit() call skips the exit hook, so lines still in memory are lost. Say so in the design, and flush often so little sits in memory.

### How would you run this in a real service?

- **Cap the queue:** Give queue.Queue a maxsize. Once it is full, put() blocks, so a slow disk pushes back on callers instead of filling memory.
- **Handle sink errors:** The sketch stops the writer if the sink raises. A real writer catches the error, retries a set number of times, and counts the lines it had to drop.
- **Watch the numbers:** Track the queue depth and the dropped lines, so a slow disk shows up on a chart before it hurts users.
- **Run it off the request path:** Python's logging module offers QueueHandler for the same idea, with the slow handler on its own thread. Use it if the stdlib fits.

## What does the interviewer want to hear?

**A strong answer covers**

- [ ] One writer thread owns the file, so lines can't interleave.
- [ ] Callers use a thread-safe queue and return straight away.
- [ ] Batches flush on size and on a time limit, so no line waits for ever.
- [ ] Shutdown sends a stop marker, empties the queue, and joins the writer.
- [ ] Named trade-offs: an unbounded queue, sink errors, and loss on a hard kill.

**Common traps**

- Trap: "Put a lock around the file, and every thread writes directly." Better: That is safe but slow: each line waits for the lock and makes its own write. Hand lines to one writer through a queue.
- Trap: "Give each thread its own log file." Better: The logs split into pieces that are out of order and hard to join. One file, one writer.
- Trap: "Keep the lines in a list and write them when the program ends." Better: A crash or a kill loses everything still in memory. Flush on size and on a short time limit.

## Can you spot the problem in this batcher?

**Spot the stall:** In a version with no timeout on get(), a quiet payments service logs one line every few minutes. Which line keeps the writer waiting for hours?

A. self.q.put(line)
B. batch.append(self.q.get())
C. self.sink(lines)
D. self.worker.join()

**Answer:** B. With no timeout, the writer waits for a 100th line that may never come. The demo gives get() a timeout, so the batch is written when the wait ends.

**Quick check:** 64 threads log at peak. Which design is safe and still fast?

A. Each thread opens the file and writes its own line
B. A shared list, with the writer reading it and no lock
C. A thread-safe queue, with one writer thread that writes batches
D. A global counter that numbers the lines

**Answer:** C. The queue does the locking and the single writer keeps lines whole. The other options either race or make every thread wait on the file.

## Can you answer these from memory?

**Flash cards**

- **Why does one writer thread keep lines from mixing?** Only that thread touches the file, so each batch is written whole, one call at a time.
- **What does a thread-safe queue give you?** Its own locks, so many threads can add and take items without a lock of your own.
- **Why batch the writes?** One write for many lines means far fewer trips to the disk or the log shipper.
- **What is a stop marker for?** It sits behind every queued line, so the writer finishes them all before it stops.
- **Why cap the queue?** A slow disk otherwise fills memory. A cap makes callers wait instead, which shows the problem early.
- **Why does the writer need a time limit?** On a quiet system a few lines would wait for hours. The limit flushes whatever has arrived.

## Likely follow-up questions

- Q479 Implement an LRU cache. https://designervenkat.online/interview/ai/implement-an-lru-cache
- Q478 Parse and validate LLM JSON, retrying on failure. https://designervenkat.online/interview/ai/parse-and-validate-llm-json-retrying-on-failure
- Q473 Run an LLM over 50,000 documents with concurrency limits and 429 retries. https://designervenkat.online/interview/ai/run-an-llm-over-50000-documents
- Q471 Implement a rate limiter (per-user and global). https://designervenkat.online/interview/ai/implement-a-rate-limiter
- Q482 Write a minimal agent loop with tool dispatch. https://designervenkat.online/interview/ai/write-a-minimal-agent-loop-with-tool-dispatch
