Lock-Free Background C++ Logger with Deferred Formatting
Hard · System Design · Software Engineer · Technical Screen
Prompt
Design and implement a concurrent C++ logging library in which application threads hand off log calls to a dedicated background worker thread that executes {fmt}-style string interpolation and writes formatted lines to output destinations.
Producer threads invoke a variadic logging interface accepting {fmt}-compatible format strings and arbitrary formattable arguments—for example, LOG_INFO(log, "desk={} seq={} px={:.4f}", desk_buf, seq_no, mid_px) where desk_buf may be a temporary stack buffer—and pass captured records across threads through an already-supplied bounded lock-free queue (LockFreeQueue<T>). Minimizing heap allocations or RAM footprint is explicitly out of scope for the baseline design.
Detail the caller-facing C++ API, the internal event structure, the end-to-end producer-to-consumer execution model, and runnable demonstrations of race-free flush(), graceful shutdown(), and fault containment (malformed runtime format strings, sink write/flush failures, allocation errors, and queue saturation).
Scope & Expectations
- Caller-facing C++ API & level gating: Compile-time
{fmt}format verification, cheap disabled-level short-circuiting, sink interface, backpressure options, and lifecycle controls. - Type-erased event layout & argument lifetime safety: Packing arbitrary variadic argument tuples and control commands behind a uniform queue element type without dangling C-strings or non-owning views.
- Lock-free producer–consumer flow: Fast
noexceptproducer enqueue path, single-worker consumer loop with buffered sink writes, and configurable overflow policies (Blockvs.DropNewest). - Deterministic flush, shutdown, & error containment: Ordering
flush()andshutdown()safely against concurrent callers, draining stragglers, and isolating formatting or I/O failures without terminating the process.
Step-by-step walkthrough
Clarify requirements and scope
Unlike distributed web design questions, this system is a concurrent C++ library inside a single process. In latency-sensitive software—such as automated trading engines, game engines, or real-time audio pipelines—a business thread cannot pause for hundreds of nanoseconds to format floats into text or microseconds to write to disk. Our goal is to move both string formatting and I/O off the caller's thread onto a single background worker thread, connected by a provided lock-free multi-producer multi-consumer (MPMC) queue (a fixed-capacity concurrent buffer where multiple threads push and pop safely using atomic CPU instructions instead of OS mutex locks).
Functional requirements
- Variadic formatted logging:
log(level, "fmt {} string", args...)accepting{fmt}-style format strings, any number of formattable arguments, and runtime log-level filtering (Trace,Debug,Info,Warn,Error,Critical,Off). - Deferred formatting and writing: The calling thread checks the level, captures the arguments, and enqueues an event. Only the background thread formats text and writes to sinks (output destinations such as files or
stderr). - Lock-free hand-off: Producer threads pass events to the background thread through the provided bounded lock-free queue.
- Flush and shutdown:
flush()blocks the caller until every message logged before it is written out to the sinks;shutdown()drains all remaining queued messages, flushes the sinks, and stops the background thread cleanly. - Explicit error handling: Bad runtime format strings, sink I/O errors, allocation failures, and dropped messages are caught and reported—never silently ignored and never thrown back into the caller's business logic.
Non-functional requirements & explicit assumptions
- Fast, non-throwing hot path:
log()isnoexcept, takes no mutex lock, makes no I/O system call in the common case, and finishes in roughly 40–80 nanoseconds. - Heap usage is allowed: The prompt explicitly states we do not optimize for heap footprint, so allocating one heap object per logged message (plus string copies) is acceptable. However, the queue itself is bounded so memory cannot grow to infinity if a disk stalls.
- Per-thread ordering: Messages logged by a single thread appear in the output in the exact order that thread logged them.
- Provided queue contract: We assume
LockFreeQueue<T>is a bounded MPMC ring buffer offering non-blockingbool try_push(const T&)(returnsfalsewhen full) andbool try_pop(T&)(returnsfalsewhen empty), preserving FIFO order per producer. Storing raw 8-byteLogEvent*pointers keeps queue slots tiny and ensures a failedtry_pushnever leaves an event half-moved. - Backpressure (overflow) policy: Configurable per logger.
Block(default) waits for space so zero messages are lost;DropNewestdrops immediately and increments an atomic counter for ultra-low-latency threads where stalling is worse than losing a log line. - Durability of
flush():flush()callsfflush, handing buffered bytes to the operating system's page cache (in-memory disk cache managed by the OS kernel) so logs survive an application crash. Callingfsyncto force physical disk writes takes milliseconds and is an opt-in sink setting.
- Variadic formatted logging:
Back-of-the-envelope numbers
Even inside one process, quick numbers tell us whether a single background thread can keep up and how large the queue should be.
Producer hot path (cost paid by the calling thread per log() call) 1 relaxed atomic load (level check): ~1 ns (if disabled, stop here!) Read clock (system_clock::now): ~15-20 ns (vDSO user-space read on Linux) 1 heap allocation for the event + arg copies: ~20-40 ns with a thread-caching allocator 1 atomic compare-and-swap (queue try_push): ~10-20 ns uncontended (more under 16+ threads) Total on caller thread: ~45-80 ns per enabled log line Consumer throughput (single background worker thread) Format timestamp prefix + message into reusable buffer + write to 64 KB file buffer: ~400-500 ns per ~110-byte line -> ~2.0M lines/s (~220 MB/s into OS page cache) Queue capacity and burst headroom 65,536 slots x 8-byte pointer = 512 KB for the ring buffer itself 65,536 heap events x ~200 B average when full = ~13 MB peak queued memory Burst absorption: if 16 threads burst at 3M msgs/s while consumer drains at 2M msgs/s, queue fills at net 1M msgs/s -> 65,536 / 1,000,000 = ~65 ms of burst cushionWhat these numbers tell us:
- One consumer thread is plenty. Very few single processes sustain more than 200 MB/s of text logs; keeping a single consumer thread avoids locking on sinks and preserves message order automatically.
- A queue only absorbs bursts, never sustained overload. If producers generate 3M lines/s forever while the disk only accepts 500K lines/s, any finite queue eventually fills up. That is why we must explicitly support
BlockandDropNewest.
Public API and compile-time format checks
Before looking at the internals, let's design an API that is hard to misuse:
fmt::format_string<A...>validates the format string against the argument types at compile time in C++20. WritingLOG_INFO(log, "{} {}", 42)fails to compile instead of failing in production.- Wrapper macros (
ALOG,LOG_INFO, ...) do two jobs a normal C++ function cannot:- They check
should_log(level)before evaluating arguments, soLOG_DEBUG(log, "{}", expensive_dump())costs a single 1 ns atomic load whenDebugis turned off. - They capture
__FILE__and__LINE__as compile-time constants (const char*string literal in static memory, zero copying required).
- They check
- Single-threaded
Sinkinterface: Only the background thread callswrite()andflush()(orshutdown()after joining that thread), so custom sinks need zero internal locks.
namespace alog { enum class Level : std::uint8_t { Trace, Debug, Info, Warn, Error, Critical, Off }; enum class OverflowPolicy : std::uint8_t { Block, // caller waits for a free queue slot: lossless, but can stall if disk lags DropNewest, // caller returns immediately and increments dropped(): never stalls caller }; struct Options { std::size_t queue_capacity = 65536; OverflowPolicy overflow = OverflowPolicy::Block; Level min_level = Level::Info; std::chrono::milliseconds flush_every{200}; }; class Sink { public: virtual ~Sink() = default; virtual void write(std::string_view line) = 0; virtual void flush() = 0; }; class Logger { public: explicit Logger(std::vector<std::unique_ptr<Sink>> sinks, Options opts = {}); ~Logger(); // calls shutdown() and drains any stragglers Logger(const Logger&) = delete; Logger& operator=(const Logger&) = delete; bool should_log(Level level) const noexcept { return static_cast<std::uint8_t>(level) >= min_level_.load(std::memory_order_relaxed); } void set_level(Level level) noexcept { min_level_.store(static_cast<std::uint8_t>(level), std::memory_order_relaxed); } // Captures arguments and pushes one event pointer; never formats, blocks on I/O, or throws. template <typename... A> void log(Level level, const char* file, int line, fmt::format_string<A...> format, A&&... args) noexcept; // Blocks until all messages logged on this thread prior to flush() are written and flushed. // Returns false if the deadline expires first (for example, on a hung network filesystem). bool flush(std::chrono::milliseconds timeout = std::chrono::seconds(5)); // Stops accepting new messages, drains the queue, flushes sinks, and joins the worker. void shutdown(); std::uint64_t dropped() const noexcept { return dropped_.load(std::memory_order_relaxed); } // ... private members shown in Step 5 }; } // namespace alog #define ALOG(logger, level, ...) \ do { \ if ((logger).should_log(level)) { \ (logger).log((level), __FILE__, __LINE__, __VA_ARGS__); \ } \ } while (0) #define LOG_INFO(logger, ...) ALOG(logger, ::alog::Level::Info, __VA_ARGS__) #define LOG_WARN(logger, ...) ALOG(logger, ::alog::Level::Warn, __VA_ARGS__) #define LOG_ERROR(logger, ...) ALOG(logger, ::alog::Level::Error, __VA_ARGS__)A minimal buffered
FileSinkuses a 64 KBstdiobuffer so small lines coalesce in user space instead of triggering a kernelwrite()system call on every message:class FileSink final : public Sink { public: explicit FileSink(const std::string& path) : file_(std::fopen(path.c_str(), "a")) { if (file_ == nullptr) { throw std::system_error(errno, std::generic_category(), "open " + path); } std::setvbuf(file_, nullptr, _IOFBF, 1 << 16); // 64 KB user-space write buffer } ~FileSink() override { if (file_ != nullptr) { std::fclose(file_); } } FileSink(const FileSink&) = delete; FileSink& operator=(const FileSink&) = delete; void write(std::string_view line) override { if (std::fwrite(line.data(), 1, line.size(), file_) != line.size()) { throw std::system_error(errno, std::generic_category(), "fwrite"); } } void flush() override { if (std::fflush(file_) != 0) { throw std::system_error(errno, std::generic_category(), "fflush"); } } private: std::FILE* file_; };Log event structure and type erasure
Here is the first design puzzle: one call logs
(int, double), the next logs(std::string), andflush()sends a control signal—yetLockFreeQueuemust have a single element type.We solve this with type erasure (hiding many different concrete argument types behind one common base-class interface):
LogEventis a non-template base struct holding common metadata (level,time,thread,file,line,format_str) plus avirtual void format_message(fmt::memory_buffer&)method.MessageEvent<Ts...>is a small template subclass that stores the captured arguments in astd::tuple<Ts...>with their exact types and overridesformat_messageto unpack that tuple intofmt::vformat_to.- Control commands (
FlushandStop) are plainLogEventinstances pushed into the exact same queue, so they naturally stay ordered relative to log messages!
Queue slot (8 bytes) Heap object +------------+ +-----------------------------------------+ | LogEvent* | ------------> | LogEvent (base) | +------------+ | kind = Message, level = Info | | time, thread, file, line, format_str | +-----------------------------------------+ | MessageEvent<int, std::string> (derived)| | args = std::tuple{704, "MSFT"} | +-----------------------------------------+struct LogEvent { enum class Kind : std::uint8_t { Message, Flush, Stop }; Kind kind = Kind::Message; Level level = Level::Info; std::chrono::system_clock::time_point time; // stamped on the caller thread, not the writer! std::uint32_t thread = 0; const char* file = ""; // points to __FILE__ literal in static storage int line = 0; std::string format_str; // owned copy: fmt::runtime(s) may be temporary std::shared_ptr<std::promise<void>> flushed; // shared so a timed-out flush() never dangles virtual ~LogEvent() = default; virtual void format_message(fmt::memory_buffer&) {} }; template <typename... Ts> struct MessageEvent final : LogEvent { std::tuple<Ts...> args; explicit MessageEvent(Ts&&... values) : args(std::move(values)...) {} void format_message(fmt::memory_buffer& out) override { std::apply( [&](auto&... values) { fmt::vformat_to(std::back_inserter(out), format_str, fmt::make_format_args(values...)); }, args); } };Why every field is shaped this way:
timeis recorded on the producer thread so timestamps reflect when the event happened, not 50 ms later when the background thread wrote it.format_stris copied into astd::stringbecause while most callers pass string literals,{fmt}also allows dynamic strings viafmt::runtime(temp_str)whose storage may die before the background thread runs.flushedis wrapped instd::shared_ptr: if a caller callsflush(5ms), times out, and returns, its stack frame is destroyed; keeping thepromisein ashared_ptrensures the background thread will not write into freed stack memory when it eventually reaches theFlushevent.
High-level architecture and producer flow
Let's trace how producer threads, the lock-free queue, and the single background consumer fit together:
Producer threads (many) Background worker thread (one) ----------------------- ------------------------------ LOG_INFO(log, "fill {} @ {}", qty, px) | | 1. should_log(level)? (relaxed load) | 2. capture args -> owning types (copy char*/string_view to std::string) | 3. new MessageEvent{time, thread_no, file, line, format_str, tuple(args)} v try_push(LogEvent*) -----> [ LockFreeQueue<LogEvent*> ] -----> try_pop(raw) | if full: (65,536 8-byte slots) | | - DropNewest: dropped_++, delete event, return v | - Block: spin -> yield -> sleep(50us), retry Message: format prefix + body v -> write to each sink return in ~45-80 ns Flush: flush sinks, fulfill promise Stop: drain remaining, flush, exit Idle: every 200ms report drops & flushPointer ownership follows a strict single-owner relay so nothing ever leaks or double-frees:
log()creates the event insidestd::unique_ptr<LogEvent> ev.- If
queue_.try_push(ev.get())succeeds,ev.release()hands ownership to the queue. Iftry_pushfails and we drop (or an exception is caught),ev's destructor frees the event automatically. - When the worker pops
LogEvent* raw, it immediately adopts it intostd::unique_ptr<LogEvent> ev(raw).
Notice a subtle concurrency detail in
push_or_drop_on_stop: ifBlockmode encounters a full queue whileshutdown()is running, the worker may exit after draining, so spinning blindly forever would deadlock! Checkingstopping_inside the retry loop prevents that deadlock cleanly.template <typename... A> void Logger::log(Level level, const char* file, int line, fmt::format_string<A...> format, A&&... args) noexcept { if (stopping_.load(std::memory_order_acquire)) { dropped_.fetch_add(1, std::memory_order_relaxed); return; } try { auto ev = std::make_unique<MessageEvent<detail::captured_t<A>...>>( detail::capture(std::forward<A>(args))...); ev->level = level; ev->time = std::chrono::system_clock::now(); ev->thread = detail::this_thread_number(); ev->file = file; ev->line = line; fmt::string_view text = format; ev->format_str.assign(text.data(), text.size()); LogEvent* raw = ev.get(); if (queue_.try_push(raw)) { ev.release(); // ownership transferred to the queue return; } if (opts_.overflow == OverflowPolicy::DropNewest) { dropped_.fetch_add(1, std::memory_order_relaxed); return; // ev deletes the unpushed event } push_or_drop_on_stop(std::move(ev)); } catch (...) { // Never allow bad_alloc or a throwing copy constructor to escape into business code. dropped_.fetch_add(1, std::memory_order_relaxed); } } void Logger::push_or_drop_on_stop(std::unique_ptr<LogEvent> ev) { LogEvent* raw = ev.get(); int attempt = 0; while (!queue_.try_push(raw)) { if (stopping_.load(std::memory_order_acquire)) { dropped_.fetch_add(1, std::memory_order_relaxed); return; // shutdown began while waiting; avoid spinning if worker already exited } detail::wait_for_room(attempt++); } ev.release(); }When waiting for room, we spin briefly first (the consumer normally frees a slot within a couple of microseconds), then yield the CPU slice, then sleep 50 µs so we do not burn CPU if a disk is genuinely slow:
namespace detail { inline std::uint32_t this_thread_number() { static std::atomic<std::uint32_t> next{1}; thread_local std::uint32_t number = next.fetch_add(1, std::memory_order_relaxed); return number; } inline void wait_for_room(int attempt) { if (attempt < 64) { return; // brief busy-spin: avoids OS scheduler latency for tiny micro-bursts } if (attempt < 128) { std::this_thread::yield(); return; } std::this_thread::sleep_for(std::chrono::microseconds(50)); } inline void idle_wait(int attempt) { if (attempt < 100) { std::this_thread::yield(); return; } std::this_thread::sleep_for(std::chrono::milliseconds(1)); } inline const char* level_name(Level level) { static const char* names[] = {"TRACE", "DEBUG", "INFO", "WARN", "ERROR", "CRIT", "OFF"}; return names[static_cast<int>(level)]; } } // namespace detailHere are the private members of
Loggerand its constructor. Noticeworker_is declared very last: C++ initializes class members in declaration order, so startingworker_last guarantees thatqueue_,sinks_, and all atomics already exist before the background thread touches them:// Inside class Logger (private): void push_or_drop_on_stop(std::unique_ptr<LogEvent> ev); void push_control_blocking(std::unique_ptr<LogEvent> ev); bool push_until(std::unique_ptr<LogEvent> ev, std::chrono::steady_clock::time_point deadline); void run(); void handle(LogEvent& ev); void drain(); void write_message(LogEvent& ev); void format_prefix(const LogEvent& ev); void write_to_sinks(); void flush_sinks(); void report_drops(); void report_sink_error(const char* what); void stop_worker(); Options opts_; LockFreeQueue<LogEvent*> queue_; std::vector<std::unique_ptr<Sink>> sinks_; std::atomic<std::uint8_t> min_level_; std::atomic<bool> stopping_{false}; std::atomic<std::uint64_t> dropped_{0}; std::mutex control_; // serializes flush() and shutdown() only; never touched by log() std::once_flag shutdown_once_; std::promise<void> stopped_promise_; std::shared_future<void> stopped_; // Owned exclusively by worker_ while running (and by shutdown/~Logger after worker_.join()): fmt::memory_buffer line_; bool dirty_ = false; std::uint64_t reported_drops_ = 0; std::uint64_t sink_errors_ = 0; std::chrono::steady_clock::time_point last_error_report_{}; std::thread worker_; // MUST be last: started only after all fields above are liveLogger::Logger(std::vector<std::unique_ptr<Sink>> sinks, Options opts) : opts_(opts), queue_(opts.queue_capacity), sinks_(std::move(sinks)), min_level_(static_cast<std::uint8_t>(opts.min_level)) { stopped_ = stopped_promise_.get_future().share(); worker_ = std::thread([this] { run(); }); }Deep dive 1: Capturing arguments safely for deferred formatting
Deferred formatting introduces a classic lifetime trap. Watch what happens if
log()naively stores every argument with its decayed type (std::decay_t<T>):Caller thread Background worker thread ------------- ------------------------ void on_order(int id) { char sym[16]; snprintf(sym, sizeof(sym), "SYM%d", id); LOG_INFO(log, "sym={}", sym); // sym decays to const char*! } // <-- sym's stack memory dies right here! // 2 ms later, worker pops event: // reads dangling const char* -> garbage or crash!Because formatting runs later on another thread, every captured argument must own its underlying bytes before
log()returns:namespace detail { template <typename T> auto capture(T&& value) { using D = std::decay_t<T>; if constexpr (std::is_same_v<D, const char*> || std::is_same_v<D, char*>) { // Covers char*, const char*, char[N], and string literals (via array-to-pointer decay). const char* text = value; return text != nullptr ? std::string(text) : std::string("(null)"); } else if constexpr (std::is_same_v<D, std::string_view> || std::is_same_v<D, fmt::string_view>) { // Views borrow memory without owning it; copy the characters now. return std::string(value.data(), value.size()); } else { // Numbers, std::string, and user value types: move temporaries, copy lvalues. return D(std::forward<T>(value)); } } template <typename T> using captured_t = decltype(capture(std::declval<T>())); } // namespace detailLet's verify every argument category and document what still requires caller care:
- Primitives (
int,double, enums) andstd::string: Moved if passed as a temporary, copied if passed as a variable, so mutating the variable on the next line never changes the logged text. - C-strings (
char*,const char*, stackchar buf[32]) andstring_view: Converted immediately to an owningstd::string. Passingnullptrsafely records"(null)"instead of triggering undefined behavior instrlen. - Documented boundaries of automatic capture:
- Non-owning range views (
std::span,fmt::join(vec, ",")) hold pointers into external containers; callers should pass the owning container or pre-format withfmt::format. - Pointer format specifiers (
"{:p}"): sinceconst char*becomesstd::stringin storage, printing an address requiresstatic_cast<const void*>(ptr). - Custom
fmt::formatter<MyType>: runs on the background thread against the copiedMyType, so the formatter itself must not touch unsynchronized global state or dereference raw pointers insideMyType.
- Non-owning range views (
- Primitives (
Deep dive 2: The background consumer loop and buffered I/O
Three design choices govern the worker thread in
Logger::run():- How to wait when the queue is empty:
- Busy-spinning wastes 100% of a CPU core even when the app is idle.
std::condition_variablewakes immediately, but requires producers to notify it—and avoiding the classic "lost wake-up" race requires either a mutex on the producer path or tricky memory fences on everylog()call.- Polling with progressive backoff (chosen): yield for 100 empty checks, then sleep 1 ms. Producers pay zero notification overhead, and an idle logger wakes briefly once per millisecond (at most 1 ms delay before writing, which never delays callers).
- Zero-allocation steady-state formatting: The worker reuses one
fmt::memory_buffer line_across all messages, clearing its size while keeping its heap capacity. - Fault-isolated writing: Periodic flushes happen every
flush_every(200 ms) only ifdirty_is true. Runtime format errors become visible[format error: ...]log lines, and failing sinks never block healthy sinks or spamstderr.
void Logger::run() { auto next_flush = std::chrono::steady_clock::now() + opts_.flush_every; int idle = 0; for (;;) { LogEvent* raw = nullptr; if (queue_.try_pop(raw)) { idle = 0; std::unique_ptr<LogEvent> ev(raw); if (ev->kind == LogEvent::Kind::Stop) { drain(); // write everything queued behind Stop before exiting report_drops(); flush_sinks(); return; } handle(*ev); } else { detail::idle_wait(idle++); } auto now = std::chrono::steady_clock::now(); if (now >= next_flush) { report_drops(); flush_sinks(); next_flush = now + opts_.flush_every; } } } void Logger::handle(LogEvent& ev) { try { if (ev.kind == LogEvent::Kind::Message) { write_message(ev); } else if (ev.kind == LogEvent::Kind::Flush) { report_drops(); flush_sinks(); ev.flushed->set_value(); } } catch (...) { // An uncaught exception escaping std::thread calls std::terminate()! report_sink_error("unexpected exception in logger worker"); } } void Logger::drain() { LogEvent* raw = nullptr; while (queue_.try_pop(raw)) { std::unique_ptr<LogEvent> ev(raw); handle(*ev); } }Formatting prefixes, isolating bad format strings, and rate-limiting sink errors:
void Logger::write_message(LogEvent& ev) { line_.clear(); format_prefix(ev); try { ev.format_message(line_); } catch (const std::exception& e) { // Triggered by a bad fmt::runtime() string or a throwing user formatter. line_.clear(); format_prefix(ev); fmt::format_to(std::back_inserter(line_), "[format error: {}] format string: \"{}\"", e.what(), ev.format_str); } line_.push_back('\n'); write_to_sinks(); } void Logger::format_prefix(const LogEvent& ev) { using namespace std::chrono; auto since_epoch = ev.time.time_since_epoch(); auto secs = floor<seconds>(since_epoch); auto micros = duration_cast<microseconds>(since_epoch - secs).count(); std::time_t t = static_cast<std::time_t>(secs.count()); std::tm utc{}; gmtime_r(&t, &utc); // POSIX thread-safe UTC conversion (gmtime_s on Windows) fmt::format_to(std::back_inserter(line_), "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}.{:06}Z {:<5} [t{}] {}:{} ", utc.tm_year + 1900, utc.tm_mon + 1, utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec, micros, detail::level_name(ev.level), ev.thread, ev.file, ev.line); } void Logger::write_to_sinks() { std::string_view text(line_.data(), line_.size()); for (auto& sink : sinks_) { try { sink->write(text); } catch (const std::exception& e) { report_sink_error(e.what()); } catch (...) { report_sink_error("unknown sink write failure"); } } dirty_ = true; } void Logger::flush_sinks() { if (!dirty_) { return; } for (auto& sink : sinks_) { try { sink->flush(); } catch (const std::exception& e) { report_sink_error(e.what()); } catch (...) { report_sink_error("unknown sink flush failure"); } } dirty_ = false; } void Logger::report_drops() { std::uint64_t total = dropped_.load(std::memory_order_relaxed); if (total == reported_drops_) { return; } line_.clear(); fmt::format_to(std::back_inserter(line_), "alog: dropped {} messages\n", total - reported_drops_); reported_drops_ = total; write_to_sinks(); } void Logger::report_sink_error(const char* what) { ++sink_errors_; auto now = std::chrono::steady_clock::now(); if (now - last_error_report_ < std::chrono::seconds(10)) { return; // rate-limit to 1 stderr message per 10s so a full disk never floods stderr } last_error_report_ = now; std::fprintf(stderr, "alog: sink error: %s (%llu total errors)\n", what, static_cast<unsigned long long>(sink_errors_)); }- How to wait when the queue is empty:
Deep dive 3: Race-free flush, shutdown, and end-to-end demo
Most bugs in asynchronous loggers live in
flush()andshutdown(), where control calls race against concurrentlog()calls.Why
flush()uses an in-band marker instead ofwhile (!queue_.empty()):Timeline if flush() merely waited for queue_.empty(): t=0: Thread 1 pushes Msg A. t=1: Worker pops Msg A -> queue is now EMPTY! (Worker has NOT called fwrite/fflush yet!) t=2: Thread 1 checks queue_.empty() == true and returns early -> app reads incomplete file! Timeline with an in-band Flush event: t=0: Thread 1 pushes Msg A, then pushes Flush{promise}. t=1: Worker pops Msg A -> formats -> fwrite(). t=2: Worker pops Flush -> fflush() -> promise.set_value() -> Thread 1 wakes up safely!Also notice that
flush(timeout)uses the same deadline for pushing the marker (push_until) AND waiting ondone.wait_until(deadline). Otherwise, if a hung network mount froze the worker and filled the queue, pushing theFlushmarker would block forever regardless oftimeout!bool Logger::flush(std::chrono::milliseconds timeout) { auto deadline = std::chrono::steady_clock::now() + timeout; std::future<void> done; { std::lock_guard<std::mutex> lock(control_); if (!stopping_.load(std::memory_order_relaxed)) { auto ev = std::make_unique<LogEvent>(); ev->kind = LogEvent::Kind::Flush; ev->flushed = std::make_shared<std::promise<void>>(); done = ev->flushed->get_future(); if (!push_until(std::move(ev), deadline)) { return false; // queue stayed full past deadline; ev cleans itself up } } } if (!done.valid()) { // Shutdown already started: wait for shutdown()'s final flush instead. return stopped_.wait_until(deadline) == std::future_status::ready; } return done.wait_until(deadline) == std::future_status::ready; } bool Logger::push_until(std::unique_ptr<LogEvent> ev, std::chrono::steady_clock::time_point deadline) { LogEvent* raw = ev.get(); int attempt = 0; while (!queue_.try_push(raw)) { if (std::chrono::steady_clock::now() >= deadline) { return false; } detail::wait_for_room(attempt++); } ev.release(); return true; }shutdown()and~Logger():std::call_oncemakesshutdown()idempotent—if two threads callshutdown(), one runsstop_worker()and the second blocks untilstop_worker()finishes. Insidestop_worker(),control_ensures noFlushmarker is ever pushed afterStop. Afterworker_.join(), the worker thread is gone, sostop_worker()(and~Logger()at destruction) can safely drain any last-nanosecondlog()call that passedstopping_ == falsejust before the flag flipped:void Logger::shutdown() { std::call_once(shutdown_once_, [this] { stop_worker(); }); } void Logger::push_control_blocking(std::unique_ptr<LogEvent> ev) { LogEvent* raw = ev.get(); int attempt = 0; while (!queue_.try_push(raw)) { detail::wait_for_room(attempt++); // worker_ is alive and popping until it sees Stop } ev.release(); } void Logger::stop_worker() { { std::lock_guard<std::mutex> lock(control_); stopping_.store(true, std::memory_order_release); auto stop = std::make_unique<LogEvent>(); stop->kind = LogEvent::Kind::Stop; push_control_blocking(std::move(stop)); } worker_.join(); // Catch any producer that read stopping_ == false right before it flipped and pushed late. drain(); report_drops(); flush_sinks(); stopped_promise_.set_value(); } Logger::~Logger() { shutdown(); drain(); report_drops(); flush_sinks(); }End-to-end demonstration:
int main() { std::vector<std::unique_ptr<alog::Sink>> sinks; sinks.push_back(std::make_unique<alog::FileSink>("app.log")); alog::Logger log(std::move(sinks), {.queue_capacity = 1024}); std::vector<std::thread> workers; for (int t = 0; t < 4; ++t) { workers.emplace_back([&log, t] { for (int i = 0; i < 10000; ++i) { char desk_buf[16]; std::snprintf(desk_buf, sizeof(desk_buf), "desk-%d", t); LOG_INFO(log, "desk={} seq={} px={:.4f}", desk_buf, i, 182.3750); // stack buffer copied safely } }); } for (auto& w : workers) w.join(); bool flushed = log.flush(); // true: all 40,000 lines are in app.log now LOG_WARN(log, "spread={:.4f}", 0.0125); log.shutdown(); // drains WARN line, flushes, joins worker LOG_INFO(log, "ignored after shutdown"); // increments dropped() std::printf("flushed=%d dropped=%llu\n", flushed, static_cast<unsigned long long>(log.dropped())); // flushed=1 dropped=1 }2026-11-30T09:15:01.104821Z INFO [t1] main.cpp:12 desk=desk-0 seq=0 px=182.3750 ... (40,000 lines total; each worker's seq=0..9999 appears strictly in order) 2026-11-30T09:15:01.129410Z WARN [t5] main.cpp:17 spread=0.0125 alog: dropped 1 messagesError handling, crashes, and scaling bottlenecks
Failure containment matrix:
Failure scenario How the logger responds Format string / arg mismatch (static) Fails at compile time via C++20 fmt::format_string<A...>.Bad fmt::runtimestring or throwing formatterCaught in write_message; emits[format error: ...]with the raw format string so context is preserved.Disk full / broken pipe on one sink Caught per sink; healthy sinks keep receiving lines; stderrnotice rate-limited to once per 10 s.Hung network mount ( fwriteblocks forever)Worker blocks in sink; queue fills; DropNewestcallers keep running,flush(timeout)returnsfalseat deadline. Sinks over network mounts should use non-blocking descriptors with timeouts.std::bad_allocor throwing copy constructorCaught in log(); incrementsdropped_;log()remainsnoexcept.Process crash ( SIGSEGV,abort)Unwritten queue items and user-space FILE*buffer (~200 ms max) are lost; mitigate by routingCriticallogs synchronously or storing raw events in a memory-mapped ring buffer.Process lifecycle traps to call out in an interview:
- Static destruction order: If a global
Loggeris destroyed while another global object's destructor still callsLOG_INFO, use-after-free occurs. Prefer creating the logger inmain()and callingshutdown()explicitly beforemain()exits. fork():fork()duplicates only the calling thread, leaving the child process without a background worker thread (and potentially with locked allocator mutexes). Construct the logger afterfork().
Scaling bottlenecks & next optimizations:
- Producer tail contention: Under 32+ threads logging simultaneously, every thread performs a compare-and-swap on the MPMC queue's tail cache line. Fix: give each producer thread a
thread_localsingle-producer single-consumer (SPSC) queue and let the background thread poll them round-robin, merging by timestamp if cross-thread order matters. - Heap allocator pressure: Use
jemallocortcmallocso small allocations hit thread-local caches; if zero-allocation logging is ever required, replace heapMessageEvents with fixed 256-byte inline ring slots holding serialized argument bytes. - Timestamp prefix caching: Calling
gmtime_r2,000,000 times per second recomputes the sameYYYY-MM-DDTHH:MM:SSstring two million times inside one second. Cache the 19-byte date/second prefix on the worker thread and recompute it only whensecschanges, formatting just the 6-digit microseconds per line.
- Static destruction order: If a global
Summary of trade-offs
- Deferred formatting on the worker vs. eager formatting on the caller: Keeps
log()around 50 ns on business threads, at the cost of copying C-strings/string_views into owningstd::strings and forbidding dangling view wrappers. - Heap
LogEvent*per message vs. fixed-size inline byte ring: Supports arbitrary C++ types cleanly through one virtual call and keeps queue slots at 8 bytes; trades away allocator overhead (explicitly permitted by the problem). Blockvs.DropNewestoverflow policy:Blockprioritizes completeness for batch services;DropNewestprioritizes deterministic tail latency for real-time threads while surfacing drops explicitly in the log anddropped().- Backoff polling vs. condition variable: Keeps the producer path 100% free of mutexes and kernel wake syscalls, trading up to 1 ms of write delay after idle periods.
- In-band
Flush/Stopmarkers + control-only mutex: Gives exact happens-before ordering forflush()and race-freeshutdown()while keepinglog()completely lock-free.
- Deferred formatting on the worker vs. eager formatting on the caller: Keeps
Intuition & how it works
Think of a head chef calling out orders during a busy dinner rush. If the chef stopped cooking after every dish to walk to the back office, type up a formatted receipt, file it in a binder, and wait for the cabinet drawer to shut, the kitchen would grind to a halt. Instead, the chef jots the raw values onto a slip, drops it into a pass-through basket in a split second, and goes right back to cooking while a dedicated clerk in the back formats and files batches of receipts into the binder.
A synchronous logger makes every business thread act like that stalled chef: formatting numbers and timestamps into text takes hundreds of nanoseconds, and writing to disk can stall for microseconds or even milliseconds if the operating system flushes buffers. On the other hand, a naive asynchronous logger that simply pushes raw pointers or std::string_views into a queue fails catastrophically, because stack buffers on the caller thread disappear before the background thread wakes up to format them.
Walk through a tiny 4-event trace to see how our design stays both fast and safe:
- Thread 1 logs a stack buffer:
char desk_buf[] = "desk-0"; LOG_INFO(log, "desk={} seq={} px={:.4f}", desk_buf, 7, 182.3750);. The macro checks an atomic minimum level (Info >= Info), copies"desk-0"(convertingchar*into an owningstd::string),7, and182.3750plus the current timestamp into a heap-allocatedMessageEvent, pushes the 8-byteLogEvent*pointer into the lock-free MPMC queue (a fixed-size concurrent buffer where multiple producer and consumer threads push and pop using atomic CPU instructions instead of mutex locks), and returns in ~50 ns—even ifdesk_bufis overwritten on the very next line. - Thread 1 logs a disabled debug line:
LOG_DEBUG(log, "dump={}", slow_serialize());. Because the macro checksshould_log(Debug)before callinglog(),slow_serialize()is never even evaluated. - Background worker formats and batches: The single worker thread pops the
LogEvent*, formats the UTC microsecond prefix and"desk=desk-0 seq=7 px=182.3750\n"into a reusable buffer, and appends it to a 64 KB user-space file buffer—zero per-line kernel system calls. - Thread 1 calls
log.flush():flush()pushes a specialFlushmarker event into the same queue behind"desk=desk-0 seq=7 px=182.3750"and waits on its future. Once the worker pops that marker, it callsfflushto push buffered bytes to the operating system and fulfills the promise, guaranteeing every earlier line from Thread 1 is visible.
Key trade-offs
- Deferred formatting vs. formatting on the caller thread. Formatting on the background worker keeps
log()down to tens of nanoseconds (one allocation, small value copies, and one compare-and-swap, an atomic CPU instruction that updates a queue index only if no other thread just changed it). The trade-off is strict argument-lifetime rules: non-owning views likeconst char*andstd::string_viewmust be copied intostd::stringon the caller thread, and view wrappers likefmt::joincannot be captured safely without eager formatting. - Heap-allocated
MessageEventwith type erasure vs. fixed-size inline slots. Type erasure (hiding concrete template types likeMessageEvent<int, std::string>behind a singleLogEventbase pointer with one virtualformat_messagecall) handles any number and type of C++ arguments cleanly and keeps queue slots at 8 bytes. Pre-allocated fixed-size byte slots avoidmallocoverhead completely, at the cost of custom binary serialization and a fallback path for oversized messages. Blockvs.DropNewestbackpressure policy. Backpressure is how a system responds when producers outpace consumers and fill the bounded buffer.Blockguarantees zero lost log lines at the risk of stalling business threads when storage lags;DropNewestguarantees bounded caller latency at the cost of lost messages, which we make auditable viadropped()and periodic"alog: dropped N messages"lines.- Polling consumer with progressive backoff vs.
std::condition_variable. Yielding briefly and then sleeping 1 ms when the queue is empty keeps the producer hot path 100% free of mutexes and kernel wake-up calls, at the cost of up to ~1 ms extra delay before an idle logger writes a new line. - In-band
Flush/Stopcontrol events vs. out-of-band atomic flags. PushingFlushandStopmarkers through the queue itself orders them naturally behind earlier messages, which is what"flush everything logged so far"requires; a separate boolean flag cannot tell which queued messages arrived beforeflush()was called. fflushvs.fsynconflush().fflushcopies user-space buffered bytes to the OS page cache (kernel memory backing open files) in microseconds so logs survive a crash of our process;fsyncforces physical disk persistence across power loss but costs milliseconds per call, so it remains opt-in per sink.
Common mistakes
- Capturing non-owning pointers or views as-is: Storing
const char*pointing to a localchar buf[32]or storingstd::string_viewdirectly insidestd::tupleworks in toy tests where string literals are used, then crashes or prints corrupted memory under load when stack frames unwind before the worker formats the event. - Storing a
string_viewto the format string:fmt::runtime(dynamic_str)allows temporary runtime strings; failing to copyformat_strinto an ownedstd::stringleaves a dangling reference on the worker thread. - Implementing
flush()aswhile (!queue.empty()): As soon as the worker pops the last item, the queue is empty—even though the worker has not yet formatted that item or flushed the file buffer! Only an acknowledged in-bandFlushmarker guarantees completion. - Applying
flush(timeout)only to the future wait, not the queue push: If a network disk hangs, the worker freezes and the queue fills up; an unbounded blocking push of theFlushmarker hangs forever despite the caller passing a timeout. - Putting
std::promiseonflush()'s stack: Ifflush(timeout)times out and returns, its stack frame dies; when the worker eventually reaches theFlushevent and callsset_value(), it corrupts dead stack memory unless ownership is shared viastd::shared_ptr<std::promise<void>>. - Deadlocking in
Blockmode duringshutdown(): If a producer passesstopping_ == false, gets delayed whileshutdown()joins the worker, and then spins forever waiting for room in a full queue nobody is popping anymore, the process hangs. Re-checkingstopping_inside the full-queue retry loop eliminates this deadlock. - Letting exceptions escape the worker thread or
log(): An uncaughtfmt::format_erroror disk I/O exception escapingLogger::run()invokesstd::terminate()and crashes the entire application over a single bad log message. - Declaring
std::thread worker_beforequeue_orsinks_in the class: C++ initializes members in declaration order, so a thread declared first can start executingrun()beforequeue_has even been constructed.
Follow-up questions
- How would you eliminate per-message heap allocations if memory footprint and allocator latency did matter? Replace
LockFreeQueue<LogEvent*>with a pre-allocated ring buffer of fixed-size cache-aligned slots (for example, 256 bytes each). Onlog(), serialize the metadata, a function pointer to a static template decoder for<Ts...>, and the raw bytes of primitives and short strings directly into the slot; the worker calls that decoder pointer to reconstruct and format the arguments without touching the heap, falling back to heap allocation only for rare oversized messages. Ultra-low-latency trading loggers (such as NanoLog or Quill) go one step further by writing raw binary argument bytes straight to disk or shared memory and deferring string formatting entirely to an offline reader tool. - How can you avoid losing the last few log lines right before an abrupt crash such as SIGSEGV or abort? Because queued events and user-space
FILE*buffers live in process RAM, an abrupt crash loses up to ~200 ms of buffered output—often the exact clues needed to debug the crash. Practical defenses, from cheapest to strongest, are: routingErrorandCriticalmessages through an immediate synchronous write path alongside the queue; installing a best-effort signal handler (caveat: formatting andfwriteare not async-signal-safe and can deadlock if the crash occurred insidemalloc); or backing the ring buffer with a memory-mapped file (mmap) so the OS kernel preserves unwritten binary events in the page cache even after the process dies, allowing a separate crash-reporter process to format and flush them on restart. - Given that the supplied queue supports multiple consumers, why run a single background writer thread rather than several? A single consumer already formats and writes ~2 million lines per second, preserves per-thread FIFO log order automatically, and allows every
Sinkimplementation to be completely lock-free. With four consumers popping and formatting in parallel, two consecutive lines from the same thread can finish out of order and every sink must guardwrite()with a mutex, reintroducing contention. If heavy custom formatting ever saturates one CPU core, a staged pipeline works better: stamp each event with a sequence number, let multiple worker threads format into buffers in parallel, and have a single writer thread flush buffers to sinks in sequence order.
Follow-up questions
- How would you eliminate per-message heap allocations if memory footprint and allocator latency did matter?
- How can you avoid losing the last few log lines right before an abrupt crash such as SIGSEGV or abort?
- Given that the supplied queue supports multiple consumers, why run a single background writer thread rather than several?
Similar questions
- Bagging, Random Forests, Boosting, and the Bias-Variance Trade-off
- Expected Turns Until Zero Whole Tablets
- Raw vs. Smart Pointers in Modern C++
- Negative Return Skewness and Black-Scholes Call Pricing Terms
- Build and Cross-Validate a k-NN Classifier
- Balance Equalization Transfers and Flat Map Design
More Qube Research & Technologies interview questions
- Bagging, Random Forests, Boosting, and the Bias-Variance Trade-off Hard
- Expected Turns Until Zero Whole Tablets Hard
- Raw vs. Smart Pointers in Modern C++ Hard Pro
- Negative Return Skewness and Black-Scholes Call Pricing Terms Hard Pro
- Build and Cross-Validate a k-NN Classifier Hard Pro
- Balance Equalization Transfers and Flat Map Design Medium Pro
- Even Integer Redistribution and Flat Map Iterators Medium Pro