Your FastAPI service is slow only under real traffic. Locally every endpoint answers in a few milliseconds. The obvious move is to restart the worker under cProfile, and that is the move that ruins the measurement: you lose the warm state, and the profiler you just added slows down every function call in the process you wanted to observe.

Python 3.15.0 shipped on October 9, 2026 (3.15.2 is the current patch release) with a different option in the standard library. It is called Tachyon, it lives at profiling.sampling, and it attaches to a process that is already running, by PID, without restarting it or adding code to it. Pointed at a uvicorn worker under load, it tells you which adapter call is eating your latency.

What PEP 799 actually shipped

PEP 799, by Pablo Galindo Salgado and László Kiss Kollár, gives Python's profilers one home. The 3.15 What's New lists the two halves:

  • profiling.tracing: the deterministic profiler, relocated from cProfile. cProfile stays as an alias, so existing scripts keep working.
  • profiling.sampling: the new statistical sampling profiler, Tachyon.

The pure-Python profile module is deprecated and, per the same page, will be removed in Python 3.17.

The two profilers answer different questions. The PEP describes profile and cProfile as tracing profilers that "instrument every function call and return," and says this "introduces significant runtime overhead and can disable certain interpreter optimizations, such as those introduced by PEP 659." PEP 659 is the specializing adaptive interpreter, the thing that makes hot bytecode faster since 3.11. A profiler that switches it off is measuring a slower program than the one you run in production.

Tachyon takes the other approach. It looks at the target's call stack at fixed intervals and counts what it sees. The What's New entry claims sampling rates of up to 1,000,000 Hz, which it calls the fastest sampling profiler for Python "at the time of its contribution." The default in the module docs is a much calmer 1 kHz.

How one process reads another process's frames

Tachyon runs outside your worker, as a second Python process that reads the worker's memory. To do that it needs two things: permission from the operating system, and a map of where the interpreter keeps its state.

Permission comes from the OS debugging interfaces. The remote debugging how-to lists them: process_vm_readv() or /proc/[pid]/mem on Linux, task_for_pid() plus mach_vm_read_overwrite on macOS, and ReadProcessMemory() on Windows.

The map comes from CPython itself. Every interpreter binary has a dedicated section (.PyRuntime on ELF, __DATA,__PyRuntime on Mach-O, PyRuntim on Windows, cut short by the 8-character PE limit) holding the PyRuntime structure. Its address depends on where the OS loaded the binary, so the reader finds the module's base address, reads the section offset from the file on disk, and adds the two.

At the very start of PyRuntime sits _Py_DebugOffsets: a table of field offsets that says where each interesting member lives inside the interpreter's private structs. The reader checks three fields before trusting it. The cookie must match the expected marker, the version must match the reader's own Python version, and the free_threaded flag must match too. If any check fails, the how-to says the tool "should stop the operation to avoid reading memory in the wrong format."

PEP 768, new in 3.14, built its safe-attach protocol on this same table. It added a debugger_support group and sys.remote_exec(), which injects a script that the target runs at its next safe point. Tachyon only needs the reading half.

A magnifying glass held by a second process reads a stack of interpreter frames inside another process's memory
The profiler lives outside the worker and reads its frames through the OS debugging interface.

From there the walk is mechanical. interpreters_head leads to the interpreter state, threads_head to each thread state, and each thread's stack chunks hold its _PyInterpreterFrame records. In CPython's Modules/_remote_debugging/frames.c, the reader copies those chunks into a local buffer, then follows each frame's previous link and reads its executable (the code object) and instr_ptr, which gives the current line.

This is where Tachyon differs from py-spy, the long-standing external profiler. py-spy uses the same OS memory-read interfaces, but its README explains that it generates matching struct layouts per Python version with bindgen, because the layout changes between releases. Tachyon reads the offsets from the target. That design also explains a rule in the docs: profiler and target must run the same minor version, the exact same version for pre-releases, and a free-threaded build cannot attach to a standard one.

Tachyon is not strictly read-only, though. The sampler in Lib/profiling/sampling/sample.py always builds its unwinder with cache_frames=True, and set_last_profiled_frame in frames.c writes one pointer-sized field, last_profiled_frame, into the target's thread state. On the next sample, if the current frame's parent chain still reaches that marker, Tachyon reuses the parent frames it already has and only reads the new ones.

Why the target barely pays

By default, the module docs say, "the target process is never stopped or paused during sampling—Tachyon reads the call stack directly from the process's memory while it continues to run." No trace hook runs on each call. Specialization stays on. The worker executes the same bytecode it would without a profiler attached.

The cost moves to the profiler process, which burns CPU on the machine doing the reads. The docs call that "typically negligible" and note that higher rates mean "slightly higher profiler CPU usage." If your worker shares a small container with the profiler, that CPU comes out of the same budget, so keep the default rate on constrained hosts.

Reading a moving target has a price. Because the worker keeps running, any sample can catch a stack halfway through a change. The docs flag this for dump, which without --blocking "can occasionally produce a torn stack." Both attach and dump take --blocking, which pauses the target for each read to get consistent stacks. For sampling in that mode, the docs recommend intervals of 1,000 µs or more.

Two more limits come with sampling. Times are estimates (sample count multiplied by the interval), and a function shorter than the interval can be missed entirely. Tachyon tells you where time goes, not how many times something ran. If you need exact call counts, that is still profiling.tracing.

Profiling a uvicorn worker under load

Here is a small service with two ports and two deliberately bad adapters. One blocks on I/O inside a sync endpoint. The other does CPU work inside an async def endpoint, which blocks the event loop.

# main.py import hashlib import time from typing import Protocol from fastapi import FastAPI class RateCard(Protocol): def price_for(self, sku: str) -> int: ... class Signer(Protocol): def sign(self, body: bytes) -> str: ... class SlowRateCard: def price_for(self, sku: str) -> int: time.sleep(0.02) # stands in for a blocking HTTP call return 1999 class Pbkdf2Signer: def sign(self, body: bytes) -> str: key = hashlib.pbkdf2_hmac("sha256", body, b"salt", 50_000) return key.hex() class Quotes: def __init__(self, rates: RateCard, signer: Signer) -> None: self._rates = rates self._signer = signer def quote(self, sku: str) -> dict: return {"sku": sku, "cents": self._rates.price_for(sku)} def receipt(self, sku: str) -> dict: return {"sku": sku, "sig": self._signer.sign(sku.encode())} app = FastAPI() quotes = Quotes(SlowRateCard(), Pbkdf2Signer()) @app.get("/quote/{sku}") def quote(sku: str) -> dict: return quotes.quote(sku) @app.get("/receipt/{sku}") async def receipt(sku: str) -> dict: return quotes.receipt(sku) 

The FastAPI docs say a path operation declared with plain def "is run in an external threadpool that is then awaited." So /quote runs on pool threads, while /receipt runs on the main thread with the event loop. Tachyon samples only the main thread by default, so a default profile would show the signer and miss the rate card entirely.

Start the worker on Python 3.15, then put load on both endpoints with oha from two other terminals:

python3.15 -m venv .venv && . .venv/bin/activate pip install fastapi uvicorn uvicorn main:app --port 8000 # terminal 2 and 3 oha -z 60s -c 50 http://127.0.0.1:8000/quote/abc oha -z 60s -c 20 http://127.0.0.1:8000/receipt/abc 

Then attach. On Linux, the default Yama ptrace_scope of 1 only lets a process attach to its own children, so either run the profiler as root or with CAP_SYS_PTRACE. On macOS you need root or the debugger entitlement. The profiler must use the same 3.15 interpreter, which is why the command calls the venv's Python:

PID=$(pgrep -f "uvicorn main:app") sudo .venv/bin/python -m profiling.sampling attach \ -a -d 30 --flamegraph -o wall.html $PID sudo .venv/bin/python -m profiling.sampling attach \ -a -d 30 --mode cpu --flamegraph -o cpu.html $PID 

-a samples every thread, -d 30 stops after 30 seconds, and --flamegraph writes a self-contained HTML file. The first run uses the default wall-clock mode. The second, --mode cpu, keeps only samples where the thread is actually on a CPU.

An abstract flame graph of stacked bars where one tall burnt-orange tower stands out from the black and cream bars around it
Wall-clock and CPU mode tell different stories about the same worker.

Reading the profile by adapter

In wall.html, expect a wide tower whose leaf Python frame is price_for on the time.sleep line, under quote. That is time the pool threads spend waiting. Also expect wide stacks of idle pool threads waiting for work. They are real wall time, but they are not your problem, so skip any stack that does not pass through your code.

In cpu.html, the sleeping threads drop out, because a thread asleep in time.sleep is not on a CPU. What stays is the stack that runs from the receipt endpoint down into the signer's sign method, on the main thread. That is the adapter blocking the event loop, and every other async request queued behind it pays for it.

Two other commands help here. attach --live $PID opens a top-like view in the terminal (Unix only) that updates as samples arrive. For async-heavy code, attach --async-aware --flamegraph -o tasks.html $PID rebuilds stacks from the asyncio task structure instead of the raw thread stack. It cannot be combined with -a or --mode cpu, so treat it as a third pass. If a worker hangs outright, python -m profiling.sampling dump -a $PID prints one traceback-style snapshot of every thread and exits (without -a, only the main thread).

With --workers 4, uvicorn's process manager starts and monitors the worker processes as children of the main process. Each worker is its own interpreter, so attach to one worker's PID, which you can find with pgrep -P <main-pid> or ps. One profile covers one worker.

Look at what made those profiles easy to read. Each slow thing sits behind a named port, RateCard and Signer, with one adapter class each. The flame graph points at price_for or sign, and you know which boundary is costing you without reading a line of framework internals. The fix stays local too: make the rate card async with a real HTTP client, hand the signer to a worker thread with asyncio.to_thread, then profile again and compare. Because the use case only knows the port, a pytest run can swap in an instant fake adapter and show the core was never the slow part.

If this was useful

Tachyon finds the slow call, but the profile only reads cleanly when the slow call sits behind a boundary with a name. That is the idea Hexagonal Architecture in Python is built around: one async FastAPI + SQLAlchemy 2 service built five ways (Hexagonal, Clean, Onion, layered, vertical slice) and then measured, with the core kept apart from the framework and the database. Profiling is out of scope. The book is about the structure that makes "which adapter is slow" a one-glance question. Every listing runs from the free companion repo.

Hexagonal Architecture in Python by Gabriel Anhaia