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 noexcept producer enqueue path, single-worker consumer loop with buffered sink writes, and configurable overflow policies (Block vs. DropNewest).
  • Deterministic flush, shutdown, & error containment: Ordering flush() and shutdown() safely against concurrent callers, draining stragglers, and isolating formatting or I/O failures without terminating the process.

Step-by-step walkthrough

  1. 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() is noexcept, 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-blocking bool try_push(const T&) (returns false when full) and bool try_pop(T&) (returns false when empty), preserving FIFO order per producer. Storing raw 8-byte LogEvent* pointers keeps queue slots tiny and ensures a failed try_push never leaves an event half-moved.
    • Backpressure (overflow) policy: Configurable per logger. Block (default) waits for space so zero messages are lost; DropNewest drops immediately and increments an atomic counter for ultra-low-latency threads where stalling is worse than losing a log line.
    • Durability of flush(): flush() calls fflush, 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. Calling fsync to force physical disk writes takes milliseconds and is an opt-in sink setting.
  2. 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 cushion
    

    What these numbers tell us:

    1. 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.
    2. 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 Block and DropNewest.
  3. 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. Writing LOG_INFO(log, "{} {}", 42) fails to compile instead of failing in production.
    • Wrapper macros (ALOG, LOG_INFO, ...) do two jobs a normal C++ function cannot:
      1. They check should_log(level) before evaluating arguments, so LOG_DEBUG(log, "{}", expensive_dump()) costs a single 1 ns atomic load when Debug is turned off.
      2. They capture __FILE__ and __LINE__ as compile-time constants (const char* string literal in static memory, zero copying required).
    • Single-threaded Sink interface: Only the background thread calls write() and flush() (or shutdown() 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 FileSink uses a 64 KB stdio buffer so small lines coalesce in user space instead of triggering a kernel write() 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_;
    };
    
  4. Log event structure and type erasure

    Here is the first design puzzle: one call logs (int, double), the next logs (std::string), and flush() sends a control signal—yet LockFreeQueue must have a single element type.

    We solve this with type erasure (hiding many different concrete argument types behind one common base-class interface):

    1. LogEvent is a non-template base struct holding common metadata (level, time, thread, file, line, format_str) plus a virtual void format_message(fmt::memory_buffer&) method.
    2. MessageEvent<Ts...> is a small template subclass that stores the captured arguments in a std::tuple<Ts...> with their exact types and overrides format_message to unpack that tuple into fmt::vformat_to.
    3. Control commands (Flush and Stop) are plain LogEvent instances 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:

    • time is recorded on the producer thread so timestamps reflect when the event happened, not 50 ms later when the background thread wrote it.
    • format_str is copied into a std::string because while most callers pass string literals, {fmt} also allows dynamic strings via fmt::runtime(temp_str) whose storage may die before the background thread runs.
    • flushed is wrapped in std::shared_ptr: if a caller calls flush(5ms), times out, and returns, its stack frame is destroyed; keeping the promise in a shared_ptr ensures the background thread will not write into freed stack memory when it eventually reaches the Flush event.
  5. 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 & flush
    

    Pointer ownership follows a strict single-owner relay so nothing ever leaks or double-frees:

    1. log() creates the event inside std::unique_ptr<LogEvent> ev.
    2. If queue_.try_push(ev.get()) succeeds, ev.release() hands ownership to the queue. If try_push fails and we drop (or an exception is caught), ev's destructor frees the event automatically.
    3. When the worker pops LogEvent* raw, it immediately adopts it into std::unique_ptr<LogEvent> ev(raw).

    Notice a subtle concurrency detail in push_or_drop_on_stop: if Block mode encounters a full queue while shutdown() is running, the worker may exit after draining, so spinning blindly forever would deadlock! Checking stopping_ 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 detail
    

    Here are the private members of Logger and its constructor. Notice worker_ is declared very last: C++ initializes class members in declaration order, so starting worker_ last guarantees that queue_, 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 live
    
    Logger::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(); });
    }
    
  6. 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 detail
    

    Let's verify every argument category and document what still requires caller care:

    • Primitives (int, double, enums) and std::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*, stack char buf[32]) and string_view: Converted immediately to an owning std::string. Passing nullptr safely records "(null)" instead of triggering undefined behavior in strlen.
    • 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 with fmt::format.
      • Pointer format specifiers ("{:p}"): since const char* becomes std::string in storage, printing an address requires static_cast<const void*>(ptr).
      • Custom fmt::formatter<MyType>: runs on the background thread against the copied MyType, so the formatter itself must not touch unsynchronized global state or dereference raw pointers inside MyType.
  7. Deep dive 2: The background consumer loop and buffered I/O

    Three design choices govern the worker thread in Logger::run():

    1. How to wait when the queue is empty:
      • Busy-spinning wastes 100% of a CPU core even when the app is idle.
      • std::condition_variable wakes 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 every log() 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).
    2. Zero-allocation steady-state formatting: The worker reuses one fmt::memory_buffer line_ across all messages, clearing its size while keeping its heap capacity.
    3. Fault-isolated writing: Periodic flushes happen every flush_every (200 ms) only if dirty_ is true. Runtime format errors become visible [format error: ...] log lines, and failing sinks never block healthy sinks or spam stderr.
    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_));
    }
    
  8. Deep dive 3: Race-free flush, shutdown, and end-to-end demo

    Most bugs in asynchronous loggers live in flush() and shutdown(), where control calls race against concurrent log() calls.

    Why flush() uses an in-band marker instead of while (!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 on done.wait_until(deadline). Otherwise, if a hung network mount froze the worker and filled the queue, pushing the Flush marker would block forever regardless of timeout!

    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_once makes shutdown() idempotent—if two threads call shutdown(), one runs stop_worker() and the second blocks until stop_worker() finishes. Inside stop_worker(), control_ ensures no Flush marker is ever pushed after Stop. After worker_.join(), the worker thread is gone, so stop_worker() (and ~Logger() at destruction) can safely drain any last-nanosecond log() call that passed stopping_ == false just 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 messages
    
  9. Error 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::runtime string or throwing formatter Caught 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; stderr notice rate-limited to once per 10 s.
    Hung network mount (fwrite blocks forever) Worker blocks in sink; queue fills; DropNewest callers keep running, flush(timeout) returns false at deadline. Sinks over network mounts should use non-blocking descriptors with timeouts.
    std::bad_alloc or throwing copy constructor Caught in log(); increments dropped_; log() remains noexcept.
    Process crash (SIGSEGV, abort) Unwritten queue items and user-space FILE* buffer (~200 ms max) are lost; mitigate by routing Critical logs 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 Logger is destroyed while another global object's destructor still calls LOG_INFO, use-after-free occurs. Prefer creating the logger in main() and calling shutdown() explicitly before main() 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 after fork().

    Scaling bottlenecks & next optimizations:

    1. 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_local single-producer single-consumer (SPSC) queue and let the background thread poll them round-robin, merging by timestamp if cross-thread order matters.
    2. Heap allocator pressure: Use jemalloc or tcmalloc so small allocations hit thread-local caches; if zero-allocation logging is ever required, replace heap MessageEvents with fixed 256-byte inline ring slots holding serialized argument bytes.
    3. Timestamp prefix caching: Calling gmtime_r 2,000,000 times per second recomputes the same YYYY-MM-DDTHH:MM:SS string two million times inside one second. Cache the 19-byte date/second prefix on the worker thread and recompute it only when secs changes, formatting just the 6-digit microseconds per line.
  10. 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 owning std::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).
    • Block vs. DropNewest overflow policy: Block prioritizes completeness for batch services; DropNewest prioritizes deterministic tail latency for real-time threads while surfacing drops explicitly in the log and dropped().
    • 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/Stop markers + control-only mutex: Gives exact happens-before ordering for flush() and race-free shutdown() while keeping log() completely lock-free.

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:

  1. 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" (converting char* into an owning std::string), 7, and 182.3750 plus the current timestamp into a heap-allocated MessageEvent, pushes the 8-byte LogEvent* 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 if desk_buf is overwritten on the very next line.
  2. Thread 1 logs a disabled debug line: LOG_DEBUG(log, "dump={}", slow_serialize());. Because the macro checks should_log(Debug) before calling log(), slow_serialize() is never even evaluated.
  3. 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.
  4. Thread 1 calls log.flush(): flush() pushes a special Flush marker 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 calls fflush to 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 like const char* and std::string_view must be copied into std::string on the caller thread, and view wrappers like fmt::join cannot be captured safely without eager formatting.
  • Heap-allocated MessageEvent with type erasure vs. fixed-size inline slots. Type erasure (hiding concrete template types like MessageEvent<int, std::string> behind a single LogEvent base pointer with one virtual format_message call) handles any number and type of C++ arguments cleanly and keeps queue slots at 8 bytes. Pre-allocated fixed-size byte slots avoid malloc overhead completely, at the cost of custom binary serialization and a fallback path for oversized messages.
  • Block vs. DropNewest backpressure policy. Backpressure is how a system responds when producers outpace consumers and fill the bounded buffer. Block guarantees zero lost log lines at the risk of stalling business threads when storage lags; DropNewest guarantees bounded caller latency at the cost of lost messages, which we make auditable via dropped() 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/Stop control events vs. out-of-band atomic flags. Pushing Flush and Stop markers 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 before flush() was called.
  • fflush vs. fsync on flush(). fflush copies user-space buffered bytes to the OS page cache (kernel memory backing open files) in microseconds so logs survive a crash of our process; fsync forces 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 local char buf[32] or storing std::string_view directly inside std::tuple works 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_view to the format string: fmt::runtime(dynamic_str) allows temporary runtime strings; failing to copy format_str into an owned std::string leaves a dangling reference on the worker thread.
  • Implementing flush() as while (!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-band Flush marker 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 the Flush marker hangs forever despite the caller passing a timeout.
  • Putting std::promise on flush()'s stack: If flush(timeout) times out and returns, its stack frame dies; when the worker eventually reaches the Flush event and calls set_value(), it corrupts dead stack memory unless ownership is shared via std::shared_ptr<std::promise<void>>.
  • Deadlocking in Block mode during shutdown(): If a producer passes stopping_ == false, gets delayed while shutdown() joins the worker, and then spins forever waiting for room in a full queue nobody is popping anymore, the process hangs. Re-checking stopping_ inside the full-queue retry loop eliminates this deadlock.
  • Letting exceptions escape the worker thread or log(): An uncaught fmt::format_error or disk I/O exception escaping Logger::run() invokes std::terminate() and crashes the entire application over a single bad log message.
  • Declaring std::thread worker_ before queue_ or sinks_ in the class: C++ initializes members in declaration order, so a thread declared first can start executing run() before queue_ 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). On log(), 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: routing Error and Critical messages through an immediate synchronous write path alongside the queue; installing a best-effort signal handler (caveat: formatting and fwrite are not async-signal-safe and can deadlock if the crash occurred inside malloc); 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 Sink implementation 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 guard write() 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

Similar questions

More Qube Research & Technologies interview questions

All 8 Qube Research & Technologies questions →