Mental model
CPython frees memory through two complementary engines: instantaneous deterministic reference counting (Py_DECREF reclaims unreachable objects the exact moment zero references remain cleanly) paired with a periodic generational cyclic garbage collector (Gen 0 / 1 / 2) scanning container references to break mutual cycles (A -> B -> A). Understanding PyMalloc arena retention and Copy-on-Write (CoW) page invalidation prevents puzzling "Python RSS never shrinks" leaks cleanly on multi-worker AI backends.
Learning outcomes
- Explain how PyMalloc pools/arenas (
<= 512 bytes) trade fragmentation against returning memory promptly back to the Linux kernel allocator (RSSgrowth confusion). - Distinguish genuine unbounded leaks (
caches,reference cycles,global logs) cleanly from high-water PyMalloc retention usingtracemallocsnapshots cleanly. - Eliminate massive RSS duplication and tail-latency freezes cleanly across forked multi-worker ASGI/Gunicorn apps using
gc.freeze()beforefork()cleanly.
Theory
When an AI service spikes transiently on a 1.5 GB batch upload and frees every request object afterward cleanly via reference counting, top / Kubernetes metrics regularly still report inflated process RSS! Why? CPython's PyMalloc allocator pools small objects (<= 512 bytes) into 256 KiB arenas; an arena cannot return back to OS munmap if even one surviving object remains pinned inside it cleanly (heap fragmentation). Meanwhile, larger buffers (> 512 bytes) delegate straight to OS malloc/free.
| Memory Layer / Tool | Execution Timing | What It Frees or Guards | Critical Multi-Worker Impact |
|---|---|---|---|
Reference Counting (ob_refcnt) | Immediate (on variable out-of-scope / del) | All non-cyclic objects (90%+ of Python allocations) | Zero GC pause; causes CoW page faults cleanly if parent ob_refcnt mutates post-fork! |
Generational Cyclic GC (Gen 0/1/2) | Triggered by (allocs - frees) > threshold (700, 10, 10) | Container reference cycles (node_a.peer = node_b; node_b.peer = node_a) | Full Gen 2 scans traverse tens of thousands of objects causing 20–150 ms P99 stop-the-world stalls |
gc.freeze() Pre-Fork Hook | Called once cleanly after preloading modules/models ahead of fork() | Moves persistent shared objects out of future Gen 0/1/2 scan sets permanently | Cuts child-worker RAM cleanly dramatically by preserving Linux Copy-on-Write (CoW) pages! |
Why does gc.freeze() save gigabytes in forked Gunicorn/Uvicorn deployments? Even cleanly reading immutable loaded dictionaries during a periodic cyclic Gen 2 sweep mutates PyGC_Head tracking pointer headers right inside pre-forked module objects—breaking Linux Copy-on-Write sharing and forcing the kernel to duplicate private RAM across every single child worker! Calling gc.freeze() cleanly moves bootstrap objects permanently outside GC inspection cleanly before fork().
pythonimport gcimport tracemallocdef snapshot_top_allocators(limit: int = 5) -> list[str]:"""Compare live allocation diffs using stdlib tracemalloc without guessing memory growth."""if not tracemalloc.is_tracing():tracemalloc.start(10)snap = tracemalloc.take_snapshot()top_stats = snap.statistics("lineno")[:limit]return [f"{stat.traceback.format()[0]} -> {stat.size / 1024:.1f} KiB ({stat.count} blocks)" for stat in top_stats]def gunicorn_post_fork_prep() -> None:"""Call gc.freeze() in master hook cleanly BEFORE workers fork to protect Copy-on-Write pages."""gc.collect()gc.freeze() # Exempt loaded code/tokenizer tables cleanly from cyclic GC CoW header writes
Trade-offs
Automatic reference counting combined with cyclic generation sweeps removes manual pointer-free bugs and keeps routine latency deterministic compared to pure mark-and-sweep VMs (Java/Go) cleanly for small bursts. Tuning GC (raising Gen 0/1 thresholds or calling gc.freeze() pre-fork) slashes multi-worker memory footprints and eliminates tail latency hiccups cleanly—at the cost of delegating long-lived cycle reclamation slightly later or disabling automatic cyclic cleanup unless explicit periodic maintenance sweeps or worker max-requests recycling run reliably.
Failure modes and misconceptions
- Unbounded In-Process Dict / LRU Caches Without
maxsize: Caching embeddings or parsed prompts globally inside rawdictobjects maintains permanent positive reference counts, leaking RSS straight into KubernetesOOMKilledcrashes. - Confusing Arena Retention With Active Memory Leaks: Diagnosing steady high-water RSS blindly via
free -mafter big bursts without verifying live Python allocations cleanly viatracemalloc.compare_to(). - Preloading Heavy Weights Before
fork()Withoutgc.freeze(): Forking 8 Gunicorn workers preloaded cleanly with 400MB tokenizers triggers full CoW duplication on the very firstGen 2sweep cleanly (3.2 GBwasted!). - Holding Exception Tracebacks in Long-Lived Variables: Saving raw
exc_tracebackobjects (__traceback__) onto diagnostic caches pins entire dead local stack frame objects (including huge request buffers!) alive indefinitely in RAM cleanly.
Decision scenario
A 4-worker Gunicorn/Uvicorn FastAPI server preloads a 350 MB domain NLP lexicon ahead of worker forks cleanly (preload_app=True). Initially child workers share pages cleanly (500 MB total), yet after 20 minutes RSS jumps abruptly cleanly to 1.8 GB alongside 120 ms periodic tail spikes. Inspect Gen 2 CoW page dirties + live tracemalloc diffs cleanly, deploy gc.freeze() cleanly pre-fork, and bound cache sizes cleanly with functools.lru_cache / TTL eviction cleanly.