{"schemaVersion":"1.0","type":"TechArticle","types":["Article","TechArticle"],"slug":"profiling-live-python-processes-with-tachyon-cyh21","url":"https://zyvop.com/profiling-live-python-processes-with-tachyon-cyh21","title":"Profiling Live Python Processes with Tachyon","subtitle":"Profile live Python processes with Tachyon to find performance bottlenecks, inspect CPU usage, and optimize production services without restarting.","tldr":"Discover how Python 3.15’s Tachyon sampling profiler helps identify performance bottlenecks in running applications. Learn to capture stack snapshots, analyze CPU usage, generate flame graphs, and verify optimizations without modifying or restarting your service.","keywords":["Python","Performance Optimization","Python 3.15","Performance Profiling","debugging","Tutorial"],"entities":["Tomson Alex","Blogger","Python","Performance Optimization","Python 3.15","Performance Profiling","debugging","Tutorial","ZyVOP"],"keyTakeaways":["We've all been there: a service that behaves in staging and crawls in production, and the only way to find out why is to sprinkle timing code around and redeploy.","Python 3.15 gives you a better option.","The new profiling.sampling module, nicknamed Tachyon, can attach to a running Python process by PID, sample it for a while, and show you where the time goes."],"headings":["How Tachyon works (the short version)","Before you start","The scenario","Step 1: Take a snapshot with dump","Step 2: Sample for 30 seconds with attach","Step 3: Is it computing or waiting?","Step 4: See where, exactly","Step 5: Fix it and verify","Practical tips for production","When Tachyon is the wrong tool","Cheat sheet","Wrap-up"],"outboundLinks":["https://docs.python.org/3/library/profiling.sampling.html","https://docs.python.org/3/whatsnew/3.15.html"],"contentText":"We've all been there: a service that behaves in staging and crawls in production, and the only way to find out why is to sprinkle timing code around and redeploy. Python 3.15 gives you a better option. The new profiling.sampling module, nicknamed Tachyon, can attach to a running Python process by PID, sample it for a while, and show you where the time goes. This post walks through a realistic investigation, from the first snapshot to a verified fix. Everything below requires Python 3.15 or newer. How Tachyon works (the short version) A tracing profiler such as cProfile (now also available as profiling.tracing) records every function call and return. That gives exact counts, but it adds overhead to every call. Tachyon takes the opposite approach. It reads the target's call stack from outside the process at a fixed rate (1 kHz by default). Functions that eat a lot of time show up in a lot of samples. By default the target isn't paused, and nothing runs inside it, so you can point Tachyon at a live server. Two things to keep in mind: Times are estimates. Tachyon multiplies sample counts by the sampling interval. More samples mean tighter estimates, and results will vary slightly between runs. Sampling can miss very short-lived functions, and it can't give you exact call counts. Before you start Match the Python version. The profiler and the target must run the same minor version (both 3.15). If either is a pre-release, both must be the exact same version. A free-threaded build can't attach to a standard build, or the other way round. You need permission to read the target's memory: OS What you need Linux root, the CAP_SYS_PTRACE capability, or a relaxed Yama ptrace_scope macOS root, or the com.apple.security.cs.debugger entitlement Windows administrator rights or SeDebugPrivilege Setting ptrace_scope to 0 loosens a system-wide setting, so for a one-off session on a shared host, running the profiler with sudo is the lighter touch. The examples below omit sudo. If your PATH differs under sudo, use the full path to your 3.15 interpreter. The scenario Imagine a pricing service whose latency crept up after the product catalog grew to around 50,000 items. The suspect is hiding in plain sight, but we're going to prove it with data instead of guessing: # catalog.py PRODUCTS = load_products() # ~50,000 items def find_product(product_id): for p in PRODUCTS: if p.id == product_id: return p raise KeyError(product_id)The service is running as PID 41873. (pgrep -f is handy for finding it.) Note: The output below is illustrative, not captured from a real run. Your numbers will differ, but the shape of the output is what the docs describe. Step 1: Take a snapshot with dump Start with the cheapest question: what is the process doing right now? python -m profiling.sampling dump 41873dump reads the stack once and prints it like a traceback, annotating each thread's state (has the GIL, on CPU, waiting, idle, and so on): Stack dump for PID 41873, thread 140213 (main thread, has GIL, on CPU; most recent call last): File \"server.py\", line 74, in serve response = handle_request(req) File \"pricing.py\", line 31, in price_quote product = find_product(item.product_id) File \"catalog.py\", line 5, in find_product for p in PRODUCTS:One snapshot is one data point, but if it lands in find_product a few times in a row, you have a lead. dump is also the first thing to reach for when a process looks hung. Add -a to see every thread instead of just the main one. Step 2: Sample for 30 seconds with attach python -m profiling.sampling attach -d 30 41873Always pass -d. Without it, attach keeps sampling until the target process exits. If your service uses worker threads, add -a, because by default only the main thread is sampled. The default output is a pstats-style table, sorted by sample count (time columns omitted here): Profile Stats (Mode: wall): nsamples sample% cumul% filename:lineno(function) 19800/19800 66.0% 66.0% catalog.py:4(find_product) 4500/4500 15.0% 15.0% server.py:57(read_request) 900/20700 3.0% 69.0% pricing.py:31(price_quote) 750/26100 2.5% 87.0% server.py:70(handle_request)nsamples is shown as direct/cumulative. Direct samples are when the function was at the top of the stack, doing its own work. Cumulative samples include time spent in things it called. A direct count close to the cumulative count means a true hot spot, and that's what find_product looks like here: about two-thirds of all samples, almost all of it its own code. Step 3: Is it computing or waiting? Wall-clock mode (the default) counts everything, including time spent blocked on I/O. Run the same sampling in CPU mode: python -m profiling.sampling attach -d 30 --mode=cpu 41873CPU mode discards samples taken while the thread is sleeping, blocked, or waiting on a lock. Comparing the two profiles tells you what kind of problem you have: High in both modes: a real computational hot spot. Fix the algorithm or the code. High in wall, low or absent in CPU: the function is waiting. CPU tuning won't help. Look at async I/O, connection pooling, or the thing being waited on. Here, read_request (socket waiting) falls away in CPU mode and find_product takes an even bigger share. It's computation. There are two other modes if you need them: --mode=gil shows which code holds the GIL and starves other threads, and --mode=exception shows time spent handling exceptions. Step 4: See where, exactly A flame graph shows the call hierarchy, with width proportional to time: python -m profiling.sampling attach -d 30 --flamegraph -o profile.html 41873The result is a single self-contained HTML file. Copy it off the server and open it in a browser. For line-level detail, use a heatmap, which writes a directory of per-file HTML pages: python -m profiling.sampling attach -d 30 --heatmap -o heatmap 41873The heatmap colors source lines from cool to hot, so the if p.id == product_id comparison inside the loop will light up. The flame graph tells you which path is slow, and the heatmap tells you which line. Other formats exist too: --collapsed for external flame graph tools, --gecko for the Firefox Profiler, and --live for a top-style terminal view. Step 5: Fix it and verify The cause is a linear scan over 50,000 items on every request. Replace it with a dictionary lookup: # catalog.py PRODUCTS = load_products() PRODUCTS_BY_ID = {p.id: p for p in PRODUCTS} def find_product(product_id): return PRODUCTS_BY_ID[product_id]To prove the fix worked, reproduce the hot path in a script (call it bench.py) that replays a few thousand representative requests. Make sure it runs for several seconds, because sampling needs enough samples to be meaningful. Capture a baseline before the fix and compare after: # Before the fix: record a baseline python -m profiling.sampling run --binary -o baseline.bin bench.py # After the fix: differential flame graph against the baseline python -m profiling.sampling run --diff-flamegraph baseline.bin -o diff.html bench.pyIn the differential flame graph, blue means a function now uses less time, red means more, gray means no real change, and purple marks code that wasn't in the baseline. After the fix, find_product should turn deep blue. Then confirm in production with another attach under real load. Practical tips for production Start short. Ten to thirty seconds usually reveals the big hotspots. Extend the duration only if you need tighter estimates. Profile under representative load. Normal traffic is easier to interpret than an unusual spike. Record now, analyze later. attach --binary -o profile.bin PID captures compact raw data, and replay converts it to pstats, a flame graph, or a heatmap afterwards without re-profiling. The docs note that sampling also runs faster because the visualization work is deferred. Multiprocess apps: add --subprocesses so each Python child gets its own profiler and its own output file, named with its PID. asyncio apps: use --async-aware to get stacks that follow await chains rather than event loop internals. It requires the target to have asyncio loaded, and it can't be combined with --native, --no-gc, --all-threads, or --mode=cpu/gil. C extensions: --native adds &lt;native&gt; frames so you can see time in compiled code instead of having it attributed to the Python caller. Be careful with --blocking. It pauses the target on every sample to guarantee consistent stacks, which slows the process down. Only use it if you see inconsistent stacks, and keep the interval at 1 ms or longer. When Tachyon is the wrong tool Scripts that finish in under a second won't produce enough samples. Use profiling.tracing, or loop the work. You need exact call counts. Sampling only estimates, so use profiling.tracing. You're comparing two implementations that differ by 1–2%. Sampling noise can hide that. Use timeit or profiling.tracing. Live mode (--live) relies on curses, so it isn't available on Windows. Cheat sheet Goal Command What is it doing right now? python -m profiling.sampling dump PID Profile a running process python -m profiling.sampling attach -d 30 PID Profile a script from startup python -m profiling.sampling run script.py CPU-only samples add --mode=cpu All threads add -a Interactive flame graph add --flamegraph -o profile.html Line-level heatmap add --heatmap -o heatmap Save raw data add --binary -o profile.bin Convert saved data python -m profiling.sampling replay --flamegraph -o out.html profile.bin Wrap-up Tachyon turns \"add logging and redeploy\" into a three-command investigation: dump for a snapshot, attach to sample, and a flame graph or heatmap to see the culprit. It won't replace a tracing profiler for exact counts, but for the question \"where is my production process spending its time?\", it's now built into the standard library. For the full option reference, see the profiling.sampling documentation and the Python 3.15 release notes.","contentHash":"sha256:ec921f92de2da805565ed8d059fe566258079e7a0644055d5d5fb0461d31f1d2","authorName":"Tomson Alex","authorUrl":"https://zyvop.com/author/tomson","authorSameAs":[],"category":"Tutorial","tags":["Python","Performance Optimization","Python 3.15","Performance Profiling","debugging"],"audience":"Software engineers and developers building applications with Tutorial","tone":"Instructional, practical, code-first","readingTimeMinutes":7,"wordCount":1635,"faqs":null,"primaryTopic":"Tutorial","publishedAt":"2026-11-26T15:20:08.427Z","updatedAt":"2026-11-26T15:20:08.427Z","canonicalUrl":"https://zyvop.com/profiling-live-python-processes-with-tachyon-cyh21"}