How-to guide
Python memory usage: find what uses memory
Python processes often grow until they are killed. tracemalloc shows which lines allocate the memory that stays, and a few patterns explain most growth.
4 min read13 sectionsUpdated
On this page
import tracemalloc
tracemalloc.start(25) # keep 25 frames per allocation
before = tracemalloc.take_snapshot()
handle_many_requests() # or wait a few minutes under real load
after = tracemalloc.take_snapshot()
for stat in after.compare_to(before, "lineno")[:15]:
print(stat) # lines whose retained memory grew most| Cause | Fix |
|---|---|
| Module-level cache dict that only grows | functools.lru_cache(maxsize=...) or a TTL cache |
| Loading whole query results or files | Iterate, stream, paginate |
| Large pandas DataFrames copied repeatedly | Select columns, use categories and smaller dtypes, process in chunks |
| Reference cycles with __del__ or C extensions | Break cycles; check gc.garbage |
| Fragmentation in long-lived workers | Recycle workers (gunicorn --max-requests) |
Watching it continuously
Chart each process's or pod's memory against its limit in VitalRix infrastructure monitoring and alert before it is OOM-killed. APM deploy markers show which release started the growth. See also Python performance monitoring.
Data-heavy code
Most large Python memory spikes come from loading data: a whole table into a list of dicts, a CSV into a DataFrame with default types, or JSON responses kept in a module-level cache. Stream rows with server-side cursors, read files in chunks, choose smaller dtypes and categories for repetitive strings, and delete intermediate DataFrames you no longer need. Measure each change with tracemalloc or memray rather than guessing.
import tracemalloc
tracemalloc.start(25)
# ... run the code that grows ...
snapshot = tracemalloc.take_snapshot()
for stat in snapshot.statistics('lineno')[:10]:
print(stat)| Tool | Use |
|---|---|
| tracemalloc | Built in: which lines allocated the memory still in use |
| memray | Detailed allocation profiles, including native extensions |
| objgraph | Which object types grow, and what keeps them alive |
| RSS per worker (ps, process metrics) | Is it growing over time in production? |
Where Python memory goes
- Caches without limits: dictionaries or lru_cache without maxsize that grow forever.
- Loading whole files or query results into memory instead of streaming them.
- Pandas copies: chained operations create copies; use dtypes that fit and process in chunks.
- Long-lived workers in Gunicorn or Celery that slowly grow; max_requests (Gunicorn) or max_tasks_per_child (Celery) recycles them while you look for the real cause.
- Memory that is freed but not returned to the OS, which looks like a leak in RSS; watch whether it keeps growing or levels off.
Why does memory not go down after I delete objects?
CPython keeps freed memory in its own allocator pools for reuse, so RSS often stays flat. A leak shows as continued growth, not a failure to shrink.
Is there a Python heap dump?
Tools such as memray and guppy give detailed views; tracemalloc is built in and usually enough to find the growing line.
Related reading
- How to find a Node.js memory leak: Detect a Node.js memory leak from heap metrics, compare heap snapshots to find what retains memory, fix the usual causes and alert before a crash.
- Goroutine leaks in Go: how to find and fix them: Find and fix goroutine leaks in Go: read pprof goroutine profiles, spot blocked channels and missing context cancellation, and use goleak in your tests.
- Java memory usage: heap, metaspace and leaks: Understand Java memory usage: heap, metaspace, threads and direct memory, why RSS exceeds -Xmx, how to size for containers.
- Redis monitoring: metrics that matter: Monitor Redis with INFO: memory and evictions, hit rate, clients, latency, persistence and replication, with thresholds and the alerts to set.
- Prometheus high cardinality: how to find and fix it: Find and fix Prometheus high cardinality: use the TSDB status page and promtool, identify runaway labels and drop them with relabeling rules before ingestion.
- .NET OutOfMemoryException: causes and how to fix it: Fix .NET System.OutOfMemoryException: use dotnet-counters and dotnet-gcdump, spot Large Object Heap fragmentation and set the right GC limits in containers.
Watch your own site and services with VitalRix
Uptime checks, APM, logs, real-user monitoring, alerts and status pages in one place. Every product has a free tier and no credit card is needed.