py-spy is the production-safe Python profiler — it attaches to a running process without instrumentation, samples the stack at 100 Hz, and emits a flamegraph SVG or a live top-style view. The “without instrumentation” part matters because cProfile requires a code change and a restart, and pdb blocks the interpreter. py-spy works against any CPython process, including under Gunicorn, Celery, and Django, on a live production worker.
How to verify
Make sure py-spy is installed and can read another process’s memory:
py-spy --version
sudo py-spy dump --pid $(pgrep -f gunicorn | head -1)
cat /proc/sys/kernel/yama/ptrace_scope
ls -l /proc/$(pgrep -f gunicorn | head -1)/status 2>/dev/null | head -2
If dump returns “Operation not permitted,” either ptrace_scope is 1 (allow only parent) and you need root, or the target binary lacks the capability — see step 1.
What’s happening
py-spy uses ptrace on Linux (or its equivalent on macOS) to read the target process’s memory and walk the Python interpreter’s frame stack without pausing execution. Each sample takes microseconds; at 100 Hz the runtime overhead on the target is around 1-2%. Because it doesn’t instrument the code, you can attach to a production worker, capture 30 seconds of samples, detach, and convert to a flamegraph — the worker doesn’t know you were there.
Three sampling modes matter. py-spy record -o out.svg produces a flamegraph SVG — wide bars are functions that consumed CPU, stacked vertically by call chain. py-spy top is top for Python — function names with percentage of samples, updated live. py-spy dump is a one-shot snapshot of every thread’s current call stack — useful for “the worker is stuck, what is it doing right now.”
Containers complicate this. From outside a container, py-spy needs the container’s PID namespace; from inside, it needs CAP_SYS_PTRACE. The cleanest production pattern is a sidecar with the same PID namespace as the app container.
The procedure
-
Install py-spy. The wheel is statically linked Rust — no Python install dependencies:
sudo pip install py-spy # or via pipx: pipx install py-spy -
Allow ptrace for the target user. The kernel default
yama.ptrace_scope=1only lets a parent process attach to its children — for a sudo’d profiler attaching to a Gunicorn worker, that’s fine. For unprivileged attach (e.g. on a hardened host where you can’t sudo), grant the capability to the py-spy binary:sudo setcap cap_sys_ptrace=eip $(which py-spy) -
Capture a 30-second flamegraph against a Gunicorn worker:
sudo py-spy record \ -o /tmp/gunicorn-app-$(date +%s).svg \ --pid $(pgrep -f "gunicorn.*app.wsgi" | head -1) \ --duration 30 \ --rate 10030 seconds at 100 Hz is 3000 samples — enough to see the shape, short enough not to slow the worker. For a worker that’s CPU-pegged, drop the rate to 50 Hz to lower overhead.
-
View the SVG. Open in a browser; bars are clickable to zoom in. The bar width is “samples in or under this function,” not wall-clock time, but the proportionality holds.
-
For a stuck process, use
dumpto see every thread’s current stack instantly:sudo py-spy dump --pid 12345Output is one block per thread, showing the Python call stack from the active frame outward. If you see every thread at
socket.recvin a queue worker, the queue is empty — not stuck. If you see them all atLock.acquire, you have lock contention. -
For a worker that crashes intermittently, run
recordagainst the parent and use--subprocessesto follow forks:sudo py-spy record -o /tmp/celery.svg \ --pid $(pgrep -f "celery worker" | head -1) \ --subprocesses --duration 60 -
In a Kubernetes deployment, add a sidecar with shared PID namespace:
spec: shareProcessNamespace: true containers: - name: app image: myorg/app:1.4.2 - name: profiler image: pyspy:0.3.14 command: ["sleep", "infinity"] securityContext: capabilities: add: ["SYS_PTRACE"]Then
kubectl exec -it <pod> -c profiler -- py-spy record --pid 1 -o /tmp/out.svg --duration 30.
Common pitfalls
- Running py-spy against a process that uses native extensions heavily (NumPy, SQLAlchemy with cython) — frames that are C-only appear as
[native code]or are missing from the stack, hiding the real cost. - Sampling at 1000 Hz: the overhead jumps to 5-10% and the SVG balloons. 100 Hz is the right default; 50 Hz for hot workers.
- Profiling a single worker out of N — you’re seeing one worker’s behaviour. If the worker handles a specific tenant or a specific endpoint, you may miss the slow path. Capture against several workers in turn.
- Forgetting
ptrace_scopeexists. On a freshly-installed host, the firstpy-spy dumpreturns “permission denied” and the obvious answer is sudo — but if even sudo fails, checkcat /proc/sys/kernel/yama/ptrace_scopeand either set to0for the session or use thesetcaproute. - Capturing flamegraphs of an async event loop with py-spy without
--idleflag — idle async tasks show as deep stacks inasyncio.events.Loop._run_once, drowning the actual work. Add--idleto omit them.
For invasive deterministic profiling under controlled conditions (a benchmark, a staging replica), see cProfile and flamegraph generation. Stack Harbor’s managed operations practice keeps py-spy pre-installed on every Python worker host and a sidecar pattern ready for containerized clients, so the on-call team can profile a slow worker in 30 seconds without a deploy.