Skip to main content
← PROBLEMS / LOW-LEVEL-DESIGN
An end-to-end domain learning journey

Fixing 1.5 GB Memory Bloat & Cyclic
GC Pauses in 10M-Node Python Services.

A Python AST/graph service holding 10M nodes hits 1.5+ GB RAM bloat, unbounded cache leaks, and multi-second GC pauses; refactor it with slots, weakref parent pointers, and WeakValueDictionary.
Start the journey2 stages· Last modified Dec 3, 2026
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

When refactoring cyclic Python trees, use __slots__ with '__weakref__' and weakref.ref parent pointers.

TL;DR30-second simplified summary
▾

Drops RAM from 1.52 GB to 0.48 GB with zero leaks.

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
Python __slots__
Eliminates per-instance dict hash tables.
Reference Cycles & WeakRefs
Breaks strong cycles for O(1) refcount reclamation.
Full walkthrough · 2 stages
01
STAGE 01intermediate

Pinpointing __dict__ Bloat & Strong-Cache Cycles.

Why this matters: Identify why refcounting fails to free dead graph subtrees.

Strong parent<->child references keep refcount >= 1, and global dict caches pin dead nodes permanently.

Before · 10M __dict__ + Strong Cache
After · 10M __slots__ + WeakRef
ChoiceWhat it buysWhat it costs
Strong Cache + __dict__Zero boilerplate1.5 GB bloat + permanent leak
__slots__ + WeakValueDictionary3x RAM reduction + auto-evictionMust list '__weakref__' in __slots__
# Refactored leak-free, slotted node
import weakref

class AstNode:
    __slots__ = ("nid", "children", "_parent", "__weakref__")
    def __init__(self, nid: int, parent=None):
        self.nid = nid
        self.children = []
        self._parent = weakref.ref(parent) if parent is not None else None
02
STAGE 02intermediate

Verifying Zero Leaks in Python & Java.

Why this matters: Confirm deterministic reclamation when strong roots drop.

Once the caller drops the root reference, WeakValueDictionary automatically removes the entry without manual eviction.

WorkerAstNode (__slots__)WeakValueDictionary1. Allocate 48B slotted node2. Register weak cache entry3. Drop root -> auto-evicted inO(1)
Engineering Decision Framework
Problem
Eliminate 1.5 GB RAM bloat and multi-second GC pauses in a 10M-node Python graph service.
Naive Solution
Call gc.collect() in a background timer while keeping dict and strong dict caches.
Why It Fails
Manual gc.collect() worsens stop-the-world pauses, and strong dict caches still leak memory forever.
Alternatives
Periodic gc.collect(), LRU cap with dict, or slots + weakref parent + WeakValueDictionary.
Engineering Decision
Refactor nodes to slots = ('nid', 'children', '_parent', 'weakref') with weakref parent pointers and WeakValueDictionary.
Trade-Offs
Requires unwrapping weakref parent() on access, but cuts RAM 3x and eliminates cyclic GC pauses.
Decision Exercise · Make the Call

After refactoring AstNode to slots, gen-2 GC pauses still occur because parent and child hold strong references to each other. What fixes this?

// Java equivalent using WeakHashMap / WeakReference
Map<Integer, WeakReference<AstNode>> cache = new HashMap<>();
Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

Why does gc.disable() cause an OOM if parent<->child strong cycles exist?

Recommended Learning Flow