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.
12 min readAdvancedOccasional · estimateFacts checked 27 November 2026
Say it out loud
Read it once, then say it without looking. Start with the short one; use the long one when they ask you to go deeper.
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.
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.
Key words
- 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.
Many threads in, one writer out
Worker threads
Checkout thread
Sends each payment audit line
Refund thread
Sends each refund audit line
Fraud check thread
Sends each fraud check line
Thread-safe queue
lines wait here, in order
One writer thread
Collect a batch
up to 100 lines, or 0.5 s
Write the batch
one call for many lines
Log file
no two lines mixed up
- 1The checkout thread puts its line on the queue and goes back to work.
- 2The refund thread does the same.
- 3The fraud check thread does the same.
- 4The writer takes the next lines off the queue, in order.
- 5Once the batch is full or the wait is up, the writer moves on to write it.
- 6One 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.
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
[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.
Shutdown: the last lines still get written
close() is called
the program is finishing
Stop marker queued
it lands behind every line
Writer empties queue
batches go out until the marker
Writer exits
lines logged before close() are written
- 1close() adds a stop marker to the end of the queue.
- 2The marker sits behind every line that was logged before it.
- 3The 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."
BetterThat 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."
BetterThe 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."
BetterA 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?
Quick check
64 threads log at peak. Which design is safe and still fast?
Can you answer these from memory?
Flash cards · tap a card to flip it
What will they ask next?
Last updated on 27 November 2026
Building a logging or audit trail for an AI app?
Venkat designs and builds AI products and agents, including the system behind the screen. Book a short call and say what you need.