When you ask "why does this Python process use 2 GB?", most tools give you a number and leave you guessing. Memray, Bloomberg's memory profiler, gives you the call stack behind every byte. It hooks the allocator, so it sees allocations made by Python code and by C extensions like NumPy, lxml or a database driver, which is where the standard library's tracemalloc goes blind. The cost is a capture file and some slowdown. What you get back is a flame graph of exactly what was alive at the moment memory peaked.
It runs on Linux and macOS only. Install it into the same environment as the code you're profiling:
python -m pip install memray pytest-memrayA program worth profiling
This is a typical report script: read a JSON Lines file of events and count clicks per user. It's correct, and it's the kind of code that's fine on a 10 MB file and falls over on a 10 GB one.
import json
import sys
from collections import Counter
def load_events(path: str) -> list[dict[str, object]]:
with open(path) as fh:
return [json.loads(line) for line in fh]
def clicks_per_user(path: str) -> Counter[str]:
events = load_events(path)
return Counter(str(e["user"]) for e in events if e["kind"] == "click")
if __name__ == "__main__":
top = clicks_per_user(sys.argv[1]).most_common(3)
print(top)memray run, then a report
Memray separates capturing from reporting. memray run executes your program and writes every allocation and deallocation to a binary file. Reporter commands turn that file into something you can read, as many times as you like and in different formats:
memray run -o report.bin report.py events.jsonl
memray stats report.bin
memray flamegraph report.binmemray run accepts a script, -m module like the python command, or -c for a string, so a web server is memray run -m uvicorn app:app. Stop it with Ctrl-C and the capture is still written. Against a 300,000-line, 17 MB events file, memray stats printed this, trimmed to the parts that matter:
📏 Total allocations:
1204832
📦 Total memory allocated:
880.221MB
📈 Peak memory usage:
166.400MB
🥇 Top 5 largest allocating locations (by size):
- decode:.../json/decoder.py:339 -> 368.346MB
- decode:.../json/decoder.py:338 -> 328.500MB
- raw_decode:.../json/decoder.py:354 -> 115.354MB
- load_events:report.py:8 -> 41.130MBThe distinction between those first two numbers is the most useful thing on the screen. Total allocated is the sum of every allocation over the run, including memory freed a microsecond later, so it tells you about allocator churn and speed. Peak is the most memory that was alive at once, and that's what gets a container OOM-killed. A 17 MB file turning into a 166 MB peak says the program holds far more than the input at some point. The "top locations by size" list ranks by total allocated, which is why the JSON decoder tops it. It doesn't tell you what was alive at the peak. The flame graph does.
Reading the flame graph
memray flamegraph report.bin writes memray-flamegraph-report.html, which you open in a browser. It loads its JavaScript from a CDN, so pass --no-web if you'll view it offline. By default it shows the high watermark: the allocations that were still alive at the moment the process's heap was largest. As the flame graph docs put it, each box's width is how much memory that function and its children allocated. Your entry point is at the top and callees stack below it.
For this script, nearly the full width runs <module> to clicks_per_user to load_events to the list comprehension to json.loads. That's the diagnosis in one picture: at the peak, nearly all live memory is the list of 300,000 parsed dicts. Each dict with its keys, strings and ints costs several hundred bytes, so a 60-byte line becomes many times that in memory. The streaming version keeps one event at a time:
import json
import sys
from collections import Counter
from collections.abc import Iterator
def iter_events(path: str) -> Iterator[dict[str, object]]:
with open(path) as fh:
for line in fh:
yield json.loads(line)
def clicks_per_user(path: str) -> Counter[str]:
return Counter(str(e["user"]) for e in iter_events(path) if e["kind"] == "click")
if __name__ == "__main__":
top = clicks_per_user(sys.argv[1]).most_common(3)
print(top)Run the same commands on it and the peak drops from 166 MB to about 1.2 MB, almost all of it the Counter. Your numbers will vary a little with the platform and Python build, but the shape won't. Two habits make flame graphs easier to read. Use the search box to highlight your own package's frames, and turn off the import system filter only when you suspect import-time memory. --inverted flips the graph so the functions that made the allocations sit at the root, which groups memory by allocation site instead of by caller.
For a server that grows slowly, --temporal is the better view. It adds a chart of memory over time at the top of the page with two sliders, and the flame graph below shows the peak within whatever window you select. Pick the window where the line climbs and you see what was allocated during the climb.
Leaks mode, and why PYTHONMALLOC matters
The default view answers "what made the peak". --leaks answers a different question: what was allocated and never freed by the time tracking stopped.
PYTHONMALLOC=malloc memray run -o worker.bin worker.py
memray flamegraph --leaks worker.binThe environment variable isn't optional decoration. CPython's pymalloc allocator grabs memory from the system in large arenas and hands out small objects from them, so from the outside a freed object often looks like memory that was never released. The memray docs recommend PYTHONMALLOC=malloc for leak reports so every Python object goes straight to the system allocator, where memray sees its true lifetime. The alternative is --trace-python-allocators, which records pymalloc's allocations directly at the cost of much larger capture files. Without either, leak reports show false positives from the arenas.
Leaks mode also needs a clean stopping point. Anything still alive at exit counts, including module globals and caches that are meant to live forever. Exercise the suspect code path many times so that the real leak dominates the one-off noise. The general workflow for leaks, including tracemalloc snapshot diffs and finding which reference holds an object, is in the guide to finding and fixing Python memory leaks.
Native frames and child processes
By default the stacks show Python frames only. When the wide box ends in a call into a C extension, add --native to capture the C and C++ frames as well. That's how you tell whether memory went into NumPy's array buffer or into a driver's internal cache. It costs some speed, and the report has to be generated on the same machine that made the capture, because it resolves symbols from the local binaries.
--follow-fork records children created with fork(), one capture file per process, which is what you want for gunicorn-style pre-fork servers or multiprocessing with the fork start method. It doesn't work with live mode. For long captures, --aggregate writes summarised data instead of every event, so the file stays small, but you lose temporal reports and the stats reporter.
Live mode and attaching to a running process
Sometimes you don't want a file, you want to watch. memray run --live starts the program and opens a terminal UI showing the functions that currently hold the most memory, refreshed as it runs. For a server, it's often nicer in two terminals:
# terminal 1: start the app and wait for a viewer
memray run --live-remote -m uvicorn app:app
# terminal 2: connect using the port memray printed
memray live 61435The port is random unless you pass --live-port. Live mode is the fastest way to answer "does memory go up when I hit this endpoint", because you can make requests and watch the rows move.
For a process that's already running and already bloated, memray attach <pid> injects the tracker into it. Memray has to be installed in that process's environment. On Python 3.14 and later it uses sys.remote_exec(). On older versions it needs gdb or lldb, plus ptrace permission, which on many Linux systems means root or CAP_SYS_PTRACE, and --cap-add=SYS_PTRACE in Docker. Add -o and --duration to record for a fixed number of seconds into a file instead of a live session. Take the attach docs seriously when they say injection can crash or deadlock the target and is meant for development machines. Attaching to a production process is a decision, not a habit. Note that attach only sees allocations made after it attaches. Memory that's already allocated doesn't appear, so it shows you growth, not the existing heap.
You can also start tracking from inside the program, which suits a batch job you want to profile on its own schedule:
import memray
from report_stream import clicks_per_user
def nightly_job(path: str) -> None:
with memray.Tracker("nightly.bin", native_traces=False, follow_fork=False):
print(clicks_per_user(path).most_common(3))
if __name__ == "__main__":
nightly_job("events.jsonl")Memory limits in tests with pytest-memray
A flame graph fixes today's problem. pytest-memray stops it coming back. Run the suite with pytest --memray and every test is tracked, and you get a summary of the biggest allocators per test. Two markers turn that into assertions: limit_memory fails a test whose peak exceeds a budget, and limit_leaks fails a test if any single call stack leaks more than its limit.
from pathlib import Path
import pytest
import report
import report_stream
DATA = Path(__file__).parent / "small.jsonl"
_leaked: list[bytes] = []
@pytest.mark.limit_memory("5 MB")
def test_streaming_report_stays_small() -> None:
assert report_stream.clicks_per_user(str(DATA))
@pytest.mark.limit_memory("5 MB")
def test_list_report_stays_small() -> None:
assert report.clicks_per_user(str(DATA))
@pytest.mark.limit_leaks("1 MB")
def test_no_leaks() -> None:
_leaked.append(b"x" * 2_000_000)Against a 40,000-line sample file, the streaming test passes, and the other two fail with messages that say exactly what went wrong:
Test was limited to 5.0MiB but allocated 20.5MiB
Test was allowed to leak 1.0MiB per location but at least one location leaked moreThe leak failure also prints the stack of each leaking allocation. A few options are worth knowing. --most-allocations=10 lists the ten hungriest tests, a quick way to find the next thing to fix. --stacks=N controls how many frames the failure output shows, and --native adds C frames. --fail-on-increase fails a limit_memory test that uses more memory than its last passing run, which catches gradual regressions without having to retune budgets.
The plugin's docs recommend running the code under test in a loop for limit_leaks, and the same PYTHONMALLOC caveat applies, so set PYTHONMALLOC=malloc for that job. Give tests generous budgets at first, because peaks differ between macOS and Linux and between Python builds. Then tighten them once you've seen a few CI runs. For async services, a common reason those leak tests fail is an HTTP client that's created per call and never closed, which has its own write-up on unclosed httpx and aiohttp sessions.
Memray versus the alternatives
tracemalloc ships with Python and needs no install, and its snapshot diffs are great at "which line allocated what grew between these two points". It only sees memory that goes through Python's allocators, though, and it has no flame graph. Memray sees native allocations, records the full timeline, and its reports are much easier to share. The trade-off is a dependency, a capture file that can reach gigabytes for long runs, and no Windows support. If your question is time rather than memory, a sampling CPU profiler is the right tool, and finding the actual bottleneck covers those.













