Moving a CPU-bound Python hot path to Rust with PyO3
· rust, python, pyo3, performance
Problem
A Python web service spends most of each request in a CPU-bound function: a loop over records doing string normalization, hashing, a lookup in a large reference table, some arithmetic and a fuzzy string match. Under Gunicorn with threads, that kind of endpoint hits two limits:
- The GIL. Pure-Python code runs on one core per worker process, however many threads the worker has. Throughput scales only by adding processes.
- Memory per process. Every extra worker loads its own copy of the reference table, so scaling out by processes multiplies memory.
The question: if only the hot function moves to Rust, with the GIL released while it runs, what changes in latency, throughput, CPU and memory, with the rest of the service still in Python?
Approach
I built a small synthetic version of that service, with random data from a fixed seed. POST /transform takes 64 records. For each record it:
- normalizes a name (lowercase, ASCII letters and digits only)
- computes a 64-bit FNV-1a hash of it
- looks the record’s id up in a 1,000,000-row reference table
- scores it: a 16-value dot product with the row’s weights, plus a hash term
- fuzzy-matches the name against 4 candidate category labels (Levenshtein distance) and keeps the closest
There are two implementations of transform(records), chosen by an environment variable. Everything else (Flask, JSON parsing, Gunicorn config) is identical.
Python. Each worker loads the table at startup into a dict from id to row index, plus compact array('I') and array('f') columns. That’s already the memory-friendly way to hold it in pure Python.
Rust via PyO3. The table is one binary file, memory-mapped and searched with binary search, so all workers share one copy in the page cache. Each call has three steps:
// 1. Copy inputs out of Python objects (GIL held).
let inputs = extract(records)?;
// 2. Compute with the GIL released: other request threads keep running Python.
let outputs = py.detach(|| compute(table, &inputs)); // `detach` was `allow_threads`
// 3. Build the Python result dicts (GIL held again).
to_py_list(py, outputs)
A test checks that both versions return identical results, float scores included, on the benchmark payload and on random inputs.
Setup: AMD Ryzen 5 9600X (6 cores, SMT), Linux 7.0, Python 3.14.4, PyO3 0.30, Flask 3.1, Gunicorn 23 (gthread). The server is pinned to 4 physical cores (8 hardware threads); the load generator, oha 1.16, is pinned to the other 2. Each point runs at a fixed request rate (open loop, with latency correction, so slow responses don’t hide queueing) for 20 s after a 5 s warm-up, over 64 connections.
Results
On one thread, one call with 64 records takes 3.06 ms in Python and 89 µs in Rust, about 34× faster. Under load the gap is smaller, because Flask, JSON and converting objects in and out still run in Python on every request.
| Python, 4 workers × 8 threads | Python, 8 workers × 4 threads | Rust via PyO3, 4 × 8 | |
|---|---|---|---|
| Max sustained throughput | ~880 req/s | ~1,140 req/s | ~9,750 req/s |
| p50 / p99 at 500 req/s | 3.7 / 9.6 ms | 3.7 / 9.5 ms | 0.48 / 0.62 ms |
| p50 / p99 at 1,000 req/s | saturated (p99 2.5 s) | 9.3 / 34 ms | 0.38 / 0.74 ms |
| CPU at 1,000 req/s | 4.0 cores (capped) | 5.4 cores | 0.43 cores |
| p99 at 3,000 / 8,000 req/s | saturated | saturated | 1.1 / 2.6 ms |
| Memory (PSS, all processes) | 917 MiB | 1.8 GiB | 127–138 MiB |
| Worker startup (load table) | 0.57 s | 0.57 s | 0.04 ms (mmap) |
What the numbers show:
- The GIL caps each Python worker at one core. With 4 workers, CPU sits at exactly 4.0 cores from 1,000 req/s up, and adding offered load only grows the queue. Doubling to 8 workers buys about 30% more throughput, using the SMT siblings, and doubles memory.
- Per core, the Rust version does roughly 10× the work. About 2,250 requests per core-second at 3,000 req/s, against about 220 for Python. That’s less than the 34× single-call speedup because the per-request Python parts remain.
- Memory drops about 7×. Python holds the table once per worker; the memory map is shared, so going from 4 workers to 8 wouldn’t add much.
Disadvantages
- Two languages in one service. Every change to the hot path needs Rust skills, Rust review and Rust tests, alongside the Python ones.
- Builds get harder. The extension is a compiled wheel per Python version and platform (maturin handles it, but CI needs a Rust toolchain and a build matrix). Docker images need a build stage.
- Debugging crosses a boundary. A Python traceback stops at the extension call; profilers and debuggers show one side at a time. A panic in Rust becomes a Python exception, which needs deliberate handling.
- Conversion isn’t free. Copying 64 dicts into Rust structs and building 64 result dicts happens with the GIL held, on every request. For small functions that overhead can cancel out the gain.
- It only pays off for CPU-bound paths. If the time goes to the database, the network or I/O waits, Rust changes nothing. Profile first.
- Simpler alternatives exist. A C-backed library for the expensive part (here, a native Levenshtein implementation) would close much of the gap without new code in a new language. Running more processes also works, up to the memory bill.
- Caveats of this setup: synthetic data and one repeated request body; the load generator shares the machine (on separate cores), so the Rust ceiling of ~9,750 req/s is a lower bound.
Learnings
What I’d do next
- Find the new bottleneck. Profile the Rust configuration near 9,750 req/s (py-spy plus perf) to confirm whether Flask, JSON parsing and object conversion are now the limit, or the load generator.
- Move JSON parsing into Rust. Pass the raw request body to the extension and parse it with serde, so no Python objects are built for the records at all.
- Try free-threaded Python 3.14. Run the pure-Python version without the GIL and see how much of the gap threads alone close.
- Benchmark the C-library alternative. Swap in a native Levenshtein package and measure it against the Rust version.
- Run the load generator on a second machine to remove it as a possible ceiling.
Reproduce it: https://github.com/chaitu-19-03/pyo3-hotpath-bench