IYIndo Yoon
·10 min read

Building the Fastest Python Logger in Rust — Part 3: Free-Threaded Python 3.15t and Killing the Last GIL Re-entry

Declaring gil_used = false on Python 3.15t was supposed to make multi-threaded logging fly. Instead, 2-thread %-formatted throughput stalled at 516K rec/s because every log line quietly re-entered CPython's str.__mod__. Eliminating that last FFI round-trip pushed 3.15t to 1,374,814 rec/s (+166%, 8.41x stdlib).

Empirical Provenance: All throughput numbers were measured directly on CPython 3.12.16, 3.15.2 (GIL), and 3.15.2t (free-threaded No-GIL) compiled with --release (lto = fat, opt-level = 3) on a 2-core Intel Xeon Platinum 8481C: 80,000 sink-verified records written and flushed per run, reporting 5-run median and min-max range.

When you build a Python logging engine in Rust, free-threaded CPython (--disable-gil, shipped as python3.13t through python3.15t) sounds like a free lunch. LogXide already kept level checks in an atomic byte and ran file and network sinks in Rust. Turn off the GIL, add threads, watch throughput double.

So I upgraded LogXide to PyO3 0.30, added #[pymodule(gil_used = false)] in src/lib.rs, compiled cp315t wheels, and ran two OS threads logging "user %s action %s id=%d" into independent FileHandlers.

Here is what came back:

  • Single-thread literal logger.info("hello") on 3.15.2t: 1,522,046 rec/s
  • Two-thread %-formatted logging on 3.15.2t: 516,792 rec/s

Adding a second CPU core on a no-GIL runtime made LogXide three times slower than a single thread logging literals, and slower than a single thread logging %-args (618,572 rec/s).

That number hurt — because it meant my "native Rust hot path" was still secretly bouncing back into the Python interpreter once per log record.

This is the story of shipping LogXide v0.4.0: three concurrency and runtime landmines we hit on Python 3.15 and 3.15t, and how killing that final CPython re-entry pushed 2-thread 3.15t throughput from 516,792 to 1,374,814 rec/s (+166.0%, 8.41x faster than Python stdlib).

Landmine 1: Lying About gil_used = false Gets Caught Immediately

On free-threaded CPython builds, importing any C or Rust extension that has not declared Py_mod_gil = Py_MOD_GIL_NOT_USED triggers a RuntimeWarning and re-enables the GIL globally for the entire Python process. One unported logging dependency silently disables free-threading for your whole service.

In PyO3 0.30, opting into no-GIL execution takes one attribute on the root module:

src/lib.rs
#[pymodule(gil_used = false)]
fn logxide(_py: Python, m: &Bound<'_, pyo3::types::PyModule>) -> PyResult<()> {
    // ...
}

Once sys._is_gil_enabled() stayed False after importing LogXide, our new multi-threaded 3.15t stress test immediately crashed with:

RuntimeError: Already borrowed

Why #[pyclass] Panicked Without the GIL

On traditional GIL builds, CPython serializes entry into #[pymethods]. Even if eight Python threads call logger.info(...) while a ninth thread calls logger.setLevel(...), only one thread enters PyO3's wrapper at the exact instant PyCell checks its dynamic borrow flags — unless a method detaches mid-borrow.

On 3.15t, eight threads execute logger.info(&self, ...) simultaneously, holding shared borrows on PyLogger's PyCell header. The instant another thread called setLevel(&mut self, ...) (requesting a mutable borrow of PyLogger), PyO3's borrow checker did its job and raised RuntimeError: Already borrowed.

Look at PyLogger's struct fields, though: every mutable state inside PyLogger was already synchronized via Arc<FastLogger> (AtomicU8) or Arc<Mutex<...>>. It never needed &mut self at the PyO3 wrapper layer in the first place.

Marking PyLogger with #[pyclass(frozen)] and changing setLevel to take &self solved two problems at once:

src/py_logger.rs
#[pyclass(frozen)]
pub struct PyLogger {
    pub(crate) inner: Arc<Mutex<Logger>>,
    pub(crate) fast_logger: Arc<FastLogger>,
    pub(crate) rust_dispatch: Arc<Mutex<Vec<RustEntry>>>,
    pub(crate) py_dispatch: Arc<Mutex<Vec<PyEntry>>>,
    // ...
}
  1. Zero borrow panics under concurrent setLevel, addHandler, and info storms across 8+ free-threaded worker threads.
  2. Zero dynamic borrow-tracking overhead on every logger.info() call, because frozen pyclasses bypass PyCell atomic borrow counters completely.

Landmine 2: Python 3.15's Built-in frozendict (PEP 814) & Sentry SDK 3.x

Testing against CPython 3.15.2 surfaced two immediate ecosystem changes:

First, PEP 814 adds frozendict as a Python built-in type in 3.15. Teams using immutable request context maps immediately pass frozendict into extra or named mapping arguments:

ctx = frozendict({"user": "alice", "id": 42})
logger.info("user %(user)s logged in (id=%(id)d)", ctx, extra=ctx)

Previously, LogXide checked obj.cast::<PyDict>().is_ok(). In CPython's C API, frozendict is not a subclass of dict (PyDict_Check returns false), so frozendict arguments were misclassified as scalar positional values.

We added a one-time OnceLock type probe against builtins.frozendict that resolves once per interpreter lifetime and extracts key-value pairs on 3.15 while returning false cleanly on Python 3.12–3.14:

src/py_logger.rs
#[inline]
fn is_frozendict_instance(obj: &Bound<PyAny>) -> bool {
    static FROZENDICT_TYPE: std::sync::OnceLock<Option<Py<pyo3::types::PyType>>> =
        std::sync::OnceLock::new();
    let py = obj.py();
    let Some(ft) = FROZENDICT_TYPE.get_or_init(|| {
        py.import("builtins")
            .ok()
            .and_then(|b| b.getattr("frozendict").ok())
            .and_then(|t| t.cast_into::<pyo3::types::PyType>().ok())
            .map(|t| t.unbind())
    }) else {
        return false;
    };
    obj.is_instance(ft.bind(py)).unwrap_or(false)
}

Second, Sentry SDK 3.x removed the deprecated sentry_sdk.Hub class that Part 1 originally probed. Updating sentry_integration.py to check sentry_sdk.is_initialized() and sentry_sdk.new_scope() first (falling back to Hub only on legacy 1.x installs) kept zero-config Sentry working across SDK versions 1.x, 2.x, and 3.x.

Landmine 3: Why 3.15t Stalled at 516K rec/s on %-Formatted Logs

With correctness green across all 17 Linux, macOS, and Windows matrix jobs, I went back to that benchmark cliff: why was 2-thread %-formatted logging stuck at 516,792 rec/s on 3.15.2t, while literal strings ran at 1.52M rec/s?

Reading LogRecord::write_message_into in src/core.rs gave the whole game away in six lines:

// OLD PATH: Every record with %-args re-entered CPython!
let formatted = Python::attach(|py| {
    let py_args = json_value_to_py(py, value)?;
    let py_msg = self.msg.as_str().into_pyobject(py)?;
    let formatted = py_msg.call_method1("__mod__", (py_args,))?;
    Ok(formatted.str()?.to_string())
})?;

Look at what happened on every single log line whenever formatting arguments were present:

  1. At call time in Python, PyLogger had already extracted ("alice", "login", 42) into a Rust serde_json::Value so LogRecord could cross threads safely without holding Python pointers.
  2. Then, at format time inside Formatter::format, Rust called Python::attach, converted the Rust Value back into fresh Python tuple, string, and int heap objects, allocated a PyUnicode for self.msg, invoked Python's __mod__ operator, copied the resulting string back into Rust, and decref-freed every temporary Python object.

On a standard GIL build (3.12 and 3.15), Python::attach serialized formatting behind the GIL — dropping 2-thread throughput to 243K–277K rec/s.

On free-threaded 3.15t, there is no global GIL, yet Python::attach still attaches each worker to CPython's thread state, hits CPython's object allocator, constructs four temporary PyObjects per log line, and runs PyUnicode_Format in C. We were paying the FFI marshaling tax twice per log line just to substitute %s and %d.

The Fix (P1-3): Pure-Rust Scratchpad %-Formatting with Rollback

Roughly 99% of production Python log calls use a small subset of printf-style specifiers: %s, %d, %i, %u, %%, optional - or 0 width flags (%06d, %-12s), and named dictionary keys (%(user)s).

Meanwhile, the remaining 1% of Python's % operator is full of edge cases (%r invoking custom __repr__, float precision formatting, or arity mismatches raising TypeError). Breaking stdlib edge cases to win a benchmark is cheating.

So in src/core.rs, we built try_write_percent_args_rust around an optimistic rollback contract:

Hot-Path Architecture: Eliminating CPython Re-entry in LogXide v0.4.0Before (str.__mod__ re-entry — stalls at 517K rec/s on 2T 3.15t)logger.info(msg, a, b)PyCell borrow + serdePython::attach + str.__mod__BufWriter File Sinkv0.4.0 Pure-Rust Fast Path (0 GIL / CPython re-entries — 1,374,814 rec/s on 2T 3.15t)#[pyclass(frozen)] + AtomicU8serde Value / frozendictFMT_SCRATCH + itoa (%s/%d)Native Rust SinkFallback contract: unsupported %r / float / custom __str__ truncates FMT_SCRATCH and delegates to Python str.__mod__.

LogXide v0.4.0 formats common %s, %d, and %(key)s patterns directly into thread-local FMT_SCRATCH using itoa without touching Python::attach, truncating and falling back to str.mod on exotic specifiers.

  1. Formatter already holds a thread-local FMT_SCRATCH buffer used to assemble the full log line (%(asctime)s - %(levelname)s - %(message)s\n) with zero per-record heap allocations.
  2. try_write_percent_args_rust records let start_len = out.len(); and writes literal slices plus scalar values (strings, stack-formatted integers via itoa::Buffer, booleans) straight into FMT_SCRATCH — supporting both positional tuples and mapping dicts.
  3. If it hits anything outside that scalar contract — %r, floats, precision dots, missing keys, or extra positional arguments — it calls out.truncate(start_len) and returns false, delegating cleanly to Python::attach and str.__mod__.
src/core.rs
pub fn try_write_percent_args_rust(msg: &str, args: &Value, out: &mut String) -> bool {
    let start_len = out.len();
    let ok = match args {
        Value::Object(map) => try_write_percent_mapping(msg, map, out),
        Value::Array(items) => try_write_percent_positional(msg, items.as_slice(), out),
        scalar => try_write_percent_positional(msg, std::slice::from_ref(scalar), out),
    };
    if !ok {
        out.truncate(start_len);
    }
    ok
}

#[inline]
pub fn write_message_into(&self, out: &mut String) -> PyResult<()> {
    match &self.args {
        None => {
            out.push_str(&self.msg);
            Ok(())
        }
        Some(value) => {
            if try_write_percent_args_rust(&self.msg, value.as_ref(), out) {
                return Ok(());
            }
            let formatted = Python::attach(|py| self.format_message_via_python(py, value))?;
            out.push_str(&formatted);
            Ok(())
        }
    }
}

Zero intermediate String allocation for message formatting. Zero temporary PyObjects. Zero Python::attach calls on the hot path.

Sink-Verified Benchmarks Across 3.12, 3.15 (GIL), and 3.15t (No-GIL)

To verify real I/O rather than un-flushed memory queues, every trial writes 80,000 formatted log records to disk, flushes the FileHandler, verifies the line count on disk, and reports the 5-run median (plus min–max range) after warmup on a 2-core Intel Xeon Platinum 8481C (lto = "fat", opt-level = 3):

2-Thread %-Formatted FileHandler Throughput — Before vs After Killing Python str.__mod__ Re-entryCPython 3.12.16 (GIL)v0.4.0 495,809/s (+79.2%)str.__mod__ 277K/sstdlib 89K/sCPython 3.15.2 (GIL)standard GIL buildv0.4.0 516,314/s (+112.1%)str.__mod__ 243K/sstdlib 98K/sCPython 3.15.2t (No-GIL)free-threaded · gil_used = falsev0.4.0 1,374,814/s (+166.0% · 8.41x stdlib)str.__mod__ 517K/sstdlib 164K/s2 concurrent Python threads -> independent FileHandlers · 80,000 sink-verified records · 5-run median

2-thread independent FileHandler throughput on "user %s action %s id=%d" before and after eliminating Python::attach + str.mod re-entry.

1. Two Concurrent Threads -> Independent FileHandlers (%-Args)

RuntimeBefore (str.__mod__)LogXide v0.4.05-Run RangeGainPython stdlibvs stdlib
CPython 3.12.16 (GIL)276,727 / s495,809 / s489.6K–522.0K+79.2%89,436 / s5.54x
CPython 3.15.2 (GIL)243,455 / s516,314 / s498.4K–518.6K+112.1%98,336 / s5.25x
CPython 3.15.2t (No-GIL)516,792 / s1,374,814 / s1.30M–1.42M+166.0%163,538 / s8.41x

Look at how the three runtimes separate:

  • On GIL builds (3.12.16 and 3.15.2), two threads contending on the GIL at the Python call site top out around 496K–516K rec/s — still over 5.2x stdlib, and roughly 2x faster than before because formatting no longer grabs the GIL a second time.
  • On free-threaded 3.15.2t, removing that second CPython re-entry unlocked real 2-core scaling: 1,374,814 rec/s — 2.66x faster than the 3.15.2 GIL build on the exact same 2-core machine.

2. Single-Thread %-Args

RuntimeBefore (str.__mod__)LogXide v0.4.0GainPython stdlibvs stdlib
CPython 3.12.16668,206 / s1,039,285 / s+55.5%114,859 / s9.05x
CPython 3.15.2 (GIL)456,136 / s1,063,551 / s+133.2%126,916 / s8.38x
CPython 3.15.2t (No-GIL)618,572 / s1,061,905 / s+71.7%119,890 / s8.86x

Even on single-threaded Python 3.12 and 3.15, crossing 1.06M rec/s on multi-argument log lines came purely from deleting redundant Python-to-Rust-to-Python string marshaling.

Try LogXide v0.4.0 on Python 3.12–3.15t

LogXide v0.4.0 ships 43 prebuilt release artifacts on PyPI — including native cp315 and free-threaded cp315t wheels across Linux (x86_64 and aarch64 manylinux + musllinux), macOS (arm64 and x86_64), and Windows:

pip install --upgrade logxide

Verify that free-threading stays active in your 3.15t environment:

import sys
from logxide import logging

assert not sys._is_gil_enabled()  # True — zero GIL fallback!

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("worker")
logger.info("user %s processed batch=%d", "alice", 1024)
logging.flush()

If there is one takeaway from porting a PyO3 extension to 3.15t, it is this: declaring gil_used = false only removes the front-door lock. If your Rust hot path still calls Python::attach to borrow Python's string formatter, allocator, or dict helpers, CPython will serialize your threads all over again. Measure with multiple threads hitting independent sinks, count your FFI crossings, and keep the hot path in Rust until the bytes hit the kernel.