Skip to the page

Performance and memory · mid

How Python frees memory, and finding leaks

CPython frees an object when its reference count reaches zero, and a cyclic garbage collector handles cycles. A leak is memory that grows with work and never levels off, and tracemalloc snapshots show which lines hold it.

The notes

What you must know

  • Each object counts references to it. At zero it is freed at once.
  • Cycles never reach zero, so a generational cyclic garbage collector finds unreachable groups. gc.collect() runs it by hand. weakref avoids cycles in caches and observer lists.
  • Freed memory often stays with the process (allocator arenas, fragmentation), so RSS does not always drop.
  • gc.freeze() before forking workers keeps pages shared longer.
  • Confirm a leak: memory grows with work done and never levels off. Reproduce with a loop of real jobs, then tracemalloc: start early (PYTHONTRACEMALLOC=25 or -X tracemalloc=25), snapshot, run N jobs, snapshot again, and use snapshot2.compare_to(snapshot1, "lineno").
  • tracemalloc tracks memory from Python allocators; memory a C library allocates directly may not show. memray also sees native allocations.
  • Usual causes: unbounded module-level dicts or lists, lru_cache(maxsize=None), lru_cache on methods (it keeps self alive), callbacks never removed, stored exceptions holding frames, threads never joined.
  • Short-term: recycle workers after N jobs and make work idempotent so retries do not send duplicates. Python 3.14.0 to 3.14.4 had an incremental garbage collector that caused memory pressure in some workloads; 3.14.5 reverted it, so use the latest 3.14.x.

The red pen

Common traps: mistake → fix

  • Mistake: Python has no memory leaks because of the garbage collector

    Fix: references held by caches and globals are never freed.

  • Mistake: Call gc.collect() after each job as the fix

    Fix: it does not free objects that are still referenced.

  • Mistake: Raising the memory limit solves it

    Fix: it only delays the kill.

  • Mistake: Restarting workers solved it

    Fix: it hides the cause.

Easy to hard

Questions interviewers ask, easy to hard

  1. How does Python free memory?
  2. Why does Python need a garbage collector if it has reference counting?
  3. A worker grows from 200 MB to 3 GB in six hours. How do you find the leak?
  4. Why can lru_cache on a method leak memory?
  5. What do you do today, before the fix?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview