The problem

While building fastbook, a low-latency market-data ingestion system, I ran into the following problem. I wanted to add logging to the path that runs on the hot-thread, in order to later be able to trace what the program did, for reproducibility and debugging.

This sounds like a simple task, right?

#define LOG(fmt, ...) \
    std::println(file, "[DEBUG] {}:{} " fmt, __FILE__, __LINE__ __VA_OPT__(,) __VA_ARGS__)

// At the call site:
LOG("Received update for instrument {}: {}", instr, price);

If this runs on a hot path, meaning code that runs millions of times per second and whose latency you care about, you are dead. Let’s analyze why.

When you call std::println, std::ostream::operator<<, fprintf() or similar functions, you pay the following costs:

  • The format string is parsed on every call, to find the replacement fields.

  • Every argument has to be converted to text. Depending on the implementation, this can be expensive, since it may involve heap allocations on top of the parsing above. Floating-point values are especially costly.

  • The resulting text is copied into the stream’s buffer (streams are fully buffered for regular files).

  • When the buffer fills up (or on std::endl / fflush()), its contents are handed to the kernel with a write() system call. That is a mode switch: the same thread keeps running, but now in kernel mode. Along the way:

    • the thread’s registers are saved on entry and restored on exit
    • depending on the CPU, the kernel also switches page tables through the CR3 register on entry and exit (KPTI). mov %cr3 is a serializing instruction that costs around 100+ cycles, and it runs twice per system call.
    • the kernel’s own code and data evict the running thread’s from the instruction and data caches, the TLB and the branch predictors. That costs twice: directly, because more instructions run, and indirectly, because the thread resumes on a cold CPU and pays extra misses until it warms up again.

    Normally the kernel only copies the bytes into the page cache and returns. The actual disk write happens later, in the background. With O_DIRECT (which bypasses the page cache), the write() itself waits for the disk, and an fsync() waits until everything written so far has reached it. While waiting, the thread sleeps, so it also pays for a full context switch.

stderr and std::cerr are worse, because they are unbuffered by default, so every call reaches the kernel.

On my benchmark machine (see Benchmarks), one such call costs 1,400 to 4,900 cycles at the median, up to 35,000 cycles at the 99.9th percentile, and the slowest write() took 16.5 ms.

On a system with a latency budget in microseconds, that is not acceptable. However, being able to log is sometimes extremely helpful, for the reasons mentioned above. So how can we log without killing performance?

The design

The following approach is based on three principles.

  • Do as much computation as possible at compile time. The format string, __FILE__, __LINE__ and the log level are all known at compile-time, so there is no reason to parse and copy them at runtime. For every LOG call site, the compiler builds one constant metadata object that holds them, together with a function generated just for that call site, which turns the logged values into text. This object lives in the binary’s read-only data. At run time, the hot thread stores only a pointer to it.

  • Move the expensive part to another thread. Formatting, system calls and I/O all happen on a background thread whose latency does not matter. The hot thread pushes the minimum needed to reproduce the line later: a pointer to the metadata object, a timestamp, and the bytes of the argument. Nothing else. Communication between the threads is achieved by using a lock-free single-producer/single-consumer (SPSC) ring.

  • Never block (mutex/lock, I/O), and do the minimum that is required for synchronization. Each thread owns its own ring, so hot threads never contend with each other: no communication, no locks, no cache-line ping-pong. Publishing a record costs one store with release ordering. If the ring is full, the record is dropped and counted, and the background thread reports the drops. And this is the trade-off we make here: It is better to miss a log once in a while rather than pay the latency cost once in a while.

Implementation

A simplified version of the code, starting with the data.

// Formats one record's payload. Generated at compile time for each call site.
using FormatFn = void (*)(const std::byte *payload, std::string &out);

// Describes one LOG call site. Built once, at compile time.
struct LogMetadata {
  const char *fmt, *file;
  uint32_t line;
  Level level;  // DEBUG, INFO, ERROR, etc.
  FormatFn fn;
};

// Written on every LOG call, at run time.
struct RecordHeader {
  const LogMetadata *meta;
  uint64_t tsc;  // timestamp counter at the time of the call
};

struct Record {             // 256 bytes, fixed size
  RecordHeader hdr;
  std::byte payload[PAYLOAD_BYTES];  // raw argument bytes, strings are encoded with their length as prefix.
};

using LogRing = SPSCQueue<Record, LOG_RING_SIZE>;
std::array<LogRing, N_THREADS> rings;  // one ring per thread

thread_local LogRing *my_ring;  // this thread's ring (producer side)

What the hot thread does:

// One constant per call site, built by the compiler.
#define LOG(lvl, fmt, ...)                                          \
  do {                                                              \
    static constexpr LogMetadata meta{                              \
        .fmt = fmt, .file = __FILE__, .line = __LINE__,             \
        .level = lvl, .fn = decoder_for<fmt, ArgTypes...>};         \
    emit(&meta, __VA_ARGS__);                                       \
  } while (0)

// The only run-time work: reserve a slot, fill it in place, publish it.
template <class... Args>
void emit(const LogMetadata *meta, Args &&...args) {
  Record *rec = my_ring->try_reserve();  // a free slot, or nullptr if the ring is full
  if (!rec) {
    dropped++;                           // never block: drop, count, report later
    return;
  }
  rec->hdr.meta = meta;                  // pointer to the compile-time constant
  rec->hdr.tsc = __rdtsc();              // a few cycles
  write_args(rec->payload, args...);     // memcpy()s of known size, compiled down to a few mov instructions
  my_ring->commit();                     // publish: one release store
}

void hot_thread() {
  while (true) {
    // process market data...
    LOG(INFO, "Received update for {}: {}", instr, price);
  }
}

decoder_for<fmt, ArgTypes...> is where the compile-time work happens. For a given format string and argument types, the compiler splits the format string, checks that the number of {} matches the number of arguments, and generates a function that reads each argument back from the payload and generates the final output string. Nothing about the format string is parsed at run time.

What the background thread does (again simplified):

bool drain_and_log() {
  std::vector<Record> records;
  for (auto &ring : rings) {
    drain_ring(ring, records);           // pop everything that is there right now
  }
  sort_by_timestamp(records);            // merge the per-thread streams

  std::string out;
  for (const Record &rec : records) {
    rec.hdr.meta->fn(rec.payload, out);  // format with the generated decoder
  }
  print_to_file(outfile, out);           // one write() per pass, not per line

  return !records.empty();
}

void logger_thread() {
  while (!stop.load(std::memory_order_acquire)) {
    if (!drain_and_log()) {
      std::this_thread::sleep_for(std::chrono::milliseconds(1));
    }
  }
}

Benchmarks

The experiments ran on a rented bare-metal machine with the following specifications:

Machine

  • Hetzner AX41, bare metal: AMD Ryzen 5 3600 (Zen 2), 6 cores, SMT off.
  • Caches: 32 KiB L1d and 512 KiB L2 per core, and 16 MiB of L3 shared by each group of 3 cores (cores 0–2 and cores 3–5).
  • 64 GB DDR4-2400. Linux 7.0, gcc 15.2, -O3 -mavx2. The log file is on an ext4 disk.

Setup

  • Pinning: the hot thread runs on core 3 and the background thread on core 4, so they share the same L3. In the last benchmark I move the background thread to core 1, in the other L3 group, to show what that costs.
  • These cores run nothing else:
    • no other tasks (isolcpus)
    • no timer tick (nohz_full)
    • no kernel RCU callbacks (rcu_nocbs)
    • no interrupts (all IRQs routed to core 0)
  • Clock frequency: 3.6 GHz with boost off. The timestamp counter also ticks at 3.6 GHz, so one tick is one cycle.
  • Profiling: I used profiling.hpp, the small profiling library I built for fastbook.
    • Latency: every call is timed on its own, with rdtscp followed by lfence on both sides, so the CPU cannot move any of the call’s work outside the two reads. The cost of the two reads is subtracted.
    • Histograms: each latency goes into a log-linear histogram. Every power-of-two range is split into 16 bins and a percentile is reported as the upper edge of its bin. Two latencies that land in the same bin show up as exactly the same number. On this CPU the timestamp counter also moves in steps of 36 cycles, so for short calls the mean is more precise than the percentiles.
    • Hardware counters: read with the perf_event_open API before and after each batch of calls, in the same run. They count user mode only.

One call at a time

Every contender writes the same line (an int and a double) to the same file, except std::format_to, which only formats it into a string and does no I/O. The hot thread makes 512 calls and then spins for 5 ms, so the background thread can empty the ring. This way the ring is never full, and we measure the cost of a call that is actually written. Each contender makes 1M calls.

Cost of one log call on the hot thread

Contendermeanp50p99p99.9maxtime in the kernel*instructions
fastbook logger6975751111.6 µs0%61
std::format_to (no I/O)1,2941,3431,4071,4712.2 µs0%3,781
fprintf1,7651,40717,40723,55111.9 ms20%3,702
std::ofstream1,9841,7912,17534,815106 µs10%4,197
write(2)5,0404,86314,33516,38316.5 ms97%87

All columns are cycles per call, except the max, and “instructions” counts user mode only.

* An approximation: the total time of a call (from rdtscp) minus its user-mode cycles (from a hardware counter that skips the kernel, exclude_kernel=1), divided by the total time. Time the thread spent waiting inside the system call counts here too.

A log call costs 69 cycles on average (19 ns), and 111 cycles at p99.9. That is about 19× less than only formatting the line with std::format_to, and about 73× less than one write().

  • std::format_to runs about 3,800 instructions to turn one int and one double into text. The logger runs 61: it stores a pointer, a timestamp and 12 bytes of arguments.
  • fprintf and std::ofstream keep the text in a user-space buffer and only call write() when it is full (4 KiB for fprintf here, 8 KiB for std::ofstream), so most calls cost about as much as std::format_to, and the write() shows up in the tail: at p99 for fprintf and at p99.9 for std::ofstream.
  • write() spends 97% of its time in the kernel. The slowest one took 16.5 ms. I didn’t go down the rabbit hole of finding out what the kernel was doing. But that is part of the cost too: once you call into the kernel, you lose control over how long the call takes.

Logging faster than the background thread can write

This benchmark shows the trade-off of this design: when the ring is full, calls are dropped. The ring has 4,096 slots, so it only absorbs short bursts. If the hot thread keeps logging faster than the background thread can write, the ring fills up. To find the point where this happens on this machine, the hot thread logs non-stop at a fixed rate for 2 seconds, from 100K to 12M calls per second (12M is as fast as the loop goes with the timing around each call).

Calls written per second, as the call rate grows

  • Up to 1M calls per second, every call is written. The background thread writes at most about 2M lines per second. Above that the ring fills up, and the extra calls are dropped and counted: at 12M calls per second, 84% of them are dropped.
  • The ring also has to absorb the background thread’s stalls. At 500K calls per second, 4,096 slots last about 8 ms. In one run (500K calls per second, background thread on core 1), 3,809 calls were dropped, which means the background thread stopped draining for about 16 ms.
  • The hot thread does not slow down when the ring is full. A dropped call costs 37 cycles at p50 (it reads the ring’s indices and increments a counter), which is less than a written one.
  • Why 2M lines per second? perf on the background thread shows more than half of its time spent the format loop that appends the final line to a std::string one character at a time. Formatting moved off the hot thread, but each line still costs about 500 ns on the background thread.

Where the background thread runs

This benchmark shows how the background thread’s placement affects the hot thread’s latency. It is the same sweep, run a second time with the background thread on core 1, in the other L3 group.

Hot thread p99 per call, with the background thread in the same or the other L3 group

Background threadhot thread p50 / p99 (100K calls/s)hot thread p50 / p99 (1M calls/s)hot thread: cache lines from L3 or another core, per call (1M calls/s)background thread: most lines written per second
core 4 (same L3 group)75 / 11175 / 1510.321.97M
core 1 (other L3 group)75 / 39975 / 5430.351.99M

The hot thread writes records into the ring and the background thread reads them, so cache lines move back and forth between the two cores. The counters show about the same number of cache lines coming from outside the hot core either way (0.32 vs 0.35 per call), but from the other L3 group each one takes longer. The effect is not evident in the median (75 cycles in every case), but in the tail: p99 goes from 111 to 399 cycles at 100K calls per second, and from 151 to 543 at 1M calls per second. The p50 does not change because most calls find the line already in the hot thread’s cache. Even at 1M calls per second, only 0.32–0.35 lines per call come from outside it, so at most about a third of the calls fetch anything. Most likely this is because the ring is written in order, so the hardware prefetcher fetches the next slots ahead of time, and because of the cached indices, which avoid needless back-and-forth of the index lines between the two threads.

The background thread itself writes just as fast in both places.

So the background thread should run in the same L3 group as the threads that log.

The work did not disappear. Formatting and I/O still happen, but on the background thread, so the hot thread barely notices them.

Full code: fastbook