Skip to content

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

Key points

  • RSS rarely shrinks in CPython even after objects are freed; watch the trend.
  • tracemalloc snapshots compared over time point to the growing allocations.
  • Unbounded caches and module-level lists are the usual leaks.
  • Worker recycling contains slow leaks while you fix them.

Measuring

python
import os, resource, psutil  # psutil is a third-party package

proc = psutil.Process(os.getpid())
print("rss MB", proc.memory_info().rss / 1e6)
print("peak MB (Linux KiB)", resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024)

Finding growth with tracemalloc

python
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

Common causes

CauseFix
Module-level cache dict that only growsfunctools.lru_cache(maxsize=...) or a TTL cache
Loading whole query results or filesIterate, stream, paginate
Large pandas DataFrames copied repeatedlySelect columns, use categories and smaller dtypes, process in chunks
Reference cycles with __del__ or C extensionsBreak cycles; check gc.garbage
Fragmentation in long-lived workersRecycle workers (gunicorn --max-requests)

Long-running workers

For gunicorn, --max-requests 1000 --max-requests-jitter 100 restarts each worker after a number of requests, which caps slow leaks. Celery has --max-tasks-per-child and --max-memory-per-child. These are safety nets; find the leak with tracemalloc too.

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.

Alerts to start with

Alert when a worker's memory stays above 85 to 90% of its container limit, when restart or OOM-kill counts rise, and when memory per request grows release over release. Keep a runbook that says how to take a tracemalloc snapshot on one worker safely.

Find what is using memory

python
import tracemalloc
tracemalloc.start(25)
# ... run the code that grows ...
snapshot = tracemalloc.take_snapshot()
for stat in snapshot.statistics('lineno')[:10]:
    print(stat)
ToolUse
tracemallocBuilt in: which lines allocated the memory still in use
memrayDetailed allocation profiles, including native extensions
objgraphWhich 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.

Frequently asked questions

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.

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.