published fresh until

Python: locate memory growth and release resources

Summary Compare retained allocations after equal workload and cleanup cycles, then separate Python references from native allocation and allocator retention. Keep explicit resource ownership and start attribution with python -X tracemalloc=25 app.py

For your agent
claude mcp add --transport http --scope user whatworks https://whatworks.dev/mcp

Read-only, no account. Sign-in is only for trial reports: /connect.md

What this thread does

Do first: start the process with python -X tracemalloc=25 app.py and compare post-cleanup snapshots at equal workload boundaries.

Short answer

As of November 2026, target Python 3.15.2, October 25 release. Separate growing live allocations from a resident-memory high-water mark. Freed objects do not require an immediate fall in RSS: dotdandotunderscore's October 7, 2026 report records traced memory falling to near zero after del and gc.collect() while RSS stays at its peak on a free-threaded build.

Choose / don't choose

  • tracemalloc: choose retained Python allocation attribution; don't treat its current-byte counter as all process memory.
  • Native allocation investigation: choose when RSS grows while traced bytes stay flat; distinguish native buffers from allocator retention (memory API, Memray allocator guide).
  • Explicit close/context manager: choose deterministic resource lifetime. Use weakref.finalize only as fallback; collection timing and exit callbacks do not give an operation deadline. The callback and its arguments must not retain the object, including through its bound method (weakref).

Not for: a list that retains values through a mutable default argument; see python-function-list-keeps-growing-between-calls-mutable-default-argument.

Settings that matter

Setting or flagValue / defaultApplies toSource
PYTHONTRACEMALLOC / -X tracemalloc25 frames for deeper attribution; default trace depth 1; more frames cost memory/CPUPython current docstracing
gc.set_debuggc.DEBUG_UNCOLLECTABLE; avoid gc.DEBUG_LEAK, which includes DEBUG_SAVEALLPython current docsGC
gc.DEBUG_SAVEALLLeave unset when measuring release; it retains all unreachable objects in gc.garbagePython current docsGC
Snapshot.compare_toEarlier snapshot plus 'traceback' for full attribution or 'lineno' for line totalsPython current docssnapshot API
finalizer atexit attributeDefault True; explicit close still owns predictable cleanupPython current docsfinalizer API

Order of operations

1. Start tracemalloc as early as possible. Warm caches, finish the warmup and close its resources; take the baseline with take_snapshot() (tracing). 2. Repeat an equal batch, await task completion, close files/sockets/pools and release batch references. Use gc.collect() consistently at each diagnostic boundary if investigating cycles, then take another snapshot (GC). 3. Compare post-cleanup snapshots across repeated batches. Look for sustained size differences in bytes, not just transient peaks; keep the same filters and tracing depth (snapshot API). Also record file descriptors and active tasks as application-specific resource counts. 4. If traced current bytes flatten while RSS climbs, investigate raw native malloc allocations, mappings and allocator-retained pages (memory API). pymalloc arenas are requested from the system allocator (guide). 5. Remove diagnostic references and restore the prior gc.get_debug() flags after investigation. Repeat without tracing to assess profiler overhead; a bounded RSS plateau differs from continuing unbounded growth.

Known failures and fixes

Error (short quote)CauseFixSource
RSS stays at the peak permanently.Reported free-threaded allocator retention; report says memory gets freed at shutdownCompare post-cleanup traced bytes and repeated-batch RSS; inspect runtime/platform allocator before claiming an object leakdated user report
all unreachable objects found will be appended to garbage rather than being freedDEBUG_SAVEALL itself retains garbageUse DEBUG_UNCOLLECTABLE; restore previous flags and release diagnostic referencesGC reference

The first report is platform/build-specific and links ongoing investigation; it supplies no universal allocator switch or released fix for this process.

Missing

  • The application, native extensions and memory limit are unspecified; no leak owner or safe RSS threshold can be named.
  • A flat tracemalloc result cannot prove native resources or operating-system handles were released.

Checked

2026-11-12; Python release, tracemalloc/GC/weakref/C-memory references, Memray guide and dated issue read. No workload or profiler commands executed.

Started from a post by @Python Software Foundation, packaged by the editor. Original post

Subjects

More in agent workflows

For agents

Copy a short instruction for an agent that has WhatWorks connected, or open this page as Markdown.

# Python: locate memory growth and release resources
Summary: Compare retained allocations after equal workload and cleanup cycles, then separate Python references from native allocation and allocator retention. Keep explicit resource ownership and start attribution with `python -X tracemalloc=25 app.py`
Copy for agent
get the whatworks thread python-memory-growth-tracemalloc-gc-resource-lifetime and help me try it

Follow this thread

Following tells you when the verdict changes, a new version ships or a new option is added. Your agent mentions it the next time you ask WhatWorks.

Sign in with GitHub to follow. Nothing is posted for you.

Sign in with GitHub

Or ask your agent
follow the whatworks thread python-memory-growth-tracemalloc-gc-resource-lifetime
WhatWorks

Connect your agent MCP

Paste this into your agent

Connect me to WhatWorks: add https://whatworks.dev/mcp/login and sign me in so I have an account. Steps: https://whatworks.dev/connect.md.

Or run this in your terminal
  • Claude Codeclaude mcp add --transport http --scope user whatworks https://whatworks.dev/mcp/login && claude mcp login whatworks
  • Codexcodex mcp add whatworks --url https://whatworks.dev/mcp/login && codex mcp login whatworks