Multithreaded Logger with Async Flush
MediumConcurrencyProducer-ConsumerBlockingQueueAsyncThread PoolBuffer
Problem Statement
Design a high-performance, thread-safe logger that decouples log production (caller threads) from log I/O (disk/network writes) using an asynchronous flush mechanism. The logger must handle thousands of log calls per second without blocking the calling threads.
class AsyncLogger {
public enum Level { DEBUG, INFO, WARN, ERROR }
public AsyncLogger(int bufferCapacity, Level minLevel, LogSink sink) {}
public void log(Level level, String message) {}
public void flush() throws InterruptedException {} // Force flush and wait
public void shutdown() throws InterruptedException {}
public long getDroppedLogCount() {}
public long getTotalLogCount() {}
}
interface LogSink {
void write(String formattedLogLine);
void flush();
}
Key Entities
- Log buffer:
BlockingQueue<LogEntry>holding entries pending flush. - Writer thread: Single background thread draining the queue to the LogSink.
- LogEntry: Immutable record of (timestamp, level, message, thread-name).
- Drop policy: When buffer is full, either drop log (non-blocking) or block caller.
Requirements
log()must never block calling threads — prefer dropping over blocking.- Background writer thread handles batching and I/O.
flush()must ensure all currently buffered logs are written before returning.shutdown()flushes all remaining logs then stops the writer thread.- Track dropped log count for monitoring.
Asked at: Amazon, Google, Microsoft, Uber, Netflix, Flipkart, Paytm
!Constraints
- 1 ≤ bufferCapacity ≤ 100,000
- log() must complete in O(1) — never blocks (uses offer(), not put()).
- Multiple threads call log() concurrently from different parts of the application.
- Writer thread batches up to 100 entries per flush cycle for efficiency.
- Timestamp precision: millisecond.
Output
Run or submit your code to see output here.