01C.6 Python Memory Management

FoundationsLesson 6 of 722,686 words11 parts
Module 01C · 0 of 7 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7

An AI service is a long-running process that holds a lot of things in memory: a tokenizer, a loaded embedding matrix, a cache of model answers, hundreds of in-flight requests each carrying prompts and responses. Sooner or later someone asks the questions this lesson answers. Why did the container get killed for using 4 GB when the data is 600 MB? Why does memory never go down after the nightly import finishes? Why did four worker processes use four times the memory we expected? Is this a leak, or is Python just like that? Python hides memory management so well that most people never learn how it works until the day it hurts. This lesson takes the lid off. You will learn what an object really is, how reference counting frees most memory instantly, what the cyclic garbage collector is for (and what it cost in Python 3.14), how Python's small-object allocator pymalloc carves memory into arenas, pools and blocks, and why that makes RSS (the number your operating system shows) a poor mirror of what your program is using. Then it turns practical: shrinking data structures, the leaks that are not leaks, a measuring toolbox (tracemalloc, gc, resource, and awareness of memray and friends), a step-by-step leak hunt on a deterministic example, and the memory shape of real AI workloads.

Lesson 01C.5 explains why reference counting and the GIL are linked. This lesson uses only the consequences: memory is managed per object, one count at a time, and that single design decision explains most of what follows. Lesson 01C.7 picks up where Part 5 here ends: how processes can share memory deliberately instead of by accident.

What you'll learn

  • What a Python name, a reference and an object are, why b = a never copies, and how id(), is and == differ
  • What an object looks like in memory (the header, the GC header), what sys.getsizeof measures and what it silently leaves out, and a recursive size helper that counts shared objects once
  • Reference counting step by step with sys.getrefcount: what raises and lowers a count, why destruction is immediate and deterministic in CPython, and what the 3.12 immortal objects change
  • The small-integer cache, string interning and constant folding: why a is b sometimes works, why you must never rely on it, and when sys.intern saves real memory
  • Weak references (weakref.ref, WeakValueDictionary, weakref.finalize): caches and registries that do not keep objects alive
  • Reference cycles and the cyclic garbage collector: generations, thresholds, gc.collect, gc.freeze, gc.callbacks, what shipped in Python 3.14.0 to 3.14.4 (an incremental collector) and why Python 3.14.5 reverted it
  • Finalizers: __del__, PEP 442, resurrection, gc.garbage, why __del__ is the wrong tool for cleanup, and what to use instead
  • The memory allocator layers: pymalloc (arenas, pools, blocks and size classes, with real sys._debugmallocstats() output), PYTHONMALLOC, mimalloc in the free-threaded build, fragmentation, and the honest answer to "why does RSS not drop?"
  • Copy-on-write and fork: why reading Python objects in a child process copies memory, and the gc.freeze recipe from the official docs
  • Shrinking memory: __slots__ and @dataclass(slots=True), tuples and columns, generators instead of lists, array, bytes, bytearray and memoryview, wide strings, mutable default arguments
  • The leaks that are not leaks (unbounded caches, lru_cache on methods, global registries, tracebacks that hold frames, asyncio tasks that are only weakly referenced) and how to write a bounded cache
  • The measuring toolbox: RSS vs VMS vs USS vs PSS, resource.getrusage, tracemalloc snapshots and diffs, gc.get_objects and gc.get_referrers, memray, scalene, py-spy (and what it is not)
  • A complete leak investigation, step by step, and a reusable "does this function leak?" test
  • Memory in AI workloads: embedding matrices and float32, loading large JSONL files, streaming and batching, concurrency multiplied by per-request memory, worker recycling, and what free-threaded builds change

What you don't need

  • Any C knowledge. Where the C side matters (Py_INCREF, malloc), you get a plain-English version first and the Python-visible consequence second.
  • NumPy, psutil, memray or any other third-party package. Every experiment uses the standard library. Third-party tools appear only as clearly labelled awareness sections and are not run.
  • Lessons 01C.1 to 01C.5. They help (threads, processes, the GIL), but this lesson stands on its own. The few places where it touches them link back.

Setup

No API key needed, nothing to install, no network. You need Python 3.11 or newer; the outputs below were produced on Python 3.14.6 (the default, GIL-enabled build) on macOS with an Apple-silicon (arm64) processor. Create a scratch folder and run each snippet with python3 file.py (macOS/Linux/WSL) or py file.py (Windows PowerShell). Three honest caveats apply to the whole lesson:

  1. Sizes are build-specific. An empty list is 56 bytes on this build; on another build or version it can differ. Where a number is deterministic on the stated build, it is labelled Output:; where it varies by machine (RSS, arena counts, timings), it is labelled illustrative. Learn the shapes (a list of floats costs about four times an array of floats), not the byte counts.
  2. RSS is measured differently on every operating system. macOS and Linux disagree about when freed memory leaves a process, so any experiment that prints RSS is labelled illustrative. The lesson is explicit about which claims are portable and which are not.
  3. Much of this is CPython implementation detail. The small-int cache, interning, immediate destruction on refcount zero, pymalloc: none of these is a language guarantee, and several changed between 3.11 and 3.14. PyPy and other implementations behave differently. The lesson marks each such fact so you do not build on sand.

What you must be able to do after this lesson#

  • Explain names, references and objects and why b = a never copies
  • Explain how reference counting frees objects
  • Explain what the cyclic garbage collector adds
  • Find a memory leak with tracemalloc
  • Use slots and generators to cut memory use
  • Explain why forked workers copy memory and how gc.freeze helps
  • Write a bounded cache that does not leak

Why this matters for an AI engineer#

AI services are unusually memory-hungry and unusually long-lived. A single process may hold hundreds of megabytes of vectors, load a million-line corpus, fan out to hundreds of concurrent model calls whose prompts and responses are large, and keep running for weeks. Every cost in this lesson shows up in the cloud bill (bigger instances, or killed containers that restart and lose their cache) long before it shows up as a bug.

You'll hear... You'll understand it after...
"b = a copied my list, but now both changed." 1.1 names and objects, 1.3 assignment never copies
"sys.getsizeof says my dict is 184 bytes but the process grew by gigabytes." 1.5 what sys.getsizeof leaves out
"Python frees memory the instant the last reference goes." Part 2 reference counting
"Why does a is b work for 256 but not 257?" 2.5 small ints, interning and constants
"Use a weak reference so the cache doesn't keep it alive." 2.6 weak references
"That's a reference cycle; the garbage collector will get it eventually." Part 3 cycles and the cyclic GC
"The 3.14 garbage collector was reverted in 3.14.5?" 3.4 what shipped in 3.13 and 3.14
"__del__ didn't run / ran at a strange time." 3.5 finalizers
"I freed everything, but RSS stays high." Part 4 allocators, 4.5 why RSS does not drop
"Four workers use four times the memory." Part 5 fork and copy-on-write
"Use __slots__, generators, array, memoryview." Part 6 shrinking data
"It's a leak!" (is it?) Part 7 leaks that are not leaks, Part 9 the investigation
"Which tool shows where the memory went?" Part 8 measuring
"How much RAM does a million embeddings need?" Part 10 memory in AI workloads

Part 1: Objects, names and references#

1.1 Names are labels, objects are boxes#

Almost every surprise in Python memory comes from one mental-model error, so start here. In many languages a variable is a box that holds a value. In Python it is the other way around: an object is the box (it lives somewhere in memory, has a type and a value), and a name is a sticky note with a word written on it, stuck to a box. Assigning b = a does not copy the box. It sticks a second note on the same box.

A useful analogy for a service: a shared document in a team folder. Sending a link to the document is b = a: both of you now see the same document, and an edit by one shows up for the other. Emailing a printed copy is copy.copy. Everything in this lesson is about who holds links, and when the document can finally be deleted.

1.2 Identity, equality and id#

Python gives you three separate questions about two values:

Question Spelling Meaning
Are these the same object? a is b Same box: identical identity
Do these hold equal values? a == b Calls a.__eq__(b): boxes with equal contents
What is the object's identity? id(a) A number unique among live objects; in CPython it is the object's memory address

id() is only guaranteed unique while the object is alive: after it is freed, a new object can reuse the number. Never store id() values as long-term keys, and never treat them as stable across runs.

1.3 Assignment never copies#

The first experiment shows the sticky-note model and the usual shallow-versus-equal confusion:

python
# e01_objects.py: names, references, identity, sizes
import sys

a = [1, 2, 3]
b = a              # a second NAME for the same object, not a copy
c = list(a)        # a new object with equal contents
print("a is b:", a is b, "| a is c:", a is c, "| a == c:", a == c)
b.append(4)
print("a after b.append(4):", a)
print("c unchanged:", c)

# sys.getsizeof measures ONE object, not what it references
print("--- sys.getsizeof (bytes, this build) ---")
for label, obj in [
    ("None", None), ("True", True), ("0", 0), ("1", 1), ("2**30-1", 2**30 - 1),
    ("2**30", 2**30), ("2**60", 2**60), ("2**100", 2**100),
    ("1.5", 1.5), ("''", ""), ("'a'", "a"), ("'abcdefghij'", "abcdefghij"),
    ("'é'", "é"), ("'€'", "€"), ("'😀'", "😀"),
    ("b''", b""), ("b'abc'", b"abc"),
    ("()", ()), ("(1,2,3)", (1, 2, 3)),
    ("[]", []), ("[1,2,3]", [1, 2, 3]), ("{}", {}), ("{'a':1}", {"a": 1}),
    ("set()", set()), ("object()", object()),
]:
    print(f"{label:>14}: {sys.getsizeof(obj)}")

big = ["x" * 1000 for _ in range(3)]
print("list of 3 strings of 1000 chars: getsizeof =", sys.getsizeof(big),
      "| sum of parts =", sys.getsizeof(big) + sum(sys.getsizeof(s) for s in big))

# list over-allocation
print("--- list growth: size changes only at some appends ---")
lst = []
last = sys.getsizeof(lst)
print(f"len=0 size={last}")
for i in range(1, 40):
    lst.append(i)
    s = sys.getsizeof(lst)
    if s != last:
        print(f"len={i} size={s}")
        last = s

The first half of the output (run on Python 3.14.6):

Output3 lines
a is b: True | a is c: False | a == c: True
a after b.append(4): [1, 2, 3, 4]
c unchanged: [1, 2, 3]

b is another name for the same list, so b.append(4) is visible through a. c = list(a) made a new list holding the same three items, so it is equal but not identical, and later changes to a do not reach it. The rest of the script prints sizes; we will read that table in 1.4.

Three consequences matter for memory and for correctness:

  • Passing an object to a function never copies it. The function gets another name for the caller's object. This is why passing a 2 GB array to a function is free, and why a function that mutates its argument surprises its caller.
  • A shallow copy (list(a), a.copy(), copy.copy(a)) duplicates the container but shares every element. A deep copy (copy.deepcopy) duplicates the container and everything inside it, recursively. deepcopy keeps a memo of what it has already copied, so sub-objects that were shared in the original stay shared in the copy (a cycle does not loop forever). A deep copy of a large structure still roughly doubles its memory, which is how an innocent "defensive copy" in a request handler becomes a memory problem under load.
  • Containers hold references, not values. A list of one million strings holds one million pointers (8 bytes each on a 64-bit build) and one million separate string objects elsewhere. This is the root of the memory overhead of Python data structures, and it returns in Part 6.

1.4 What an object looks like in memory#

Every Python object starts with a header. On a 64-bit CPython build the minimal header, called PyObject, is two machine words, 16 bytes:

text
+--------------------+--------------------+----------------------...
| reference count    | pointer to type    | the object's own data
| (8 bytes)          | (8 bytes)          | (depends on the type)
+--------------------+--------------------+----------------------...

Variable-size types (list, tuple, str, bytes, int) add a length field. Objects that can take part in reference cycles (lists, dicts, sets, instances of most classes) get a second, hidden header in front, the GC header, that links them into the collector's bookkeeping (16 bytes on this build). object() is the smallest thing you can allocate, and the experiment shows 16 bytes for it, exactly the header and nothing else.

Two details are worth knowing:

  • In the free-threaded build the layout differs. Python's own free-threading guide says that on AMD64 None takes 32 bytes there against 16 in the default build, because the GC information moves into a larger object header. Container objects such as lists and dicts are the same size in both builds.
  • Integers are objects too, and unbounded. Python's int has no fixed width: 2**100 is a perfectly good value, stored as a sequence of 30-bit "digits". That is why 0 takes 28 bytes here and 2**100 takes 40.

1.5 What sys.getsizeof measures, and what it leaves out#

sys.getsizeof(obj) returns the size of one object. The documentation is precise: "Only the memory consumption directly attributed to the object is accounted for, not the memory consumption of objects it refers to", and for objects managed by the garbage collector it adds the GC header. Here is the table from the experiment (Python 3.14.6, 64-bit macOS):

Output35 lines
--- sys.getsizeof (bytes, this build) ---
          None: 16
          True: 28
             0: 28
             1: 28
       2**30-1: 28
         2**30: 32
         2**60: 36
        2**100: 40
           1.5: 24
            '': 41
           'a': 42
  'abcdefghij': 51
           'é': 61
           '€': 60
           '😀': 64
           b'': 33
        b'abc': 36
            (): 48
       (1,2,3): 72
            []: 56
       [1,2,3]: 88
            {}: 64
       {'a':1}: 184
         set(): 216
      object(): 16
list of 3 strings of 1000 chars: getsizeof = 88 | sum of parts = 3211
--- list growth: size changes only at some appends ---
len=0 size=56
len=1 size=88
len=5 size=120
len=9 size=184
len=17 size=248
len=25 size=312
len=33 size=376

Read the table once, slowly:

  • A tiny value is not tiny. The number 1 costs 28 bytes, a one-character string 42, a one-key dict 184. Python buys uniformity and flexibility with per-object overhead.
  • getsizeof of a container ignores its contents. A list of three 1000-character strings reports 88 bytes; the true cost is 3211. This is the single most common way people underestimate their memory: getsizeof(big_dict) is the size of the table, not the data.
  • Lists over-allocate. The size jumps at appends 1, 5, 9, 17, 25 and 33, not at every append, because a list grows in chunks so that append is cheap on average (amortized constant time). After 33 items you pay for about 40 slots. The exact growth formula is a CPython detail that has changed between versions.
  • Strings come in widths. 'é' (Latin-1) and '€' (two bytes per character) and '😀' (four) all cost more than 'a'. We measure this properly in 6.6.

A summed estimate that follows every reference, counting each shared object once, is the helper below. It is the "real" getsizeof people wish for, with the caveats written into the docstring.

python
# e17_deepsize.py: a recursive size estimate that counts shared objects once, and string widths
import sys
from collections.abc import Mapping, Set
from collections import deque

def deep_getsizeof(obj, _seen: set[int] | None = None) -> int:
    """Approximate total bytes reachable from obj. Shared objects are counted once.

    It follows built-in containers and instance __dict__/__slots__ only; objects
    from C extensions (NumPy arrays, database cursors) are only as accurate as
    their own __sizeof__.
    """
    seen = _seen if _seen is not None else set()
    if id(obj) in seen:
        return 0
    seen.add(id(obj))
    size = sys.getsizeof(obj)
    if isinstance(obj, Mapping):
        size += sum(deep_getsizeof(k, seen) + deep_getsizeof(v, seen) for k, v in obj.items())
    elif isinstance(obj, (list, tuple, set, frozenset, deque, Set)):
        size += sum(deep_getsizeof(i, seen) for i in obj)
    else:
        if hasattr(obj, "__dict__"):
            size += deep_getsizeof(vars(obj), seen)
        for cls in type(obj).__mro__:
            for slot in getattr(cls, "__slots__", ()):
                if hasattr(obj, slot):
                    size += deep_getsizeof(getattr(obj, slot), seen)
    return size

label = "support"
rows = [{"queue": label, "n": i} for i in range(1000)]     # every row shares ONE 'support' string
shared_total = deep_getsizeof(rows)
shallow = sys.getsizeof(rows)
independent = sum(deep_getsizeof(r) for r in rows)     # each row measured alone: the shared string is counted 1000 times
print("getsizeof(rows) alone (just the list):", shallow, "bytes")
print("deep, shared objects counted once    :", shared_total, "bytes")
print("rows measured one by one then summed :", independent + shallow, "bytes (double counting)")
print("double counting overstates:", independent + shallow > shared_total)

# the same object referenced twice is counted once
blob = "x" * 10_000
print("one blob in two lists counted once:",
      deep_getsizeof([blob]) + deep_getsizeof([blob]) - deep_getsizeof([[blob], [blob]]) > 9_000)

print("--- str width: one wide character changes the whole string ---")
n = 1000
for label, s in [("ASCII", "a" * n), ("Latin-1 (é)", "é" * n), ("BMP (€)", "€" * n), ("one emoji + ASCII", "a" * (n - 1) + "😀")]:
    print(f"{label:<20} {sys.getsizeof(s):>5} bytes for {len(s)} chars")
Output10 lines
getsizeof(rows) alone (just the list): 8856 bytes
deep, shared objects counted once    : 220992 bytes
rows measured one by one then summed : 356856 bytes (double counting)
double counting overstates: True
one blob in two lists counted once: True
--- str width: one wide character changes the whole string ---
ASCII                 1041 bytes for 1000 chars
Latin-1 (é)           1057 bytes for 1000 chars
BMP (€)               2058 bytes for 1000 chars
one emoji + ASCII     4060 bytes for 1000 chars

Look at the three numbers. The list alone is 8,856 bytes; the whole structure, with every shared object counted once, is 220,992. The naive approach of measuring each row separately and summing double-counts the "support" label that all thousand rows share, and overstates the total by more than 60 percent. The width table at the bottom is the same effect in miniature: one emoji in a 1000-character string quadruples its size.

1.6 What this means for an AI engineer#

  • A "record" in an AI pipeline (a chunk, a document, a message) is usually a dict of strings. Plan on 150 to 300 bytes of overhead per small dict plus the strings, before you store a single useful byte. A million chunks is hundreds of megabytes of bookkeeping (6.2 shows the alternatives).
  • Passing big objects between functions is free; deep-copying them is not. Copy only what you will mutate and what someone else still holds.
  • sys.getsizeof is a design-comparison tool. The honest numbers come from tracemalloc and RSS.

Part 2: Reference counting#

2.1 The mechanism#

CPython's primary memory-management strategy is simple enough to describe in a sentence. Every object carries a count of how many references point at it. When the count drops to zero, the object is freed immediately. In the C source this is Py_INCREF (add one) and Py_DECREF (subtract one, and free if the result is zero); the interpreter does it for you on every assignment, every function call and every container operation.

What adds a reference, and what removes one:

Adds one Removes one
name = obj (binding a name) del name, or rebinding the name to another object
Putting obj in a list, tuple, dict, set Removing it, or the container being freed
Passing obj as an argument (the parameter name is a reference) The function returning (its local names disappear)
Setting an attribute (self.model = obj) Deleting the attribute or the instance being freed
A closure capturing obj The closure being freed
A traceback or frame that mentions obj among its locals The exception handler ending (except ... as e deletes e)
A running generator or coroutine holding it in a local The generator finishing or being closed

2.2 Watching it with sys.getrefcount#

sys.getrefcount(obj) returns the current count. The documentation warns that the number is "generally one higher than you might expect, because it includes the (temporary) reference as an argument", and that you should not rely on it "other than a value of 0 or 1". It is a teaching tool, and a brilliant one:

python
# e02_refcount.py: reference counting you can watch
import sys

x = object()
print("fresh object, getrefcount:", sys.getrefcount(x), "(1 name + 1 temporary argument)")
y = x
print("after y = x:", sys.getrefcount(x))
lst = [x, x]
print("after putting it in a list twice:", sys.getrefcount(x))
del y
print("after del y:", sys.getrefcount(x))
lst.clear()
print("after lst.clear():", sys.getrefcount(x))

def f(obj):
    return sys.getrefcount(obj)
print("inside a function call (extra argument reference):", f(x))

# deterministic destruction: __del__ runs the instant the count hits zero
class Noisy:
    def __init__(self, name): self.name = name
    def __del__(self): print(f"  freed {self.name}")

print("--- deterministic destruction ---")
n = Noisy("A")
print("rebinding n ...")
n = Noisy("B")
print("del n ...")
del n
print("done")

# immortal objects (3.12+): refcounts that do not move
print("--- immortal objects ---")
for label, o in [("None", None), ("True", True), ("small int 5", 5), ("int 10**6 built at runtime", int("1000000")),
                 ("interned str 'abc'", "abc")]:
    before = sys.getrefcount(o)
    keep = [o] * 1000
    after = sys.getrefcount(o)
    del keep
    print(f"{label:>28}: before={before} after 1000 refs: {'unchanged' if before == after else 'changed by ' + str(after-before)}")
print("getrefcount(None) is huge:", sys.getrefcount(None) > 10**6)
Output · Python 3.14.619 lines
fresh object, getrefcount: 2 (1 name + 1 temporary argument)
after y = x: 3
after putting it in a list twice: 5
after del y: 4
after lst.clear(): 2
inside a function call (extra argument reference): 2
--- deterministic destruction ---
rebinding n ...
  freed A
del n ...
  freed B
done
--- immortal objects ---
                        None: before=3221225472 after 1000 refs: unchanged
                        True: before=3221225472 after 1000 refs: unchanged
                 small int 5: before=3221225472 after 1000 refs: unchanged
  int 10**6 built at runtime: before=3 after 1000 refs: changed by 1000
          interned str 'abc': before=3221225472 after 1000 refs: unchanged
getrefcount(None) is huge: True

Walk through the first half. A fresh object has a count of 2: one for the name x, one for the temporary reference the function call creates. y = x adds one. Putting x in a list twice adds two (the list holds one reference per slot). del y and lst.clear() each undo what they undid.

Two things in the output deserve honesty:

  • The function-call line prints 2, not the 4 or so you might expect from older Pythons. Python 3.14's interpreter can skip some temporary increments (it borrows references in places where the object is known to stay alive; see the 3.14 What's New notes on the interpreter's performance work). The count is an implementation artefact that moves with interpreter optimizations. This is exactly why the docs tell you not to rely on exact values.
  • Destruction is immediate and deterministic. In the second half, freed A prints at the moment n = Noisy("B") rebinds the name (the old object's count hit zero), and freed B prints at del n. There was no waiting for a collector. This is a CPython behaviour; PyPy and other implementations free objects later, which is why portable code never depends on "the file closes when the variable goes away" and uses with instead.

2.3 Deterministic destruction, and why it is not a guarantee#

Immediate destruction is genuinely useful in CPython: temporary lists and strings disappear the moment you stop using them, memory use tends to follow the structure of your code, and the peak is usually the sum of what is simultaneously reachable. But three things break the picture, and they are the subject of the rest of this part and Part 3:

  1. Reference cycles (an object that refers, directly or through others, to itself) never reach count zero. See Part 3.
  2. A forgotten reference (cache, global, stored exception) keeps the count above zero forever. See Part 7.
  3. Freed is not returned to the operating system. When the count hits zero the object is gone; the bytes usually go back to Python's allocator, not to the OS. See Part 4.

2.4 Immortal objects (Python 3.12)#

Look at the last block of the e02 output. None, True, a small integer and a short interned string all show a count of 3,221,225,472, and adding a thousand references does not change it. Those are immortal objects, introduced in Python 3.12 by PEP 683. An immortal object has a fixed, enormous reference count that Py_INCREF and Py_DECREF do not change, so it is never freed during normal execution. The int built at runtime from "1000000" is an ordinary object: its count moved by exactly the 1000 references we added.

Why did CPython do this? The PEP gives two motivations, both about memory:

  • Real immutability. Before 3.12, even None was written to every time something took or dropped a reference to it. An object that is written to cannot live in read-only or shared memory. Immortal objects are never written, so they can be shared between sub-interpreters without locks, which made per-interpreter GILs (PEP 684) feasible. The PEP says "with immortal objects, support for a per-interpreter GIL becomes much simpler".
  • Copy-on-write. A pre-fork server (Part 5) shares memory pages between parent and children. Writing a refcount dirties a page and forces a copy. If the objects touched most often (None, True, small ints, the singletons, static types and interned identifiers) are never written, their pages stay shared.

The price was a small slowdown for the extra check (the PEP quotes 2 to 4 percent for a naive implementation, and about 2 percent (3 percent with MSVC) once its mitigations are applied). The practical consequences for you:

  • sys.getrefcount(None) returns a huge number. That is correct, and the docs say so: "some objects are immortal and have a very high refcount that does not reflect the actual number of references". sys._is_immortal(obj) (3.14 and later) identifies them (a CPython-specific helper).
  • Immortality only covers a few objects. Your lists, your dicts, your instances and your large strings are ordinary mortal objects. Immortality does not make a pre-fork server share your data (Part 5 covers what does).
  • Interned strings are not immortal in general. The sys.intern documentation says so directly: "Interned strings are not immortal; you must keep a reference to the return value of intern() around to benefit from it." (Compile-time constants like "abc" above are different because the interpreter creates and keeps them.) The free-threaded build is different again: its guide says "any interned string will become immortal, surviving until interpreter shutdown".

2.5 Small ints, interning and constants#

Why does a is b sometimes work for values you built separately? CPython saves memory and time by sharing some immutable objects:

python
# e03_interning.py: small ints, interning, constants
import sys

# small int cache: -5..256
def ident(a, b): return a is b
print("--- small ints ---")
for v in (-6, -5, 0, 256, 257, 1000):
    a = int(str(v)); b = int(str(v))   # built at runtime so constants folding cannot hide it
    print(f"{v:>5}: same object? {a is b}")

print("--- strings ---")
s1 = "hello"; s2 = "hello"
print("identical literals in one module:", s1 is s2)
t1 = "".join(["hel", "lo"]); t2 = "hello"
print("built at runtime vs literal:", t1 is t2, "| equal:", t1 == t2)
print("after sys.intern:", sys.intern(t1) is sys.intern(t2))
u1 = "hello world"; u2 = "hello world"
print("literal with a space, same module:", u1 is u2)
print("sys.intern gives one copy for many equal strings:")
words = ["".join(["ti", "cket"]) for _ in range(1000)]
print("  distinct objects before intern:", len({id(w) for w in words}))
words = [sys.intern(w) for w in words]
print("  distinct objects after intern: ", len({id(w) for w in words}))

print("--- tuples and constants ---")
def k():
    return (1, 2, 3)
print("constant tuple returned twice is the same object:", k() is k())
def m(n):
    return (n, 2, 3)
print("tuple built from a variable is new each call:", m(1) is m(1))
Output · Python 3.14.618 lines
--- small ints ---
   -6: same object? False
   -5: same object? True
    0: same object? True
  256: same object? True
  257: same object? False
 1000: same object? False
--- strings ---
identical literals in one module: True
built at runtime vs literal: False | equal: True
after sys.intern: True
literal with a space, same module: True
sys.intern gives one copy for many equal strings:
  distinct objects before intern: 1000
  distinct objects after intern:  1
--- tuples and constants ---
constant tuple returned twice is the same object: True
tuple built from a variable is new each call: False
  • The small-integer cache. The integers -5 through 256 exist once, created at startup; int("5") and int("5") return the same object. -6 and 257 are created fresh each time. The CPython C-API documentation calls this "a CPython implementation detail". Our run on 3.14.6 matches the 3.14 documentation's -5 to 256; the current documentation (for the newest release) says -5 to 1024. The range changed, which is the whole point: never write code that depends on it.
  • String interning. Identifier-like string literals in the same module are shared. Strings built at runtime ("".join(...), reading a file, parsing JSON) are separate objects even when equal. sys.intern(s) returns the canonical copy so that equal strings become the same object.
  • Constants are folded. The compiler builds (1, 2, 3) once and reuses it; (n, 2, 3) with a variable inside is built on every call.

When sys.intern pays off. Interning is a memory optimization when you hold very many equal, separately built strings: the last block of the output shows 1,000 copies of "ticket" collapsing to one object. The realistic cases are repeated labels and keys: the queue, language or status field of ten million parsed records, the keys of dict rows read from CSV or JSON (in a check on 3.14.6 the json module shared equal keys within one json.loads call but built new key strings on every separate call, as is showed), and column names. The pattern is to intern the field values you expect to repeat as you ingest, and nothing else. Do not intern long, unique text (document bodies, prompts): the intern table is a hash table and interning a unique string only adds overhead. And remember the documented caveat: the table does not keep strings alive on its own, so the benefit exists only while your records hold the interned object.

2.6 Weak references: referring without owning#

Sometimes you want to look up an object without being the reason it stays alive: a cache of parsed documents, a registry of open connections, an observer list. A weak reference points at an object without raising its reference count. When the last strong reference goes, the object is freed and the weak reference starts returning None.

python
# e04_weakref.py: references that do not keep objects alive
import gc
import weakref

class Model:
    def __init__(self, name): self.name = name
    def __repr__(self): return f"Model({self.name!r})"

m = Model("embed-small")
r = weakref.ref(m)
print("alive:", r())
del m
print("after del (refcount hit zero):", r())

# a cache that must not keep values alive
cache = weakref.WeakValueDictionary()
doc = Model("doc-1")
cache["doc-1"] = doc
print("in cache while strong ref exists:", "doc-1" in cache, "len", len(cache))
del doc
gc.collect()
print("after the last strong ref is gone:", "doc-1" in cache, "len", len(cache))

# callback and finalize
class Conn:
    def __init__(self, n): self.n = n
c = Conn(7)
fin = weakref.finalize(c, print, "  finalize: connection 7 released")
print("finalize alive:", fin.alive)
del c
print("finalize alive:", fin.alive)

# not every object is weak-referenceable
for v in (3, "s", [1], (1,), {"a": 1}):
    try:
        weakref.ref(v)
        print(type(v).__name__, "weakref ok")
    except TypeError as e:
        print(type(v).__name__, "->", e)

# slots without __weakref__
class S:
    __slots__ = ("a",)
try:
    weakref.ref(S())
except TypeError as e:
    print("slots class ->", e)
class S2:
    __slots__ = ("a", "__weakref__")
print("slots + __weakref__ ok:", weakref.ref(S2()) is not None)
Output · Python 3.14.614 lines
alive: Model('embed-small')
after del (refcount hit zero): None
in cache while strong ref exists: True len 1
after the last strong ref is gone: False len 0
finalize alive: True
  finalize: connection 7 released
finalize alive: False
int -> cannot create weak reference to 'int' object
str -> cannot create weak reference to 'str' object
list -> cannot create weak reference to 'list' object
tuple -> cannot create weak reference to 'tuple' object
dict -> cannot create weak reference to 'dict' object
slots class -> cannot create weak reference to 'S' object
slots + __weakref__ ok: True

Four tools from the weakref module cover nearly all uses:

Tool What it does Typical use
weakref.ref(obj) Call it (r()) to get the object or None Back-references (child to parent) that must not create a cycle
WeakValueDictionary A dict whose values vanish when nobody else holds them "Cache what is still in use": parsed documents, model handles, per-session objects
WeakKeyDictionary / WeakSet Same, for keys / members Attaching metadata to objects you do not own; observer sets
weakref.finalize(obj, fn, *args) Call fn(*args) when obj is collected, or at exit Reliable cleanup without __del__ (3.5)

Three traps, all visible in the output:

  • Not everything can be weakly referenced. int, str, list, tuple and dict instances raise TypeError. Subclass them (class MyList(list): pass) if you need it. A class that defines __slots__ loses weak-reference support unless it lists "__weakref__" in its slots.
  • A weak reference to a temporary dies at once. weakref.ref(Model("x")) is dead before you can use it; something has to hold a strong reference.
  • WeakValueDictionary is not a memory cap. It frees entries when nothing else needs them, which in a service often means immediately after a request ends: a hit rate near zero. If you want a cache that keeps hot items, use a bounded LRU (7.3); use a weak dictionary to deduplicate objects that are alive anyway.

2.7 What reference counting costs#

Reference counting makes memory use predictable, but it is not free, and the cost explains several things you will meet later:

  • Every read is a write. Binding an object to a name increments its count: that is a store to the object's memory. Reading is therefore not "read-only" at the hardware level. Part 5 shows how this ruins copy-on-write sharing between processes.
  • It is why the GIL exists. An unsynchronized count += 1 from two threads would corrupt counts and either leak or free objects too early. Protecting every count with a lock would be slow, so CPython protects the whole interpreter with one lock instead (01C.5).
  • The free-threaded build changes the mechanism. Python's free-threading guide describes biased reference counting (a fast path for objects "owned" by the creating thread, a slow path for others), deferred reference counting (references from Python function stacks to modules, top-level functions, methods and similar objects are not counted, so those objects are freed by the garbage collector rather than the moment their count reaches zero), and per-thread counts for some objects. The practical result, from the same guide: "the free-threaded build will typically use more memory compared to the default build", and some objects are freed later than in the default build; calling gc.collect() merges the deferred and per-thread counts so that they can be freed.

2.8 What this means for an AI engineer#

  • Lean on immediate freeing for temporaries: building a large prompt string in a function and returning only its length frees the prompt when the function returns. Keep references only to what you need later.
  • A with block, not "the variable goes out of scope", is how you release a connection or a file: it is portable and deterministic.
  • Do not compare values with is. Do intern repeated labels in a large ingestion; leave unique text alone.
  • Use WeakValueDictionary to share objects already alive (one Tokenizer per name, one parsed Document per id), not as a cache.
  • Never trust an exact getrefcount number across Python versions. Use it to understand, not to assert.

Part 3: Reference cycles and the cyclic garbage collector#

3.1 Why counting alone is not enough#

Reference counting has one blind spot. If object a refers to b and b refers back to a, each has a count of at least one from the other, so neither can reach zero even when nothing else in the program can reach them. That is a reference cycle, and it is garbage that counting can never free. Python adds a second mechanism for exactly this case: the cyclic garbage collector, in the gc module.

python
# e05_cycles.py: reference counting cannot free a cycle; the cyclic GC can
import gc
import weakref

class Node:
    def __init__(self, name): self.name = name; self.other = None

gc.disable()                      # so the experiment is deterministic
gc.collect()                      # start from a clean slate
a, b = Node("a"), Node("b")
a.other, b.other = b, a           # a cycle
probe = weakref.ref(a)
del a, b
print("after del, still alive (refcounts are 1 each):", probe() is not None)
found = gc.collect()
print("gc.collect() returned:", found, "(the two Node objects)")
print("after gc.collect(), alive:", probe() is not None)

# self-cycle through a closure and an exception traceback
def make():
    def inner(): return inner       # closure cell referencing itself
    return weakref.ref(inner)
p = make()
print("closure cycle alive before collect:", p() is not None)
gc.collect()
print("closure cycle alive after collect:", p() is not None)

# generations
print("--- thresholds and counts ---")
gc.enable()
print("threshold:", gc.get_threshold())
gc.collect()
print("count right after a full collection:", gc.get_count())
junk = [[] for _ in range(100)]
print("count after allocating 100 lists (gen0 count grew):", gc.get_count()[0] >= 100)
print("stats keys:", sorted(gc.get_stats()[0].keys()))
print("number of generations reported:", len(gc.get_stats()))
Output · Python 3.14.611 lines
after del, still alive (refcounts are 1 each): True
gc.collect() returned: 2 (the two Node objects)
after gc.collect(), alive: False
closure cycle alive before collect: True
closure cycle alive after collect: False
--- thresholds and counts ---
threshold: (2000, 10, 10)
count right after a full collection: (0, 0, 0)
count after allocating 100 lists (gen0 count grew): True
stats keys: ['collected', 'collections', 'uncollectable']
number of generations reported: 3

After del a, b the two nodes are unreachable from your code, but the weak-reference probe shows them still alive: each holds a reference to the other. gc.collect() found them, returned 2 (the number of unreachable objects it freed), and the probe then reports them gone. The same happens with a function that refers to itself through its own closure cell.

3.2 How the collector decides what is garbage#

You do not need the C code, but the idea is short and worth having, because it explains the cost model:

  1. The collector only looks at container objects (the ones that can hold references: lists, dicts, sets, tuples that hold containers, instances of most classes). Strings, ints and floats cannot be part of a cycle and are never tracked. gc.is_tracked(obj) tells you whether an object is tracked; the docs show that gc.is_tracked(0) is False, gc.is_tracked([]) is True, an empty {} is False and {"a": 1} is True. On 3.14.6 both {} and {"a": 1} print True, so do not test that claim on your build and expect the docs' answer: the rules for when dicts and tuples become tracked are an optimization detail that varies by version.
  2. For every tracked object in the generation being examined, it starts from the object's reference count and subtracts every reference that comes from another tracked object in that same set. What remains is the number of references from outside the set: the stack, globals, other generations, C code.
  3. Objects with a remainder above zero are externally reachable roots. Everything reachable from a root is alive. Whatever is left is unreachable, and the collector frees it (running finalizers first, see 3.5).

Two consequences follow directly:

  • The cost is proportional to the number of tracked container objects it examines, not to bytes. A heap of ten million small dicts is expensive to scan; a 4 GB bytes or a NumPy array is a single object and costs nothing.
  • Strings and numbers never need it. This is why a design with fewer, larger objects (a few big arrays, not millions of small lists) is easier on the collector as well as on memory.

3.3 Generations, thresholds and what triggers a collection#

Scanning everything on every allocation would be far too slow, so CPython uses generations, based on the observation that most objects die young. New tracked objects start in the young generation (generation 0). The collector counts allocations minus deallocations of tracked objects; when that count exceeds threshold0 it collects generation 0. Survivors move to the next generation, which is examined less often: after generation 0 has been collected more than threshold1 times, generation 1 is collected too, and so on for the oldest generation.

python
# e16_gc_cost.py: a full collection scans every tracked container; frozen ones are skipped
import gc
import time

def full_collect_seconds() -> float:
    t = time.perf_counter()
    gc.collect()
    return time.perf_counter() - t

gc.collect()
empty = full_collect_seconds()
corpus = [{"id": i, "tags": ["x", "y"], "meta": {"k": i}} for i in range(500_000)]   # 1.5M container objects
loaded = full_collect_seconds()
gc.freeze()
frozen = full_collect_seconds()
gc.unfreeze()

print(f"full collection, small heap       : {empty * 1000:8.1f} ms")
print(f"full collection, 1.5M live objects: {loaded * 1000:8.1f} ms")
print(f"same heap after gc.freeze()       : {frozen * 1000:8.1f} ms")
print("loaded heap costs far more than an empty one:", loaded > 20 * empty)
print("frozen heap is cheap again:", frozen < loaded / 20)

# gc.callbacks can time every automatic collection while a workload runs
pauses = []
start = {}
def cb(phase, info):
    if phase == "start": start["t"] = time.perf_counter()
    else: pauses.append((info["generation"], time.perf_counter() - start["t"]))
gc.callbacks.append(cb)
junk = [[i] for i in range(300_000)]        # many allocations: triggers young collections
gc.callbacks.remove(cb)
gens = sorted({g for g, _ in pauses})
print("automatic collections observed:", len(pauses) > 0, "| generations seen:", gens)
Example output · illustrative6 lines
full collection, small heap       :      0.3 ms
full collection, 1.5M live objects:     45.9 ms
same heap after gc.freeze()       :      0.0 ms
loaded heap costs far more than an empty one: True
frozen heap is cheap again: True
automatic collections observed: True | generations seen: [0, 1, 2]

You can read the settings and the current counters yourself: gc.get_threshold() printed (2000, 10, 10) on this build (the e05 output above), gc.get_count() shows the three counters, and gc.get_stats() returns per-generation dictionaries with collections, collected and uncollectable.

The output of e16 is the lesson of this section. With 1.5 million live container objects, one full collection took tens of milliseconds, against a fraction of a millisecond for a small heap. The collector is scanning your live data to prove it is alive. A long-lived service with a big in-memory corpus pays this on every full collection; it shows up as latency spikes that look like a mystery stall. After gc.freeze() (3.6) the same heap costs almost nothing, because the collector ignores frozen objects.

The third block shows gc.callbacks, a list of functions the interpreter calls at the start and the end of every collection with info["generation"]. It is the supported way to measure garbage-collection pauses in production without patching anything.

3.4 What shipped in 3.13 and 3.14#

This is a topic where reading old blog posts will mislead you, so here is the verified history (all from the official documentation, as of November 2026):

Version Collector What you can observe
3.13 and earlier Classic three-generation, stop-the-world gc.collect(1) collects generation 1; three generations in gc.get_stats()
3.14.0 to 3.14.4 Incremental: two generations, young and old; each collection scans the young generation plus an increment of the old one threshold2 ignored; gc.collect(1) performs an increment
3.14.5 and later Classic three-generation again "Python 3.14.0-3.14.4 shipped with a new incremental GC. However, due to a number of reports of significant memory pressure in production environments, it has been reverted back to the generational GC from 3.13"; threshold2 restored; gc.collect(1) collects the middle generation; generation 1 reintroduced
3.15 (newest docs) Classic gc.get_stats() and gc.callbacks gain duration and candidates fields

Three practical points:

  • What the incremental collector was for. It reduces maximum pause time ("by an order of magnitude or more for larger heaps", per the 3.14 release notes) by scanning the old generation a slice at a time instead of all at once. It did so at the price of more memory pressure in some real deployments, which is why it was withdrawn in a patch release. The big-heap pause shown in e16 is therefore back on 3.14.5 and later, and on 3.13: the cure is gc.freeze() and fewer objects, not hoping the interpreter will hide it.
  • Check what you run. python3 --version and gc.get_threshold() tell you; the experiment machine here reported (2000, 10, 10) on 3.14.6. Do not copy GC-tuning numbers from a blog post about another version.
  • The free-threaded build is a different collector design, and its GC details are outside the stable gc documentation. Treat tuning advice for the default build as not transferable (8.9 of 01C.3 covers what else changes when the GIL is gone).

3.5 Finalizers: __del__, PEP 442 and resurrection#

A finalizer is code that runs when an object is destroyed. In Python that is __del__. It looks like a destructor, and many people write it to close files and connections. It is the wrong tool for that, and the experiment shows why.

python
# e06_finalizers.py: __del__ in cycles (PEP 442), resurrection, gc.callbacks
import gc

class Res:
    def __init__(self, n): self.n = n; self.peer = None
    def __del__(self): print(f"  __del__ {self.n}")

gc.disable()
gc.collect()
x, y = Res("x"), Res("y")
x.peer, y.peer = y, x
del x, y
print("collecting a cycle whose members have __del__ ...")
n = gc.collect()
print("collected:", n, "| gc.garbage:", gc.garbage)

# gc.callbacks observe every collection
events = []
def cb(phase, info):
    events.append((phase, info["generation"]))
gc.callbacks.append(cb)
gc.collect()
gc.collect(0)
gc.callbacks.remove(cb)
print("callbacks saw:", events)

# __del__ exceptions are swallowed (printed to stderr, ignored)
class Bad:
    def __del__(self): raise RuntimeError("boom")
import sys, io
old = sys.stderr; sys.stderr = io.StringIO()
Bad(); out = sys.stderr.getvalue(); sys.stderr = old
print("exception in __del__ was not raised to caller; stderr mentions:", "RuntimeError" in out)

# __del__ order is not guaranteed at interpreter exit; use context managers
class File:
    def __enter__(self): print("  open"); return self
    def __exit__(self, *a): print("  close (deterministic)")
with File():
    print("  working")
Output · Python 3.14.69 lines
collecting a cycle whose members have __del__ ...
  __del__ x
  __del__ y
collected: 2 | gc.garbage: []
callbacks saw: [('start', 2), ('stop', 2), ('start', 0), ('stop', 0)]
exception in __del__ was not raised to caller; stderr mentions: True
  open
  working
  close (deterministic)

What the output demonstrates, and what the documentation says:

  • Objects with __del__ can be collected in cycles. Before Python 3.4, a cycle containing an object with __del__ could never be freed; the objects piled up in gc.garbage. PEP 442 (Python 3.4) fixed that: the collector runs the finalizers, then frees the objects. The gc.garbage documentation says it directly: "objects with a __del__() method don't end up in gc.garbage anymore". Here both finalizers ran and gc.garbage is empty.
  • Timing is not guaranteed. In a cycle, __del__ runs when the collector next runs, which could be milliseconds or minutes later. Outside cycles it runs at reference-count zero, but that is a CPython property.
  • Exceptions in __del__ are swallowed. The data-model documentation: "exceptions that occur during their execution are ignored, and a warning is printed to sys.stderr instead". The experiment confirms the caller never sees the error.
  • It may never run. "It is not guaranteed that __del__() methods are called for objects that still exist when the interpreter exits."
  • Resurrection. A __del__ that stores self somewhere (a global, a list) brings the object back to life. PEP 442 makes this safe (a finalizer runs only once per object; gc.is_finalized(obj) tells you whether it has run), but the pattern is almost always a bug.

The replacements, in order of preference:

You want to... Use Why
Release a file, socket, lock, DB connection with / a context manager (the File class in the experiment), or contextlib.closing Deterministic, exceptions propagate, portable to PyPy
Release a resource owned by an object that can be forgotten weakref.finalize(obj, cleanup, handle) Runs once, also at interpreter exit, and does not keep obj alive
Run code at process exit atexit.register Explicit and ordered
Clean up after a task or request try/finally, asyncio.TaskGroup, ExitStack Tied to the code's structure, not to memory management

3.6 Controlling the collector: disable, freeze, thresholds#

The default collector is good. Change it only with a measurement in hand. The knobs:

Knob What it does When it is justified
gc.collect() Full collection now; returns the count of unreachable objects found After deleting a huge structure so memory is reclaimed before the next phase; in tests and leak hunts
gc.disable() / gc.enable() Stop or resume automatic collection (reference counting still works) Short, allocation-heavy phases that you know create no cycles (bulk parse, then collect once); the fork recipe below
gc.set_threshold(t0, t1, t2) Collect less (or more) often When profiling shows GC pauses are a measurable fraction of runtime; raise t0 rather than disabling
gc.freeze() Move all currently tracked objects to a permanent generation ignored by future collections; gc.unfreeze() reverses it; gc.get_freeze_count() counts them After loading large long-lived data at startup; before fork
gc.callbacks Hooks called around every collection Measuring pauses, exporting a metric
gc.set_debug(gc.DEBUG_SAVEALL) Keep unreachable objects in gc.garbage instead of freeing them Finding out what is in a cycle

gc.freeze() earns its own look, because it is the cheapest big win for AI services that load a corpus or model metadata at startup:

python
# e08_freeze.py: gc.freeze moves everything into a permanent generation the collector ignores
import gc

gc.collect()
before = gc.get_freeze_count()
data = [{"id": i, "tags": ["a", "b"]} for i in range(10_000)]   # container objects the GC tracks
print("tracked objects in the young+old generations grew:", len(gc.get_objects()) > 20_000)
gc.freeze()
print("frozen objects now >= 20,000:", gc.get_freeze_count() - before >= 20_000)
print("objects the collector will scan now (small):", len(gc.get_objects()) < 5_000)
gc.collect()
print("data still intact:", data[9999]["id"])
gc.unfreeze()
print("after unfreeze, freeze count:", gc.get_freeze_count())
Output · Python 3.14.65 lines
tracked objects in the young+old generations grew: True
frozen objects now >= 20,000: True
objects the collector will scan now (small): True
data still intact: 9999
after unfreeze, freeze count: 0

Three things happened: after loading 10,000 dicts the collector tracked them; gc.freeze() moved them to the permanent generation so gc.get_objects() (which returns only what the collector will scan) became small; and gc.unfreeze() put them back. Frozen objects are still alive and still reference-counted; they are only skipped by the cycle collector. The trade-off is that a cycle among frozen objects is never collected. That is fine for data you load once and keep for the life of the process.

3.7 Cycles you create without noticing#

You rarely write a.other = b; b.other = a by hand. Cycles come from structure:

Pattern Why it cycles Fix
Parent and child (child.parent = parent, parent.children.append(child)) Each holds the other Make the back-reference a weakref.ref, or avoid it
A stored exception (self.last_error = exc) The exception's __traceback__ references frames whose locals include self Store str(exc) or repr(exc); or exc.__traceback__ = None; except ... as e already deletes e at the end of the block to avoid this cycle
A bound method as a callback (registry.append(self.on_event)) The registry holds the bound method, which holds self; self may hold the registry weakref.WeakMethod for observer lists
A closure referring to itself (a recursive inner function) The function's closure cell holds the function Pass it as an argument, or accept the collector handles it
An asyncio.Future with a callback that references it The future holds the callback, the callback holds the future Use done-callbacks that take the future as an argument
A class with __del__ plus cycles Safe since PEP 442, but the finalizer runs late Context managers

Cycles are only garbage if they are unreachable. A cycle reachable from a global registry is a live structure, and it is Part 7's problem, not the collector's.

3.8 What this means for an AI engineer#

  • A service that stays in memory for weeks needs the collector on; leave gc enabled and instead reduce what it has to scan: load big read-only data as a few large objects (arrays, bytes, memory-mapped files) rather than millions of small dicts.
  • After startup loading, gc.freeze() removes that data from collection scans; before fork, it also helps copy-on-write (5.3).
  • Measure GC pauses with gc.callbacks before tuning. Check which Python patch release you run (3.14.0 to 3.14.4 behaved differently from 3.14.5 and later).
  • Never put resource cleanup in __del__. Use with, weakref.finalize or atexit.
  • Stored exceptions are a classic cyclic leak in retry and agent loops: keep the message, not the exception.

Part 4: Where the bytes live: pymalloc, fragmentation and RSS#

Deep-dive

Reference counting decides when an object is dead. A separate system decides where the bytes come from and where they go back to. This is where "I freed it, why is the process still big?" is answered.

4.1 Three layers#

flowchart TB
    subgraph app ["Your Python objects"]
        O1["list, dict, str, instance (up to 512 bytes each)"]
        O2["large objects (more than 512 bytes: big strings, arrays, buffers)"]
    end
    subgraph pym ["pymalloc: Python's small-object allocator"]
        B["blocks: 16, 32, 48 ... 512 bytes"]
        P["pools of 16 KiB: one block size each"]
        A["arenas of 1 MiB: 64 pools each"]
        B --> P --> A
    end
    O1 --> B
    O2 --> M["C malloc (or mimalloc)"]
    A -->|"mmap / VirtualAlloc"| OS["Operating system pages (what RSS counts)"]
    M --> OS

The official documentation on Python's memory allocators describes the same stack: pymalloc is "optimized for small objects (smaller or equal to 512 bytes) with a short lifetime", and "falls back to PyMem_RawMalloc() and PyMem_RawRealloc() for allocations larger than 512 bytes". It carves memory out of "memory mappings called 'arenas' with a fixed size of either 256 KiB on 32-bit platforms or 1 MiB on 64-bit platforms". Arenas are obtained with VirtualAlloc() on Windows and mmap() where available.

A fresher-friendly picture: pymalloc is a warehouse with shelving units that Python rents from the operating system. The warehouse (arena, 1 MiB) is divided into aisles (pools, 16 KiB), and each aisle only stores boxes of one size (blocks of 16, 32, 48 ... 512 bytes). A new 40-byte object takes a free 48-byte slot in a 48-byte aisle. Anything bigger than 512 bytes does not go through the warehouse at all: it asks the system allocator directly.

4.2 Reading the real numbers: sys._debugmallocstats()#

You can print pymalloc's own report, a CPython-specific debugging function. Here is the top of the report on a fresh interpreter (Python 3.14.6, arm64 macOS):

Example output · illustrative20 lines
Small block threshold = 512, in 32 size classes.

class   size   num pools   blocks in use  avail blocks
-----   ----   ---------   -------------  ------------
    0     16           1              51           970
    1     32           2             798           222
    2     48          11            3655            85
    3     64          35            8803           122
 ...
   31    512           2              41            21

# arenas allocated total           =                    3
# arenas reclaimed                 =                    0
# arenas highwater mark            =                    3
# arenas allocated current         =                    3
3 arenas * 1048576 bytes/arena     =            3,145,728

# bytes in allocated blocks        =            2,228,512
# bytes in available blocks        =              290,528
37 unused pools * 16384 bytes      =              606,208

This confirms every number in the diagram on this build: 32 size classes from 16 to 512 bytes in steps of 16, pools of 16384 bytes (16 KiB), arenas of 1,048,576 bytes (1 MiB), a fresh interpreter already using three arenas. Two lines are worth reading closely: "arenas reclaimed" (arenas returned to the OS over the process's life) and "arenas highwater mark" (the most it ever had at once). Setting the environment variable PYTHONMALLOCSTATS=1 makes the interpreter print this report whenever a new arena is created and at shutdown.

4.3 Free lists and the other small caches#

On top of pymalloc, CPython keeps free lists for a few very common types (floats, tuples of small sizes, lists, dicts and some others), so that creating and destroying many short-lived objects does not hit the allocator each time. They are why a loop that makes millions of temporary floats is fast. The gc.collect() documentation notes the consequence: "The free lists maintained for a number of built-in types are cleared whenever a full collection or collection of the highest generation (2) is run." This is one reason gc.collect() can release a little memory even when no cycle exists.

4.4 Fragmentation: why freeing 99.9 percent frees almost nothing#

pymalloc can return an arena to the operating system only when every pool in it is empty. One surviving object pins its whole 1 MiB arena. That is fragmentation, and it is the main reason a Python process that freed most of its data stays large. The following experiment makes it visible with real arena counts:

python
# e07b_arenas.py: watch pymalloc arenas: freeing 99.9 percent of objects frees almost no arenas
import gc
import os
import re
import sys
import tempfile

def arena_stats() -> tuple[int, int]:
    """Return (arenas currently allocated, bytes in allocated blocks) from sys._debugmallocstats()."""
    with tempfile.TemporaryFile("w+") as tmp:
        saved = os.dup(2)
        os.dup2(tmp.fileno(), 2)           # the report is written by C code to fd 2
        try:
            sys._debugmallocstats()
        finally:
            os.dup2(saved, 2); os.close(saved)
        tmp.seek(0)
        text = tmp.read()
    arenas = int(re.search(r"# arenas allocated current\s*=\s*([\d,]+)", text).group(1).replace(",", ""))
    used = int(re.search(r"# bytes in allocated blocks\s*=\s*([\d,]+)", text).group(1).replace(",", ""))
    return arenas, used

def show(label: str) -> None:
    gc.collect()
    arenas, used = arena_stats()
    print(f"{label:<46} arenas={arenas:>4}  live bytes in blocks={used / 2**20:7.1f} MiB")

base_arenas, _ = arena_stats()
N = 2_000_000
objs = [str(i) for i in range(N)]
show(f"after {N:,} small strings")
survivors = objs[::1000]               # keep 0.1 percent, spread evenly through memory
objs = None
show("after dropping 99.9 percent (kept every 1000th)")
survivors = None
show("after dropping the survivors too")

# Same allocation pattern, but the survivors are copied into fresh, compact memory first
objs = [str(i) for i in range(N)]
compact = [str(i) for i in range(0, N, 1000)]   # built later: new objects, adjacent to each other
objs = None
show("compacted copy kept, original dropped")
Example output · illustrative4 lines
after 2,000,000 small strings                  arenas=  95  live bytes in blocks=   94.2 MiB
after dropping 99.9 percent (kept every 1000th) arenas=  95  live bytes in blocks=    2.8 MiB
after dropping the survivors too               arenas=   4  live bytes in blocks=    2.7 MiB
compacted copy kept, original dropped          arenas=   5  live bytes in blocks=    2.8 MiB

Read the four rows:

  1. Two million small strings occupy 95 arenas and 94 MiB of live blocks.
  2. We drop 99.9 percent of them, keeping every thousandth string. Live bytes fall from 94 MiB to 2.8 MiB, but all 95 arenas are still allocated, because a survivor sits in nearly every arena. The memory is "free" inside Python and unusable by anyone else on the machine.
  3. Drop the survivors too and the arenas are reclaimed: 4 are left.
  4. The fix pattern. Allocate the 2,000 survivors as a compact copy while the originals are still alive, then drop the originals: arenas go back to 5. The survivors now share a few arenas of their own.

That fourth row is a real production technique: when you filter a big in-memory dataset down to a small subset that you will keep, copy the subset into new objects and drop the original, instead of holding on to scattered survivors.

4.5 Why RSS does not drop#

RSS (resident set size) is the amount of physical memory the operating system currently attributes to your process. It is what top, ps, Docker and Kubernetes report, and the number that an out-of-memory killer acts on. It can stay high after you free data for several independent reasons:

Reason What happens What helps
Arena fragmentation A few live objects pin whole arenas (4.4) Copy survivors into compact objects; fewer, bigger objects; process recycling
The C allocator keeps freed memory For allocations above 512 bytes, Python calls the C malloc; free returns the block to the C allocator, which may keep it for reuse rather than hand it back to the OS Allocate big data as a few huge objects (these are usually mapped and unmapped directly); malloc_trim on glibc (awareness only, not covered here)
Lazy reclamation by the OS or allocator macOS and the allocators on it release pages lazily; mimalloc "defers returning freed memory back to the OS" and the free-threading guide says MIMALLOC_PURGE_DELAY=0 reduces the delay (at a performance cost) Wait, or measure with tracemalloc instead of RSS
Containers keep capacity Emptying a dict or set by deleting keys does not shrink the table clear(), or rebuild: d = dict(d) (see the container-shrinking experiment in this section)
Deferred frees (free-threaded build) Some objects are freed later; the guide says "even when QSBR frees the memory, the underlying memory allocator may not immediately return that memory to the OS ... the resident set size (RSS) of the process might not decrease" gc.collect() merges deferred counts
It is the high-water mark RSS shows what the process had, not what Python holds now Compare with tracemalloc current memory

Here is the first experiment, comparing three allocators on the same workload. It imports a small helper, rss_helper.py, listed in 8.2: save that file next to it first. It allocates a 200 MiB block, frees it, allocates three million small strings, keeps 0.1 percent, then frees those too:

python
# e07_rss.py: why RSS does not always drop when you free objects
import gc
from rss_helper import rss_mib

def show(label):
    print(f"{label:<44} RSS = {rss_mib():7.1f} MiB")

show("start")
big = bytearray(200 * 2**20)          # one 200 MiB block: served by the OS directly
for i in range(0, len(big), 4096): big[i] = 1     # touch every page so it is really resident
show("after one 200 MiB bytearray (touched)")
del big
show("after del of the 200 MiB block")

N = 3_000_000
objs = [str(i) for i in range(N)]     # millions of small objects: served by pymalloc arenas
show(f"after {N:,} small strings")
keep = objs[::1000]                   # keep 0.1 percent, spread across every arena
del objs
gc.collect()
show("after freeing 99.9 percent of them")
print("kept objects:", len(keep))
del keep
gc.collect()
show("after freeing the rest")
Example output · illustrative24 lines
--- default (pymalloc)
start                                        RSS =    16.0 MiB
after one 200 MiB bytearray (touched)        RSS =   216.0 MiB
after del of the 200 MiB block              RSS =   216.0 MiB
after 3,000,000 small strings                RSS =   378.8 MiB
after freeing 99.9 percent of them           RSS =   378.8 MiB
kept objects: 3000
after freeing the rest                       RSS =   242.8 MiB
--- PYTHONMALLOC=malloc
start                                        RSS =    16.1 MiB
after one 200 MiB bytearray (touched)        RSS =   216.1 MiB
after del of the 200 MiB block              RSS =   216.1 MiB
after 3,000,000 small strings                RSS =   379.2 MiB
after freeing 99.9 percent of them           RSS =   179.2 MiB
kept objects: 3000
after freeing the rest                       RSS =   156.4 MiB
--- PYTHONMALLOC=mimalloc
start                                        RSS =    15.7 MiB
after one 200 MiB bytearray (touched)        RSS =   215.8 MiB
after del of the 200 MiB block              RSS =   215.8 MiB
after 3,000,000 small strings                RSS =   241.0 MiB
after freeing 99.9 percent of them           RSS =   241.0 MiB
kept objects: 3000
after freeing the rest                       RSS =   241.0 MiB

Do not over-read this. The point is that the same Python program shows three different RSS curves depending on the allocator and the operating system:

  • With the default allocator (pymalloc), freeing 99.9 percent of the small strings changed RSS by nothing (fragmentation, 4.4). With PYTHONMALLOC=malloc the system allocator could give a large part back (RSS fell by about 200 MiB). With mimalloc nothing came back at all, consistent with its delayed purge.
  • On this macOS machine even freeing the 200 MiB block did not lower the number. On Linux, a block that large is typically served by mmap and freed with munmap, and RSS usually does fall immediately. macOS keeps freed pages attributed to the process until the system needs them. The ordering "big blocks come back, small objects do not" is the portable lesson; the exact numbers are not.
  • None of this is a leak. The memory is free inside the process and will be reused for the next allocations. It only looks like a leak on a dashboard.

The container experiment, which is deterministic:

python
# e20_shrink.py: containers keep their capacity after you empty them
import sys

d = {i: None for i in range(100_000)}
full = sys.getsizeof(d)
for k in list(d):
    del d[k]
print("dict: len", len(d), "| size after deleting every key:", sys.getsizeof(d) >= full * 0.9 and "still the full-size table" or "shrunk")
d2 = dict(d)                    # rebuild: the copy is sized for its contents
print("dict(d) copy is tiny:", sys.getsizeof(d2) < 1000)
d.clear()                       # clear() DOES release the table
print("d.clear() releases it:", sys.getsizeof(d) < 1000)

lst = list(range(100_000))
big = sys.getsizeof(lst)
del lst[10:]
print("list after del lst[10:] shrank:", sys.getsizeof(lst) < big / 2)

s = set(range(100_000))
bigset = sys.getsizeof(s)
for x in list(s): s.discard(x)
print("set after discarding all keeps its table:", sys.getsizeof(s) >= bigset * 0.9)
Output · Python 3.14.65 lines
dict: len 0 | size after deleting every key: still the full-size table
dict(d) copy is tiny: True
d.clear() releases it: True
list after del lst[10:] shrank: True
set after discarding all keeps its table: True

Deleting every key from a dict of 100,000 entries left the table at full size; d.clear() or building a fresh dict(d) released it. A list shrinks when you delete from the end by a large factor, a set does not.

4.6 PYTHONMALLOC, mimalloc and the debug hooks#

The allocator can be chosen at start-up with the PYTHONMALLOC environment variable. The values the documentation lists:

Value Meaning
pymalloc The default in a normal release build
malloc Bypass pymalloc and use the C library allocator directly (useful for running under Valgrind or for the A/B comparison above)
mimalloc Use Microsoft's mimalloc. Added in Python 3.13; default and required in the free-threaded build (which uses per-thread heaps so that allocation proceeds "without locking in most cases"). Available but not default in the normal build; can be disabled at build time with --without-mimalloc
debug Keep the current allocator but install debug hooks that detect buffer overruns and use-after-free (also on release builds since Python 3.6)
pymalloc_debug, malloc_debug, mimalloc_debug The same, naming the allocator explicitly

Practical advice: use the default. Reach for PYTHONMALLOC=malloc when you suspect pymalloc fragmentation and want to test the hypothesis (does RSS behave differently?), and PYTHONMALLOC=debug in tests of C extensions. Switching allocators in production to cure a leak is treating the symptom.

Linux and glibc: when it is not pymalloc

Linux-only, and not run here (this lesson was built on macOS). Most real "RSS never drops" tickets for multi-threaded or async Python services on Linux containers are about the C library's allocator, not pymalloc, because large allocations, NumPy buffers and C-extension memory all go to glibc's malloc. Note also that with PYTHONMALLOC=malloc glibc, not pymalloc, becomes the allocator that decides everything. The levers, per the glibc manual's malloc tunables:

Lever What it does Trade-off
MALLOC_ARENA_MAX=2 (tunable glibc.malloc.arena_max) Caps the number of malloc arenas. glibc gives threads separate arenas to reduce lock contention, and each arena keeps its own free memory, so many threads can multiply the freed-but-held memory. By default the limit scales with the number of CPU cores Fewer arenas means more contention between threads: measure latency
MALLOC_TRIM_THRESHOLD_ (tunable glibc.malloc.trim_threshold) The minimum size of the top-most free chunk of an arena before it is returned to the OS. Default 128 KB, adjusted dynamically; setting it turns the dynamic adjustment off Lower values return memory sooner and cost more system calls
malloc_trim(0) through ctypes (ctypes.CDLL("libc.so.6").malloc_trim(0)) Asks glibc to release free memory it can, on demand A call, not a fix: call it after a known big free (the end of a batch), not in a hot path
jemalloc or tcmalloc through LD_PRELOAD Replaces glibc's allocator entirely, with different fragmentation and trimming behaviour A deployment change with its own tuning; try it as an experiment

The rule: change one thing, then measure RSS and p99 latency before and after, under a realistic load. Environment variables are the cheapest first experiment because they need no code change.

4.7 What this means for an AI engineer#

  • RSS lies in both directions. It stays high after freeing (fragmentation, lazy return) and it hides sharing between processes (Part 5). Alert on it, but diagnose with tracemalloc and the allocator statistics.
  • Process-per-job beats a long-lived process for batch work. If a nightly import allocates 8 GB of small objects, the cleanest way to give the memory back is for the importer to run in a separate process that exits (a subprocess, a ProcessPoolExecutor worker, a job container). The OS then takes everything.
  • Worker recycling is the standard production backstop. Gunicorn's max_requests ("the maximum number of requests a worker will process before restarting", default 0, disabled) with max_requests_jitter ("the maximum jitter to add", so workers do not all restart at once) caps the damage of slow growth and fragmentation. It is a backstop, not a fix: it hides leaks until they are expensive.
  • The standard library has its own recycling. ProcessPoolExecutor(max_tasks_per_child=N) (added in 3.11) replaces a worker process after N tasks, and multiprocessing.Pool(maxtasksperchild=N) does the same. The concurrent.futures documentation says the option "is incompatible with the "fork" start method" and that, when it is set without an mp_context, "spawn" is used. The script below shows the worker pids (the counts are deterministic, the pid values are not):
python
# recycle_workers.py: each worker process exits after 2 tasks and is replaced
import multiprocessing as mp
import os
from concurrent.futures import ProcessPoolExecutor

def task(i: int) -> int:
    return os.getpid()

if __name__ == "__main__":
    ctx = mp.get_context("spawn")      # max_tasks_per_child is not supported with the fork start method
    with ProcessPoolExecutor(max_workers=1, mp_context=ctx, max_tasks_per_child=2) as ex:
        pids = [ex.submit(task, i).result() for i in range(6)]   # one task at a time
    print("executor: tasks:", len(pids), "distinct worker pids:", len(set(pids)))
    print("executor: each pid served exactly 2 tasks:", all(pids.count(p) == 2 for p in set(pids)))

    with ctx.Pool(1, maxtasksperchild=2) as pool:
        pids = pool.map(task, range(6), chunksize=1)
    print("Pool:     tasks:", len(pids), "distinct worker pids:", len(set(pids)))
    print("Pool:     each pid served exactly 2 tasks:", all(pids.count(p) == 2 for p in set(pids)))
Output · Python 3.14.64 lines
executor: tasks: 6 distinct worker pids: 3
executor: each pid served exactly 2 tasks: True
Pool:     tasks: 6 distinct worker pids: 3
Pool:     each pid served exactly 2 tasks: True

Three workers served six tasks, two each, and then each was replaced by a fresh process (which starts with none of the old process's fragmentation). The example submits one task at a time on purpose: the 3.15 documentation records a fixed deadlock (gh-115634) where the executor could hang after a worker reached its limit while tasks remained queued, and on 3.14.6 a bulk ex.map over six tasks on one worker did not finish when tried. If you use this option on 3.14 or earlier, test bulk submission with your workload first.

  • Cap memory to test your limits. On Linux, resource.setrlimit(resource.RLIMIT_AS, (limit, limit)) caps a process's address space so allocations beyond it fail with MemoryError that your code can catch; this is not meaningful on macOS, and a container's cgroup limit works differently (the kernel's OOM killer ends the process instead, with no exception to catch). To rehearse "does my service survive at its limit?", run it under a low container limit (for example docker run --memory=512m) with a realistic load and watch for restarts and the kill reason in the runtime's events. Neither was run for this lesson.
  • Keep survivors compact. After filtering a big batch down to what you keep, copy the survivors into fresh objects and drop the original.
  • Set limits from measurements. A container memory limit should come from peak RSS under realistic load, with headroom, not from getsizeof arithmetic.

Part 5: Fork, copy-on-write and many workers#

5.1 The promise of copy-on-write#

Production Python services usually run several worker processes (Gunicorn workers, a ProcessPoolExecutor, a job queue with N consumers). A sensible plan is to load the big, read-only data once (a tokenizer vocabulary, an embedding matrix, a product catalogue) in a parent process, then start the workers from it. On Linux, fork() starts a child that shares the parent's memory pages instead of copying them. The operating system marks the shared pages read-only; the first time either process writes to a page, the OS makes a private copy of that page for the writer. That is copy-on-write (CoW). If the workers only read the data, N workers cost roughly the memory of one.

The analogy: two flatmates sharing one textbook. Nobody photocopies a page until somebody wants to write in the margin, and then only that page is copied.

5.2 Why Python breaks the promise: reading is writing#

Part 2 explained the catch. Binding a Python object to a name raises its reference count, and the count lives in the object's header, in the same page as its data. A child that merely iterates over a list of a million strings increments and decrements a count in every string. Each of those writes touches a page, so the OS copies it. The "read-only" data is copied into every worker, one page at a time, as it is used. The bytes of a single big bytes object or an array are different: reading them does not write to their pages, because there is one header for the whole buffer and no per-element object.

What the child reads Does reading dirty the shared pages? Why
A list or dict of many small Python objects (str, dict, instances) Yes, as it touches each object Each object's reference count is written to
A bytes, array.array, mmap, NumPy array, memoryview over one of those No (apart from the one header) One object; elements are raw bytes, no counts
None, True, small ints, static types, interned identifiers (3.12+) No Immortal objects (2.4)
The garbage collector's own bookkeeping Yes, on every collection The GC header lives next to each tracked object and the collector writes to it while scanning

The last row is the second source of copy-on-write damage: even a child that never touches your data will have its pages dirtied by the cyclic collector scanning all tracked objects. That is exactly what gc.freeze() was added to prevent.

You can measure this without Linux's /proc. When a process first writes to a shared copy-on-write page, the kernel takes a minor page fault to make the private copy, so the child's count of minor faults (resource.getrusage(...).ru_minflt) tracks the copying. 01C.7 §8.2 uses the same method. The child below does one of two jobs, each with and without gc.freeze(): read every object (a refcount write per object), or call gc.collect() (a GC-header write per tracked object). The parent calls gc.unfreeze() before each fork so a freeze from an earlier row does not leak into the next. The data is 500,000 small dicts, which are tracked containers.

python
# cow_faults.py: POSIX only (fork, ru_minflt). Run: python3 cow_faults.py
import gc
import os
import resource

def faults() -> int:
    return resource.getrusage(resource.RUSAGE_SELF).ru_minflt

def read_all(data: list) -> None:
    n = 0
    for d in data:            # binds each dict to `d`: a refcount write per object
        n += 1

def collect(data: list) -> None:
    gc.collect()              # the collector writes to the GC header of every tracked object

def run(data: list, work, freeze: bool) -> int:
    gc.unfreeze()             # undo any earlier freeze, or it would persist across rows
    if freeze:
        gc.freeze()           # as the gc docs recommend, right before fork
    r, w = os.pipe()
    pid = os.fork()
    if pid == 0:
        before = faults()
        work(data)
        os.write(w, str(faults() - before).encode())
        os._exit(0)
    os.waitpid(pid, 0)
    os.close(w)
    n = int(os.read(r, 32))
    os.close(r)
    return n

if __name__ == "__main__":
    data = [{"id": i, "text": "chunk"} for i in range(500_000)]
    gc.collect()
    res = {}
    for name, work in [("read every object", read_all), ("gc.collect()", collect)]:
        for freeze in (False, True):
            res[(name, freeze)] = run(data, work, freeze)
            print(f"child does {name:<18} freeze={str(freeze):<5} minor faults: {res[(name, freeze)]:>6,}")
    print("read, no freeze > 1000 faults:", res[("read every object", False)] > 1000)
    print("read, freeze > 1000 faults:   ", res[("read every object", True)] > 1000)
    print("collect without freeze faults >20x collect with freeze:",
          res[("gc.collect()", False)] > 20 * res[("gc.collect()", True)])

Output (Python 3.14.6, macOS, GIL build; the booleans are the stable part, the fault counts vary by machine, page size and version, so treat them as illustrative):

text
child does read every object  freeze=False minor faults:  4,237
child does read every object  freeze=True  minor faults:  4,235
child does gc.collect()       freeze=False minor faults:  9,487
child does gc.collect()       freeze=True  minor faults:     59
read, no freeze > 1000 faults: True
read, freeze > 1000 faults:    True
collect without freeze faults >20x collect with freeze: True

Both "read" rows are large and equal: gc.freeze() cannot help a child whose own loop writes every object's reference count. The "collect" rows differ by far more than 20 times: frozen objects are skipped by the collector, so it stops dirtying their pages. A child that never collects shows no difference at all, which is why the collection job is part of the experiment. The lesson: freezing helps a worker that is mostly idle with respect to your data (a web worker touching a few objects per request, while the collector runs now and then); it cannot rescue a child that sweeps over millions of objects. The only complete cure is to keep the large read-only data in non-object form, discussed next.

On Linux you can also read /proc/self/smaps_rollup (Private_Dirty and Shared_* lines) for byte counts instead of fault counts; that file does not exist on macOS, so this lesson does not show output for it.

5.3 The fixes, and their limits#

Fix What it does Limit
Load the data before fork, with gc.freeze() The official recipe in the gc docs: "call gc.disable() early in the parent process, gc.freeze() right before fork(), and gc.enable() early in child processes" Does not stop your code's refcount writes; only the collector's
Preload the app in the parent (Gunicorn --preload, setting preload_app: "Load application code before the worker processes are forked", which per its docs "saves RAM and speeds up boot") Workers inherit the parent's already-imported modules and data Same limit; and a bug that corrupts shared state at import time hits every worker
Store big read-only data as one buffer (array.array, bytes, a memory-mapped file, a NumPy array) One header for the whole buffer; reads do not write to its pages; the OS shares them for real You pay with an index structure: a dict mapping id to offset is a million small objects again, so keep the index as arrays too
Use shared memory explicitly (multiprocessing.shared_memory, mmap) Memory that is meant to be shared, not accidentally Lifecycle and synchronization are your job: 01C.7
Fewer, longer-lived processes, with threads (or async) inside One copy of the data per process, shared by every thread for free The GIL for CPU-heavy work: 01C.5
Do not rely on fork at all A fresh interpreter per worker, then load or map the data once per worker (memory-mapped data is still shared by the OS page cache) Slower start-up

Start methods matter here. The multiprocessing documentation says that on POSIX platforms the default start method changed from fork to forkserver in Python 3.14: "to retain the performance but avoid common multithreaded process incompatibilities", and that fork "is no longer the default start method on any platform" (macOS and Windows already defaulted to spawn). Safely forking a multithreaded process is, in the documentation's words, "problematic", and since 3.12 os.fork() emits a DeprecationWarning if Python detects multiple threads. Two consequences for this lesson: code that relied on fork-inherited data now has to ask for get_context("fork") explicitly, and under the new defaults each worker is a fresh process that does not inherit the parent's objects: each one loads or maps its own copy. Only the multiprocessing default changed: Gunicorn and a direct os.fork() are unaffected. Start methods are 01C.7's subject; the memory consequence is yours.

5.4 What this means for an AI engineer#

  • The "load the model/index once, fork N workers" design only saves memory if the shared data is a few big buffers. A million Python dict chunks are copied into every worker as they are read.
  • Keep embedding matrices as array, memoryview over a memory-mapped file, or NumPy arrays (6.4 and Part 10), and chunk metadata in a database or a compact columnar form.
  • Use gc.freeze() after startup loading in every long-lived worker, with or without fork. It removes scanning cost and the collector's page writes.
  • Compare per-container memory limits to PSS, not summed RSS, when you decide how many workers fit.

Part 6: Shrinking data: __slots__, generators and buffers#

This part is about design choices that change memory by factors of two to ten. Each one has a price, and the decision tables say when it is worth paying.

6.1 __slots__ and @dataclass(slots=True)#

By default, an instance stores its attributes in a per-instance dictionary (__dict__). Declaring __slots__ = ("id", "score") tells Python the attribute names up front, so instances store them in fixed slots and have no __dict__ at all. @dataclass(slots=True) (Python 3.10+) generates the slots for you. The experiment below stores 100,000 records five ways and measures what each really costs with tracemalloc:

python
# e09_layouts.py: the same records stored five ways; real memory from tracemalloc
import array
import sys
import tracemalloc
from dataclasses import dataclass

N = 100_000

class Plain:
    def __init__(self, i, score): self.id = i; self.score = score
class Slotted:
    __slots__ = ("id", "score")
    def __init__(self, i, score): self.id = i; self.score = score
@dataclass(slots=True)
class DC:
    id: int
    score: float

def measure(label, build):
    tracemalloc.start()
    obj = build()
    current, _ = tracemalloc.get_traced_memory()
    tracemalloc.stop()
    print(f"{label:<34} {current / N:7.1f} bytes per record")
    return obj

keep = []
keep.append(measure("dict per record",       lambda: [{"id": i, "score": i * 0.5} for i in range(N)]))
keep.append(measure("plain class (has __dict__)", lambda: [Plain(i, i * 0.5) for i in range(N)]))
keep.append(measure("class with __slots__",   lambda: [Slotted(i, i * 0.5) for i in range(N)]))
keep.append(measure("@dataclass(slots=True)", lambda: [DC(i, i * 0.5) for i in range(N)]))
keep.append(measure("tuple per record",       lambda: [(i, i * 0.5) for i in range(N)]))
keep.append(measure("two array.array columns", lambda: (array.array("q", range(N)), array.array("d", (i * 0.5 for i in range(N))))))

print("--- one object's own size (getsizeof) hides what it points to ---")
p = Plain(1, 0.5)
print("Plain instance getsizeof:", sys.getsizeof(p))
print("Slotted instance getsizeof:", sys.getsizeof(Slotted(1, 0.5)))
print("Slotted has __dict__:", hasattr(Slotted(1, 0.5), "__dict__"))
Example output · illustrative10 lines
dict per record                      247.9 bytes per record
plain class (has __dict__)           152.0 bytes per record
class with __slots__                 111.9 bytes per record
@dataclass(slots=True)               111.9 bytes per record
tuple per record                     127.9 bytes per record
two array.array columns               16.3 bytes per record
--- one object's own size (getsizeof) hides what it points to ---
Plain instance getsizeof: 48
Slotted instance getsizeof: 48
Slotted has __dict__: False

What to take from it:

  • A dict per record is the most expensive: about 248 bytes for two small fields. This is the shape of most parsed JSON.
  • __slots__ saves about a quarter to a third against a plain class (112 against 152 bytes here). On older Pythons the saving was bigger. Python 3.14's instance layout is already compact, so measure before you convert.
  • Two array.array columns cost about 16 bytes per record, an order of magnitude less than any per-record object. We are storing the numbers, not objects holding numbers.
  • On 3.13 and later a plain instance keeps its attribute values in a block attached to the object (inline values), so getsizeof(p) (48) leaves them out; touching p.__dict__ would create a real dict of hundreds of bytes that normal code never builds. tracemalloc shows the real cost (152 against 112 bytes per record). This is exactly the getsizeof blind spot from 1.5. getsizeof of a slotted instance (48) is closer to the whole story, and it has no __dict__.

The price of __slots__:

Cost Detail
No new attributes at runtime obj.typo = 1 raises AttributeError (a feature as much as a limit)
No weak references by default Add "__weakref__" to __slots__ if you need them (2.6)
Inheritance is fiddly Every class in the chain must declare slots, or __dict__ comes back; do not repeat parent slot names
Pickling, vars(), copy Work, but code that reads obj.__dict__ breaks

Use it for millions of small, uniform, long-lived objects (parsed chunks, events, tokens with spans). Do not bother for a few hundred configuration objects.

6.2 Tuples, named tuples and columns#

A tuple is immutable and, with its member numbers counted, cost 128 bytes per record in the experiment, a little more than a slotted object (112); a typing.NamedTuple gives it field names with no extra per-instance cost. Both still hold one pointer plus one object per field.

The step change is columnar storage (called structure of arrays): instead of a list of a million records each holding an id and a score, keep one array of ids and one array of scores. Numbers live packed in the buffer, with no per-element header and no reference count. This is also how NumPy and pandas store data (01B.11), and why they are fast and small. If you cannot use NumPy, array.array is the standard-library form of the idea.

Layout Bytes per record (two numeric fields) Use when
dict per record about 250 The shape is dynamic; records are few, or short-lived
Plain class instance about 150 Behaviour and a few thousand instances
__slots__ / slots=True about 110 Millions of uniform objects with methods
Tuple / NamedTuple about 130 Immutable records in a list, results of a parse
Columns (array, NumPy) about 16 Numeric data you will scan or vectorize; embeddings

6.3 Generators instead of lists#

A generator produces values one at a time and keeps only its current state. When you only need to loop over a sequence once (to sum, filter, write, batch), building a list first holds every item in memory at the same time for no benefit.

python
# e10_streams.py: list vs generator, bytes vs memoryview, array vs list
import array
import sys
import tracemalloc

def peak(label, fn):
    tracemalloc.start()
    result = fn()
    _, peak_bytes = tracemalloc.get_traced_memory()
    tracemalloc.stop()
    print(f"{label:<46} peak = {peak_bytes / 2**20:8.2f} MiB   result = {result}")

N = 1_000_000
peak("sum(list of squares)",        lambda: sum([i * i for i in range(N)]))
peak("sum(generator of squares)",   lambda: sum(i * i for i in range(N)))

print("--- bytes slice copies, memoryview slice does not ---")
blob = bytes(range(256)) * 40_000          # about 10 MB
peak("blob[1:] (copy)",           lambda: len(blob[1:]))
peak("memoryview(blob)[1:] (view)", lambda: len(memoryview(blob)[1:]))

print("--- a million floats: list vs array('f') vs array('d') ---")
lst = [float(i) for i in range(N)]
print("list of floats  :", f"{(sys.getsizeof(lst) + sum(sys.getsizeof(x) for x in lst)) / 2**20:.1f} MiB")
a64 = array.array("d", lst)
a32 = array.array("f", lst)
print("array('d') 8 B  :", f"{sys.getsizeof(a64) / 2**20:.1f} MiB")
print("array('f') 4 B  :", f"{sys.getsizeof(a32) / 2**20:.1f} MiB")
print("float32 rounds:  ", a32[1], "from 0.1 ->", array.array("f", [0.1])[0])
Example output · illustrative10 lines
sum(list of squares)                           peak =    38.57 MiB   result = 333332833333500000
sum(generator of squares)                      peak =     0.00 MiB   result = 333332833333500000
--- bytes slice copies, memoryview slice does not ---
blob[1:] (copy)                                peak =     9.77 MiB   result = 10239999
memoryview(blob)[1:] (view)                    peak =     0.00 MiB   result = 10239999
--- a million floats: list vs array('f') vs array('d') ---
list of floats  : 30.9 MiB
array('d') 8 B  : 7.6 MiB
array('f') 4 B  : 3.8 MiB
float32 rounds:   1.0 from 0.1 -> 0.10000000149011612

The list comprehension sum([i * i for i in range(N)]) peaked near 39 MiB because it built a million integers and a million-slot list before summing; the generator sum(i * i for i in range(N)) peaked near zero. The result is identical.

The reflex to build is "does the next stage need all of it at once?" Things that secretly force a full list:

  • list(...), sorted(...), list(reversed(x)), len(list(...))
  • .read() and .readlines() on a file (use iteration: for line in f)
  • json.load on a file with a million records (use JSONL, one record per line, and json.loads per line)
  • pd.read_csv without chunksize, Response.json() on a huge body, cursor.fetchall() (use fetchmany, or iterate the cursor)
  • asyncio.gather(*[... for 1_000_000 items]) (a million task objects; use a bounded worker pool, 01B.4 §2.2)

6.4 bytes, bytearray, array and memoryview#

Raw buffers avoid per-element objects, and memoryview adds the other half: slicing without copying. Slicing a bytes makes a copy of the slice; slicing a memoryview makes a new view onto the same memory. The e10 output above shows the effect: blob[1:] of a 10 MB object peaked at 9.77 MiB (a copy), while memoryview(blob)[1:] peaked at zero.

Type Mutable? Use for
bytes No Immutable binary data: a file's contents, a hash, a downloaded PDF
bytearray Yes Building binary data incrementally; reading into a reusable buffer (readinto)
array.array(typecode) Yes A compact sequence of one numeric type ('f' 4-byte float, 'd' 8-byte, 'q' 8-byte int)
memoryview Per its source Slicing and passing parts of a buffer to struct, sockets, file reads and writes, without copying

The e10 experiment also shows the cost of precision: a million floats take 30.9 MiB as a list of float objects, 7.6 MiB as array('d') (8 bytes each) and 3.8 MiB as array('f') (4 bytes each). And array('f') stores 0.1 as 0.10000000149011612: float32 rounds. That is perfectly fine for embeddings (01B.11 §2.3 explains why) and wrong for money.

A memoryview also pins its source: while a view exists, a bytearray cannot be resized (BufferError), and a large source stays alive as long as any slice view does. Release views you no longer need (view.release(), or with memoryview(b) as v:).

6.5 Mutable default arguments and class attributes#

The oldest memory (and correctness) trap in Python is also a lesson in object identity: default argument values are evaluated once, when the function is defined, and shared by every call. Case 1 in 7.2 is exactly this bug (history=[]). The fix is history: list | None = None and history = [] if history is None else history. A class attribute that is a list or a dict is also shared by every instance unless you assign a new one in __init__.

6.6 Strings: width, copies and substrings#

A Python str is stored with the narrowest width that can represent every character in it: 1 byte per character if all are ASCII or Latin-1, 2 if the highest is in the Basic Multilingual Plane, 4 if any is outside it (emoji, many historic scripts). The width applies to the whole string. The e17 experiment above (at the end of 1.5) showed it: 1000 ASCII characters cost 1,041 bytes, 1000 € cost 2,058, and 999 ASCII characters plus one emoji cost 4,060.

Practical consequences for text pipelines:

  • A corpus that is 99.9 percent English with the occasional emoji costs four times what you would estimate for the strings that contain one. Chunk first, measure, then store. Cleaning (stripping emoji from stored text that will not be shown to users) shrinks memory only if you actually need that.
  • Slicing a str copies the slice. Splitting a 100 MB document into 50,000 chunks produces 50,000 new strings; the original can be freed only when you drop your reference to it.
  • A million tiny strings cost far more than their text: each has a 41-byte header on this build. Hold large chunks in memory and tiny ones in a compact structure.

6.7 What this means for an AI engineer#

  • A chunk store as a list[dict] of a few million entries is the most common accidental memory hog in RAG prototypes. Move to a database, a columnar structure, or at least slots=True dataclasses (05.9 discusses memory limits for ingestion).
  • Embeddings are columns: one float32 buffer, not a list of lists (01B.11 §2.3).
  • Pipelines should be generators or bounded queues end to end. The stage that builds a list is where your memory peak is.

Part 7: Leaks that are, and are not, leaks#

7.1 What "leak" means in Python#

Garbage collection means you rarely "forget to free". In Python a leak is almost always memory that is still reachable but no longer useful: something still holds a reference. That is different from the cases below, which look the same on a graph:

What you observe Real cause How to tell
RSS grows, then plateaus Warm-up: caches, imports, free lists, arena growth It flattens; tracemalloc shows no steady growth
RSS grows steadily with requests A real growth in reachable objects (the leak) tracemalloc diff keeps growing between identical rounds
RSS stays high after a peak Fragmentation, lazy return, high-water mark (4.5) tracemalloc current memory is low while RSS is high
RSS grows but tracemalloc shows nothing Native memory: a C extension, a database driver, a model runtime Compare tracemalloc total with RSS growth; use a native-aware profiler (8.5)
Memory jumps in steps under load Big objects (batch size, response size) Correlate with request size
Unbounded structure (a cache without a limit) Design bug: a leak by construction Read the code: is there an eviction rule?

Five ways memory stays alive by accident, each a real production pattern, run on Python 3.14.6:

python
# e11_leak_gallery.py: five ways memory stays alive "by accident"
import asyncio
import functools
import gc
import sys
import weakref

class Big:
    """A stand-in for a large object (an embedding matrix, a parsed PDF)."""
    def __init__(self, tag): self.tag = tag

def alive(refs): return sum(1 for r in refs if r() is not None)

# 1. Mutable default argument: one list for the whole process
def add_message(msg, history=[]):
    history.append(msg)
    return history
add_message("hi"); add_message("again")
print("1. default list shared across calls:", add_message("third"))

# 2. functools.lru_cache keeps every argument and result alive (and bound methods keep self alive)
class Embedder:
    @functools.lru_cache(maxsize=None)          # the cache lives on the CLASS, keyed by self
    def embed(self, text): return len(text)
e = Embedder()
probe = weakref.ref(e)
e.embed("hello")
del e
gc.collect()
print("2. lru_cache on a method keeps self alive:", probe() is not None)
Embedder.embed.cache_clear()
gc.collect()
print("   after cache_clear():", probe() is not None)

# 3. A module-level dict that only grows
SEEN: dict[str, Big] = {}
def handle(request_id):
    SEEN[request_id] = Big(request_id)           # never removed
for i in range(1000): handle(f"req-{i}")
print("3. global dict entries after 1000 requests:", len(SEEN))

# 4. An exception's traceback holds every frame, and every local in those frames
def work():
    big = Big("locals of a failed call")
    ref = weakref.ref(big)
    raise ValueError("boom")
saved = None
try:
    work()
except ValueError as exc:
    saved = exc                                    # storing the exception stores its traceback
frame = saved.__traceback__.tb_next.tb_frame
print("4. frame of the failed call still holds its locals:", sorted(frame.f_locals))
saved = None; frame = None
gc.collect()

# 5. asyncio keeps only a WEAK reference to tasks: an un-referenced task can vanish mid-flight
async def background(results):
    await asyncio.sleep(0)
    results.append("done")
async def main():
    results = []
    t = asyncio.create_task(background(results))
    await t
    print("5. task finished, results:", results)
    # the safe pattern: hold a strong reference until the task completes
    background_tasks = set()
    t2 = asyncio.create_task(background(results))
    background_tasks.add(t2)
    t2.add_done_callback(background_tasks.discard)
    await asyncio.sleep(0.01)
    print("   strong-ref set is empty again after completion:", len(background_tasks) == 0)
asyncio.run(main())
Output · Python 3.14.67 lines
1. default list shared across calls: ['hi', 'again', 'third']
2. lru_cache on a method keeps self alive: True
   after cache_clear(): False
3. global dict entries after 1000 requests: 1000
4. frame of the failed call still holds its locals: ['big', 'ref']
5. task finished, results: ['done']
   strong-ref set is empty again after completion: True
  1. A mutable default argument is one list for the whole process: three calls, one history. In a web service this is also a data-leak between users.
  2. functools.lru_cache on a method. The cache lives on the class and its key includes self, so every instance that ever called the method stays alive until its entry is evicted. The official functools documentation says it plainly: "If a method is cached, the self instance argument is included in the cache" and "the cache keeps references to the arguments and return values until they age out of the cache or until the cache is cleared." With maxsize=None (the same as functools.cache) nothing ever ages out. The default for lru_cache is maxsize=128; always set it deliberately. For methods, either cache a module-level function keyed on the data, not on self, or keep a per-instance cache that dies with the instance.
  3. A module-level dict that only grows. SEEN[request_id] = ... with no removal: 1000 requests, 1000 entries, forever. Every registry, "recent requests" list, in-memory job table and metrics-label dictionary is the same shape. The fix is a rule for removing entries: a size limit, a time limit, or a with/finally that removes the entry when the request ends.
  4. A stored exception keeps its frames. saved = exc stores the exception, whose __traceback__ references every frame it passed through, and each frame references its local variables. In the output the frame of the failed call still holds big (imagine an embedding matrix or a 20 MB document). Retry loops that save "the last error" are a classic version. Store repr(exc), or clear the traceback with exc.__traceback__ = None (or exc.with_traceback(None)), and never keep the exception object in a long-lived structure.
  5. asyncio tasks are only weakly referenced. The asyncio.create_task documentation warns: "Save a reference to the result of this function, to avoid a task disappearing mid-execution. The event loop only keeps weak references to tasks. A task that isn't referenced elsewhere may get garbage collected at any time, even before it's done." The fix in the output is the documented pattern: a set that holds each task until its done-callback removes it. The opposite failure also exists: a strong-reference set whose done-callback is missing grows forever. (TaskGroup, 01C.2, holds its tasks for you.)

More shapes of the same bug, for the review checklist:

Pattern Why it retains Fix
Observer, callback or signal lists that you only ever add to The list holds the callable (and its self) Unsubscribe in close/finally; WeakMethod
Growing log or "debug history" lists Same as the global dict collections.deque(maxlen=N)
Closures defined in a loop or per request, stored globally The closure cell holds the loop's variables Store only what the closure needs
threading.local or contextvars values on long-lived threads The slot lives as long as the thread Reset at the end of the job (01C.3 §8.5)
A slice or view that keeps its large source alive memoryview slices and (in NumPy) array views refer to the base buffer Copy the small part you keep: bytes(view[a:b])
Per-request objects stored on app.state or a module global Cross-request retention (and a data leak) Request-scoped dependencies (01B.7 §4.2)
Exception tracebacks held by Future/Task results nobody awaits The finished future stores the exception Always await or inspect task results
Interactive environments (sys.last_traceback, notebook output history) They deliberately keep recent values alive Restart the kernel; do not diagnose a notebook as a service

7.3 Bounded caches that do not leak#

A cache is supposed to hold memory; the bug is a cache with no rule for letting go. A production cache needs at least a limit on entries, and, when values vary in size (embeddings, responses, documents), a limit on bytes. A time limit (TTL) belongs here too when the data can go stale (see 11B.3 §3.4 for backends and policies). Here is a small, thread-safe, dependency-free LRU cache with both limits:

python
# e18_bounded_cache.py: a bounded LRU cache with a memory-aware limit (stdlib, thread-safe)
import threading
from collections import OrderedDict
from collections.abc import Callable
from typing import Generic, Hashable, TypeVar

K = TypeVar("K", bound=Hashable)
V = TypeVar("V")

class BoundedCache(Generic[K, V]):
    """LRU cache bounded by entry count AND by an approximate byte budget."""

    def __init__(self, max_entries: int, max_bytes: int, sizeof: Callable[[V], int]) -> None:
        self._data: OrderedDict[K, tuple[V, int]] = OrderedDict()
        self._max_entries, self._max_bytes, self._sizeof = max_entries, max_bytes, sizeof
        self._bytes = 0
        self._lock = threading.Lock()
        self.evictions = 0

    def get(self, key: K) -> V | None:
        with self._lock:
            if key not in self._data:
                return None
            self._data.move_to_end(key)             # most recently used goes last
            return self._data[key][0]

    def put(self, key: K, value: V) -> None:
        size = self._sizeof(value)
        with self._lock:
            if key in self._data:
                self._bytes -= self._data.pop(key)[1]
            self._data[key] = (value, size)
            self._bytes += size
            while len(self._data) > self._max_entries or self._bytes > self._max_bytes:
                _, (_, evicted_size) = self._data.popitem(last=False)   # least recently used
                self._bytes -= evicted_size
                self.evictions += 1

    def __len__(self) -> int:
        return len(self._data)

cache: BoundedCache[str, list[float]] = BoundedCache(
    max_entries=1000, max_bytes=64 * 1024, sizeof=lambda v: len(v) * 8)   # 64 KiB of float64 payload
for i in range(100):
    cache.put(f"doc-{i}", [0.0] * 256)            # 2 KiB per vector: only 32 fit in 64 KiB
print("entries kept:", len(cache), "| evictions:", cache.evictions)
print("oldest gone, newest present:", cache.get("doc-0") is None, cache.get("doc-99") is not None)
Output · Python 3.14.62 lines
entries kept: 32 | evictions: 68
oldest gone, newest present: True True

One hundred 2 KiB vectors went in; only 32 fit under the 64 KiB budget, the oldest 68 were evicted, the newest is present. The design notes:

  • OrderedDict.move_to_end and popitem(last=False) give O(1) LRU. The lock covers the whole put including the eviction loop; see 01C.3 §7.2 for why a lock around only the insert would not protect the invariant "bytes equals the sum of sizes".
  • The size function is yours, because only you know what a value costs. len(v) * 8 is the payload of a float64 vector; sys.getsizeof would be wrong for the reasons in 1.5.
  • For asyncio services the same structure works without the lock if no await sits between check and update (01C.3 §4.1); add single-flight for stampedes (01B.4 §7.1).
  • Libraries exist (for example cachetools, a third-party package that provides LRU, TTL and size-aware caches). Not run here; look up the current release on PyPI before using it. The standard-library functools.lru_cache(maxsize=N) is fine for pure functions of hashable arguments; it has no byte budget and no TTL.

7.4 What this means for an AI engineer#

  • Every AI service has caches (embeddings, completions, tool results, parsed documents). Review each for a maximum size, a maximum age and a byte budget when values vary.
  • Retry and agent loops that remember errors, transcripts or intermediate tool outputs are the place unbounded growth hides: keep summaries, cap history length, and never store exception objects.
  • A leak that appears only after hours is usually one of the table's rows. Check them before reaching for a profiler.

Part 8: Measuring memory#

8.1 RSS, VMS, USS and PSS#

Four numbers describe a process, and confusing them is the root of most bad dashboards.

Name Meaning Good for
VMS (virtual memory size) Address space the process has reserved, whether or not it is in RAM Almost nothing; it is large and meaningless for sizing (mapped libraries, reserved arenas, thread stacks)
RSS (resident set size) Pages currently in physical memory, including pages shared with other processes "Is the process big?" What top/ps/Docker show and what OOM killers act on
USS (unique set size) Memory that belongs only to this process "What would be freed if this process exited?"
PSS (proportional set size) USS plus this process's share of each shared page, divided among the processes sharing it Summing a fleet of forked workers correctly

Thread stacks are part of VMS: each thread reserves a stack of address space, whose size you can read and change with threading.stack_size() (it returns 0 meaning "use the platform default"; see the threading docs for the allowed values). A service with hundreds of threads therefore has a large VMS without using that memory, because only the touched pages of each stack become resident. That is another reason to size from RSS, USS and PSS and never from VMS.

On Linux, PSS and USS come from /proc/<pid>/smaps or /proc/<pid>/smaps_rollup (the Pss, Private_Clean and Private_Dirty lines). The third-party package psutil exposes them as Process().memory_full_info() (uss, pss on Linux); it is awareness only here and not run. macOS has no PSS; use the container or vmmap/Activity Monitor ("Real Memory", "Memory") for rough comparisons.

8.2 resource, /proc and ps#

For a quick look inside a script, the standard library gives you peak RSS with resource.getrusage. Units differ by platform: bytes on macOS, KiB on Linux.

python
# e14_rusage.py: peak RSS from resource; units differ by OS
import resource
import sys

peak = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
unit = 1 if sys.platform == "darwin" else 1024          # macOS reports bytes, Linux reports KiB
print("peak RSS is a positive number:", peak > 0)
blob = bytearray(100 * 2**20)
for i in range(0, len(blob), 4096): blob[i] = 1
peak2 = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss * unit
print("peak grew by at least 90 MiB:", peak2 - peak * unit >= 90 * 2**20)
del blob
peak3 = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss * unit
print("peak does not shrink after del:", peak3 == peak2)
Output · Python 3.14.63 lines
peak RSS is a positive number: True
peak grew by at least 90 MiB: True
peak does not shrink after del: True

ru_maxrss is a high-water mark: it can only go up, so it will not show that you freed memory. For the current RSS, read /proc/self/statm on Linux or ask ps -o rss= -p <pid> (macOS, Linux). The rss_helper.py used by the experiment in 4.5 does exactly that with the standard library alone:

python
# rss_helper.py: current resident set size in MiB, stdlib only (Linux /proc, otherwise ps)
import os
import subprocess

def rss_mib() -> float:
    try:
        with open("/proc/self/statm") as f:
            pages = int(f.read().split()[1])
        return pages * os.sysconf("SC_PAGE_SIZE") / 2**20
    except FileNotFoundError:
        out = subprocess.run(["ps", "-o", "rss=", "-p", str(os.getpid())],
                             capture_output=True, text=True, check=True).stdout
        return int(out.strip()) / 1024      # ps reports KiB

(resource is POSIX-only: it does not exist on Windows. On Windows, psutil or Task Manager are the usual route; the lesson does not run them.)

8.3 tracemalloc: where Python allocated, and the difference between two moments#

tracemalloc is the standard library's memory tracer. It hooks Python's allocators and records which line of code allocated every live block. The documentation's key points:

  • Start it early: "the module should be started as early as possible by setting the PYTHONTRACEMALLOC environment variable to 1, or by using -X tracemalloc command line option", or call tracemalloc.start(). "The snapshot does not include memory blocks allocated before the tracemalloc module started to trace."
  • tracemalloc.start(nframe) keeps up to nframe stack frames per allocation (default 1). More frames cost more memory and CPU, measurable with tracemalloc.get_tracemalloc_memory(). Use a deep nframe only while investigating.
  • tracemalloc.take_snapshot() captures the allocations. snapshot.compare_to(old_snapshot, "lineno") returns the difference between two moments, sorted by growth. The valid key types are 'filename', 'lineno' and 'traceback'. Filter objects (snapshot.filter_traces) remove noise such as the importlib machinery.
  • get_traced_memory() returns (current, peak); reset_peak() resets the peak to the current size so that you can measure one phase.

What it cannot see: it traces memory that goes through Python's allocators. Memory a C library gets from plain malloc (a database driver, a tokenizer written in Rust, a model runtime) is not attributed to a Python line unless that library registers with tracemalloc's domain mechanism. If RSS grows and tracemalloc is flat, the growth is native, and you need a native-aware tool (8.5). It also slows the program (documented overhead grows with nframe), so use it in staging or on one canary worker.

The workflow is "baseline snapshot, run the suspect workload, second snapshot, diff". Part 9 does it end to end.

8.4 gc.get_objects, type censuses and get_referrers#

The gc module can enumerate every object the collector tracks. Two techniques cover most investigations:

  • A type census: Counter(type(o).__name__ for o in gc.get_objects()) before and after the workload shows which types grew, even when tracemalloc is unavailable.
  • gc.get_referrers(obj) returns the containers that refer to obj: who is holding it? The documentation warns that get_objects and get_referrers are debugging aids ("Avoid using get_objects() for any purpose other than debugging"); objects can be in an invalid state, they can be in a cycle awaiting collection (call gc.collect() first), and the calls are expensive on a large heap.
python
# e13_who_holds_it.py: type census before/after, then gc.get_referrers to find the holder
import gc
from collections import Counter

class Session:
    def __init__(self, user): self.user = user

REGISTRY: dict[str, Session] = {}      # a forgotten global

def login(user: str) -> None:
    REGISTRY[user] = Session(user)

def census() -> Counter:
    gc.collect()
    return Counter(type(o).__name__ for o in gc.get_objects())

before = census()
for i in range(500):
    login(f"user-{i}")
after = census()

print("census difference for our class:")
growth = {name: after[name] - before[name] for name in after}
for name in ("Session",):
    print(f"  {name}: +{growth.get(name, 0)}")

# take one leaked instance and ask who refers to it
victim = next(o for o in gc.get_objects() if isinstance(o, Session) and o.user == "user-7")
holders = [r for r in gc.get_referrers(victim) if r is not globals()]
for h in holders:
    kind = type(h).__name__
    print("held by a", kind, "of length", len(h) if hasattr(h, "__len__") else "?",
          "| is REGISTRY:", h is REGISTRY)
Output · Python 3.14.63 lines
census difference for our class:
  Session: +500
held by a dict of length 500 | is REGISTRY: True

The census says exactly 500 more Session objects exist after 500 logins; get_referrers on one of them returns a single holder, a dict of length 500, and h is REGISTRY confirms it is the module-level registry. "Who holds this object?" is the question a leak hunt turns on. (The third-party objgraph package wraps both techniques with graph drawing: objgraph.show_growth() and objgraph.show_backrefs(obj). It is awareness only.)

8.5 The toolbox#

Tool Kind What it gives you Notes
sys.getsizeof, recursive helpers Stdlib Size of one object, estimates Comparing designs only (1.5)
tracemalloc Stdlib Live Python allocations by line and by traceback; snapshot diffs; peak The default first tool; Python allocators only
sys.getallocatedblocks() Stdlib The number of memory blocks the interpreter currently holds, whatever their size The cheapest leak-trend metric; see the note after this table
gc (get_objects, get_referrers, get_stats, callbacks, DEBUG_SAVEALL) Stdlib Census, holders, cycle contents, GC timing Debugging aids
resource.getrusage, /proc/self/statm, /proc/self/smaps_rollup, ps Stdlib / OS RSS, peak RSS, USS/PSS (Linux) The numbers the operating system acts on
-X importtime, -X tracemalloc, PYTHONMALLOCSTATS, sys._debugmallocstats() Interpreter Import cost; startup tracing; pymalloc report CPython-specific
memray (Bloomberg) Third-party; awareness only, not run Records allocations including native code, with flame graphs, a live view and the ability to attach to a running process The best answer when tracemalloc is flat but RSS grows. Check the current release and platform support on PyPI before adopting
Scalene Third-party; awareness only CPU, memory and GPU profiling in one run, distinguishing Python from native time Check the project page for supported versions
py-spy Third-party; awareness only A sampling CPU profiler and stack dumper for a running process, without restarting it Not a memory profiler. Use it to answer "what is the process doing right now?" (a stuck thread, a hot loop), not "where did the memory go?"
objgraph, pympler Third-party; awareness only Object growth, back-reference graphs, class-level size summaries Useful in a REPL on a staging process
NumPy / pandas own accounting (ndarray.nbytes, DataFrame.memory_usage(deep=True)) Third-party The honest size of array data Not run here

sys.getallocatedblocks() is the cheapest trend metric the standard library offers. The documentation calls it "mainly useful for tracking and debugging memory leaks"; it counts blocks regardless of size, so it is a growth signal, not a byte count. Two caveats from the same entry: because of internal caches the result "can vary from call to call" (call gc.collect() first, and compare trends, not single values), and an implementation that cannot compute it is allowed to return 0. A growth check that needs no tools:

python
import sys

def growth_check(make, n=5):
    sys.getallocatedblocks()
    blocks, keep = [], []
    for _ in range(n):
        keep.append(make())                      # stand-in for one unit of work
        blocks.append(sys.getallocatedblocks())
    return blocks

b = growth_check(lambda: [object() for _ in range(10_000)])
print("blocks grow by at least 10,000 per step while we keep the lists:",
      all(b[i + 1] - b[i] >= 10_000 for i in range(len(b) - 1)))
Output · Python 3.14.61 line
blocks grow by at least 10,000 per step while we keep the lists: True

The same call, sampled periodically in a long-running service, gives a leak alarm that costs almost nothing, and you can follow it with tracemalloc only when the trend rises.

Allocator domains, briefly: CPython has three allocation domains, the raw domain (PyMem_RawMalloc, no interpreter state needed, used for large and low-level allocations), the mem domain (PyMem_Malloc, for general buffers) and the object domain (PyObject_Malloc, for Python objects, served by pymalloc). tracemalloc hooks them and reports by domain; that is why its numbers cover Python allocations and not memory a C library takes by calling the C malloc itself.

8.6 What this means for an AI engineer#

  • Decide the question first: "is the process big?" (RSS/PSS), "did Python code allocate this?" (tracemalloc), "who holds it?" (get_referrers), "is it native?" (memray). Each tool answers one.
  • Add two metrics to every long-running AI service: RSS (or the container total) and the gc pause time and count via gc.callbacks. The shape over days is the single most useful memory chart you can have.
  • Take a tracemalloc snapshot behind a debug endpoint or signal on one canary worker, not on all of them.
  • Do not use py-spy for memory questions, and do not trust getsizeof for capacity planning.

Part 9: A leak hunt, step by step#

Here is the workflow end to end on a leak you can reproduce exactly. The service is a fake support-ticket summarizer: each request builds a prompt, and someone added an "audit log" list during a debugging session and never removed it. Production symptom: memory climbs a little with every request and never comes back.

flowchart TD
    S["Memory keeps growing"] --> Q1{"Does it plateau after warm-up?"}
    Q1 -->|yes| W["Normal: caches, imports, arenas. Set the limit from the plateau"]
    Q1 -->|no| Q2{"Does tracemalloc current memory grow too?"}
    Q2 -->|no| N["Native memory or fragmentation: compare with PYTHONMALLOC=malloc, use memray"]
    Q2 -->|yes| Q3["Diff two snapshots by lineno: find the growing allocation site"]
    Q3 --> Q4["gc.get_referrers on a sample object: find the holder"]
    Q4 --> F["Fix: bound it, remove it, or make the reference weak"]
    F --> V["Verify: growth test shows zero retained bytes per call"]

9.1 Step 1: confirm it is growth, not warm-up#

Every process grows at the start: imports, caches, free lists, the first arenas. Throw the first few hundred requests away, then compare equal-sized rounds. Growth that continues at the same rate per request after warm-up is a leak or an unbounded structure; growth that flattens is not. This is why the script below warms up before it takes its baseline.

9.2 Step 2: find the growing allocation site with tracemalloc#

python
# e12_find_leak.py: a deterministic leak and the tracemalloc workflow that finds it
import gc
import os
import tracemalloc

# --- the "service": looks harmless, leaks one record per request -----------------
_audit_log: list[dict] = []          # the leak: grows forever (imagine a "debug" list nobody trims)

def build_prompt(ticket_id: int) -> str:
    return f"Summarise support ticket {ticket_id}: " + "details " * 50

def handle_request(ticket_id: int) -> int:
    prompt = build_prompt(ticket_id)                       # freed when the function returns
    _audit_log.append({"id": ticket_id, "prompt": prompt})  # kept: THIS is the leak
    return len(prompt)

# --- the investigation ---------------------------------------------------------
tracemalloc.start(10)                # keep up to 10 frames per allocation
for i in range(200):                 # warm up: caches, lazy imports, free lists
    handle_request(i)
gc.collect()
baseline = tracemalloc.take_snapshot()

for i in range(200, 1200):           # the workload we suspect
    handle_request(i)
gc.collect()
after = tracemalloc.take_snapshot()

here = os.path.basename(__file__)
mine = [tracemalloc.Filter(True, __file__)]
diff = after.filter_traces(mine).compare_to(baseline.filter_traces(mine), "lineno")
print("top growth by source line (this file only):")
for stat in diff[:3]:
    frame = stat.traceback[0]
    print(f"  {here}:{frame.lineno}  +{stat.size_diff / 1024:7.1f} KiB  +{stat.count_diff} blocks")

# who is holding them? ask for the full traceback of the biggest allocation site
top = after.filter_traces(mine).compare_to(baseline.filter_traces(mine), "traceback")[0]
print("allocation stack of the top growth (most recent call last):")
for line in top.traceback.format():
    if "File" in line:
        print("  ", line.strip().replace(__file__, here))

# and confirm with the objects themselves
print("dicts in the leaking list:", len(_audit_log))
print("fix: bound it ->", end=" ")
from collections import deque
_audit_log = deque(_audit_log, maxlen=100)
print("deque(maxlen=100) keeps", len(_audit_log))
Example output · illustrative10 lines
top growth by source line (this file only):
  e12_find_leak.py:10  +  460.2 KiB  +1000 blocks
  e12_find_leak.py:14  +  187.8 KiB  +2000 blocks
  e12_find_leak.py:24  +   29.5 KiB  +943 blocks
allocation stack of the top growth (most recent call last):
   File "e12_find_leak.py", line 25
   File "e12_find_leak.py", line 13
   File "e12_find_leak.py", line 10
dicts in the leaking list: 1200
fix: bound it -> deque(maxlen=100) keeps 100

How to read it:

  1. Growth by source line. Line 10 (the return f"Summarise ... " + "details " * 50, the prompt string) grew by about 460 KiB across 1000 blocks. Line 14 (the dict created for each audit record) grew by about 188 KiB. The unrelated line 24 is just the loop's integers. Notice that the biggest growth is the prompt string, not the line that stores it: tracemalloc reports where memory was allocated, and the string was allocated in build_prompt.
  2. The allocation stack for the top entry shows the call path (module line 25, handle_request on line 13, build_prompt on line 10). Allocation stacks tell you which request path produces the retained objects.
  3. Counting the container confirms it: len(_audit_log) is 1200, one entry per request.

9.3 Step 3: find the holder#

The retained thing is a string, so you must ask who still refers to it. Strings are not GC-tracked containers, so look from the other end: scan the containers (gc.get_objects) for ones that refer to your suspect type, or use gc.get_referrers on a sample object as shown in 8.4. In the scripts here the holder is a module-level list. In a real service it will be a registry, a cache, a task set, a logger handler or a closure; the table in 7.2 is the checklist.

9.4 Step 4: fix, then prove it#

The fix in the script is a one-liner (collections.deque(maxlen=100)); in a real service it might be removing the debug list entirely. But "it looks fixed" is not enough. Put a growth test next to the function. The helper below measures the net bytes retained per call after warm-up, and fails when the function holds on to memory:

python
# e19_growth_test.py: a reusable "does this function leak?" check you can put in a test suite
import gc
import tracemalloc
from collections.abc import Callable

def growth_per_call(fn: Callable[[], object], warmup: int = 50, rounds: int = 500) -> float:
    """Average net bytes retained per call after warm-up (0.0 means steady)."""
    for _ in range(warmup):
        fn()                                    # fill caches, intern strings, import lazily
    gc.collect()
    tracemalloc.start()
    before, _ = tracemalloc.get_traced_memory()
    for _ in range(rounds):
        fn()
    gc.collect()
    after, _ = tracemalloc.get_traced_memory()
    tracemalloc.stop()
    return (after - before) / rounds

REPEAT = 20                                      # a variable, so every call builds a NEW string object

_seen: list[str] = []
def leaky() -> None:
    _seen.append("ticket body " * REPEAT)       # retained forever

_window: list[str] = []
def bounded() -> None:
    _window.append("ticket body " * REPEAT)
    del _window[:-10]                            # keep only the last 10

def clean() -> None:
    len("ticket body " * REPEAT)

for name, fn in [("leaky", leaky), ("bounded", bounded), ("clean", clean)]:
    g = growth_per_call(fn)
    print(f"{name:<8} -> {'LEAK' if g > 50 else 'steady'}")
Output · Python 3.14.63 lines
leaky    -> LEAK
bounded  -> steady
clean    -> steady

leaky retains a new string per call and is flagged; bounded keeps a sliding window of ten (a constant, not growth) and clean retains nothing. Use this pattern as a regression test for hot paths (request handlers, message processors, tool executors). Three practical rules for it:

  • Always warm up, or the first calls (interning, imports, free lists) look like growth.
  • Run many rounds so a small per-call leak accumulates above noise; compare with a threshold (here 50 bytes per call), not with exactly zero.
  • Call gc.collect() before measuring so garbage cycles do not look like leaks. If the function creates cycles, that tells you something too: they cost collector time even when they are eventually freed.

9.5 The leak triage checklist#

  1. Plot RSS (or container memory) and GC pause counts over hours. Does it plateau?
  2. Reproduce with a script that loops the suspect request path, with warm-up, in one process.
  3. tracemalloc.start(10), baseline snapshot, workload, second snapshot, compare_to(..., "lineno"). Filter to your own code to remove noise.
  4. If the growth is a type of object, get_referrers on a sample finds the holder; check the gallery in 7.2.
  5. If tracemalloc is flat and RSS grows: native memory or fragmentation. Try PYTHONMALLOC=malloc to test the pymalloc hypothesis; use memray for native allocations.
  6. Fix with a bound (size, age, bytes), a finally/with that removes entries, or a weak reference.
  7. Add the growth test. Re-measure in staging under realistic load, then watch the production chart.

Part 10: Memory in AI workloads#

Deep-dive

10.1 Embeddings are the biggest single allocation#

The arithmetic is the first thing to know before you design an index. The table below is the calculation from the experiment's last block: it allocates nothing, it only multiplies. Each embedding has dim numbers; the bytes per number depend on the type.

python
# e15_jsonl.py: load-all vs stream-and-batch for a JSONL corpus (peak memory via tracemalloc)
import json
import tempfile
import tracemalloc
from itertools import islice
from pathlib import Path

def write_corpus(path: Path, n: int) -> None:
    with path.open("w", encoding="utf-8") as f:
        for i in range(n):
            rec = {"id": i, "title": f"Ticket {i}", "body": ("lorem ipsum " * 40).strip()}
            f.write(json.dumps(rec) + "\n")

def load_all(path: Path) -> int:
    rows = [json.loads(line) for line in path.open(encoding="utf-8")]
    return sum(len(r["body"]) for r in rows)

def stream_in_batches(path: Path, batch_size: int = 500) -> int:
    total = 0
    with path.open(encoding="utf-8") as f:
        while batch := list(islice(f, batch_size)):          # at most batch_size lines in memory
            for line in batch:
                total += len(json.loads(line)["body"])       # "embed the batch" would go here
    return total

def peak_mib(fn, *args) -> tuple[float, int]:
    tracemalloc.start()
    result = fn(*args)
    _, peak = tracemalloc.get_traced_memory()
    tracemalloc.stop()
    return peak / 2**20, result

with tempfile.TemporaryDirectory() as d:
    path = Path(d) / "corpus.jsonl"
    write_corpus(path, 20_000)
    print(f"file size: {path.stat().st_size / 2**20:.1f} MiB")
    p1, r1 = peak_mib(load_all, path)
    p2, r2 = peak_mib(stream_in_batches, path)
    print(f"load everything : peak {p1:6.2f} MiB")
    print(f"stream, batch 500: peak {p2:6.2f} MiB")
    print("same answer:", r1 == r2)
    print("streaming peak is at least 10x smaller:", p1 > 10 * p2)

print("--- embedding matrix arithmetic (no allocation) ---")
for n, dim in [(100_000, 1536), (1_000_000, 1536), (1_000_000, 768), (10_000_000, 1024)]:
    f32 = n * dim * 4 / 2**30
    f64 = n * dim * 8 / 2**30
    pylist = n * (dim * (8 + 24) + 56) / 2**30      # list of lists of Python floats: 8-byte pointer + 24-byte float each
    print(f"{n:>10,} x {dim:>4}: float32 {f32:7.2f} GiB | float64 {f64:7.2f} GiB | list of lists ~{pylist:8.1f} GiB")
Example output · illustrative10 lines
file size: 10.1 MiB
load everything : peak  17.88 MiB
stream, batch 500: peak   0.70 MiB
same answer: True
streaming peak is at least 10x smaller: True
--- embedding matrix arithmetic (no allocation) ---
   100,000 x 1536: float32    0.57 GiB | float64    1.14 GiB | list of lists ~     4.6 GiB
 1,000,000 x 1536: float32    5.72 GiB | float64   11.44 GiB | list of lists ~    45.8 GiB
 1,000,000 x  768: float32    2.86 GiB | float64    5.72 GiB | list of lists ~    22.9 GiB
10,000,000 x 1024: float32   38.15 GiB | float64   76.29 GiB | list of lists ~   305.7 GiB

Read the matrix table at the bottom:

Vectors × dimensions float32 float64 list of lists of Python floats
100,000 × 1536 0.57 GiB 1.14 GiB about 4.6 GiB
1,000,000 × 1536 5.72 GiB 11.44 GiB about 45.8 GiB
1,000,000 × 768 2.86 GiB 5.72 GiB about 22.9 GiB
10,000,000 × 1024 38.15 GiB 76.29 GiB about 305.7 GiB

(The list-of-lists column estimates 8 bytes for each pointer and 24 for each separate float object; it ignores allocator overhead, so reality is worse.)

  • The dtype is a factor of two, the representation a factor of four. Storing embeddings as NumPy float32 instead of float64 halves them; storing them in a contiguous buffer instead of a list of lists of Python floats divides them by about four again. "Why does my 1M-vector in-memory index need 46 GB?" has this answer. 01B.11 §2.3 explains why float32 is the right default; 06.4 §4.7 shows how scalar, binary and product quantization cut it further.
  • A memory-mapped file lets the OS hold one shared copy. mmap (or numpy.memmap) maps a file into the address space; pages are loaded on demand and shared between processes through the operating system's page cache. For read-only vectors served by four workers, the whole box needs about one copy (the last two lines of the e21 output later in this part). The mechanics are in 01C.7.
  • Vectors in a database or index service (a vector database, pgvector, a FAISS index) move the memory out of your Python heap into code that stores it compactly; your service then holds only query vectors and results.

10.2 Loading a big corpus: stream and batch#

The first part of the experiment compares two ways to process a 20,000-record JSONL file (about 10 MiB): load every record into a list, or stream it, holding at most one batch of 500 lines at a time. The answers are identical; the peak memory is not: about 18 MiB against 0.7 MiB, a factor of 25 for a small file. The ratio grows with the file: a 10 GiB file would need well over 10 GiB as a list of parsed dicts (parsed JSON is bigger than its text: 1.8 times here, more for records made of many small fields) and the same 0.7 MiB when streamed. The pattern, in full:

  • Read lazily (for line in f, itertools.islice for batches) and json.loads one line at a time.
  • Do the work per batch (embed 500, upsert 500, write 500), then let the batch go out of scope.
  • Hold the next stage back with backpressure: a bounded queue.Queue or asyncio.Queue(maxsize=N) between a fast reader and slow API calls, so that a producer cannot outrun its consumer and pile everything into the queue (01B.4 Part 3, 03.9 §4.9).
  • Checkpoint how far you have got so a restart does not re-read everything (06.2 §3.5).

10.3 Concurrency multiplies per-request memory#

An LLM gateway holds, for every in-flight request, a prompt, a growing response and the framework's own objects. A back-of-envelope budget makes the trade-off explicit:

python
# e21_capacity.py: a back-of-envelope memory budget for an LLM gateway worker (pure arithmetic)
from dataclasses import dataclass

@dataclass(frozen=True)
class Budget:
    base_mib: float                 # interpreter + imports + tokenizer + framework (measure with RSS at idle)
    per_request_kib: float          # prompt + response + framework objects while a request is in flight
    concurrency: int                # requests in flight per worker (your semaphore limit)
    cache_mib: float                # bounded caches (entries x size), a hard cap
    headroom: float = 0.25          # fragmentation, spikes, GC lag

    def peak_mib(self) -> float:
        working = self.base_mib + self.cache_mib + self.concurrency * self.per_request_kib / 1024
        return working * (1 + self.headroom)

# 40 KB prompt + 8 KB response, as UTF-8 text held in Python str and dicts (about 3x the raw bytes)
per_request = (40 + 8) * 3
for concurrency in (50, 200, 1000):
    b = Budget(base_mib=180, per_request_kib=per_request, concurrency=concurrency, cache_mib=256)
    print(f"concurrency {concurrency:>4}: plan for {b.peak_mib():7.0f} MiB per worker")

# the same with 4 workers on one machine, each loading a 1.5 GiB embedding matrix as ordinary objects
matrix_mib = 1536
print("4 workers, matrix copied into each:", 4 * matrix_mib, "MiB for the matrix alone")
print("4 workers, matrix memory-mapped and shared:", matrix_mib, "MiB (the OS page cache holds one copy)")
Output · Python 3.14.65 lines
concurrency   50: plan for     554 MiB per worker
concurrency  200: plan for     580 MiB per worker
concurrency 1000: plan for     721 MiB per worker
4 workers, matrix copied into each: 6144 MiB for the matrix alone
4 workers, matrix memory-mapped and shared: 1536 MiB (the OS page cache holds one copy)

Three conclusions:

  • Per-request memory is cheap, base memory and caches are not. Raising concurrency from 50 to 1,000 added only about 170 MiB because each request holds under 150 KiB. What dominates is the 180 MiB base plus the 256 MiB cache. This changes where you look first.
  • Always include the headroom. Fragmentation, GC lag and bursts are real (Part 4); a 25 percent buffer is a starting guess, not a measured value. Measure your own peak.
  • Copying a large object per worker multiplies it by the worker count. Four workers each holding a 1.5 GiB matrix as ordinary objects need 6 GiB; mapped from a file and shared, about 1.5 GiB. This is the same lesson as Part 5.

Where per-request memory actually grows is streaming responses and conversation state:

  • A streaming endpoint should forward chunks, not accumulate them. Collecting every chunk into a list "to log it later" doubles the memory held per request.
  • A conversation or agent loop that appends every tool output and model reply keeps growing for as long as it runs. Cap the history, summarize, or store it externally; keep ids in memory, not transcripts.
  • A per-process cache of "recent prompts and responses for debugging" is the leak of 7.2 in a lab coat. Bound it, or log it to disk.

10.4 Service-level practice#

Practice Why
Load models, tokenizers and indexes once at startup (FastAPI lifespan, 01B.7 §4.2), never per request A per-request load multiplies the largest allocation by concurrency
gc.freeze() after startup loading Smaller scans, fewer copy-on-write copies (3.6)
Keep large read-only data in buffers (array, mmap, NumPy) Few objects, shareable (5.3)
Bound every cache by entries, bytes and age 7.3
Recycle workers (max_requests with jitter) as a backstop Contains slow growth; see 4.7
Recycle stdlib pool workers with ProcessPoolExecutor(max_tasks_per_child=...) or Pool(maxtasksperchild=...) Same backstop without Gunicorn (4.7)
Run one-shot heavy jobs in a separate process Memory returns to the OS on exit
Export RSS, GC pause time and cache sizes as metrics The chart over days finds slow leaks (11A.1, 11A.2)
Set container limits from measured peak plus headroom; sum PSS, not RSS, for forked workers Avoids OOM kills and over-provisioning (8.1)

Deployment details (workers, containers, restart policy) are 11C.1 §5.2; this lesson supplies why those settings exist.

10.5 Free-threaded and sub-interpreter builds#

If you try the free-threaded interpreter (01C.5), expect these memory differences, all from the official free-threading guide (as of November 2026): the allocator is mimalloc rather than pymalloc; "the free-threaded build will typically use more memory compared to the default build"; interned strings become immortal "surviving until interpreter shutdown", so a service that interns unbounded user-supplied strings grows; and deferred and per-thread reference counts mean some objects are freed later, until gc.collect() merges the counts. Measure steady-state memory before you commit to it, and do not tune GC thresholds by copying advice for the default build.

10.6 What this means for an AI engineer#

  • Size embeddings with the arithmetic table before you choose an architecture; the factor between representations is larger than the factor between models.
  • Stream and batch everything that scales with the corpus; hold memory proportional to the batch, not the file.
  • Memory is an operational metric. Chart it, bound every structure, and test hot paths for growth.

Part 11: Checklists#

Reference

11.1 Design review: memory#

  • Is every long-lived structure (dict, list, set, cache, registry, history) bounded, with a rule for removing entries?
  • Do caches have a byte limit when values vary in size, and an age limit when data goes stale?
  • Are there lru_cache/cache decorators on methods, or with maxsize=None, in a long-lived process?
  • Are exceptions, frames, tracebacks or tasks stored anywhere long-lived? Are fire-and-forget tasks held until done?
  • Is anything built as a full list that a generator would serve?
  • Are large numeric datasets held as buffers (array, NumPy, mmap) rather than lists of objects? float32 where float64 is not needed?
  • Are millions of small uniform objects using slots=True (measured)?
  • Are models and indexes loaded once at startup, and is gc.freeze() called after loading?
  • For forked or multi-process workers: is the big data in a few buffers; is the limit sized from PSS or the container total?
  • Is cleanup done with with, weakref.finalize or atexit, never __del__?
  • Are mutable default arguments and class-level mutable attributes absent?
  • Is there a growth test, and are RSS and GC pauses on a dashboard?
Symptom Cause Fix
Container killed at 4 GB when the data is 600 MB Per-record Python objects (dict per chunk) plus fragmentation Columnar or slots=True; stream; measure with tracemalloc (6.1, 10.2)
RSS stays high after the import finished Arena fragmentation; lazy return to the OS Compact survivors; run the job in a subprocess; recycle workers (4.4, 4.7)
Memory grows with every request Unbounded cache, list or dict; stored exceptions; lru_cache on a method Bound it; maxsize; module-level cached function (7.2, 7.3)
Latency spikes every few minutes A full GC scanning millions of live objects gc.freeze() after load; fewer, larger objects; gc.callbacks to confirm (3.3)
Memory keeps climbing after someone ran gc.disable() Cycles are never freed Re-enable; fix the cycles (3.6, 3.7)
Four workers use four times the memory of one Copy-on-write defeated by refcounts and GC writes Buffers, mmap, shared memory; gc.freeze(); sum PSS (5.2, 5.3)
A background task "just stopped" Only a weak reference was held Keep a strong reference until done (7.2)
__del__ never ran, or ran at a bad time, or raised silently Finalizers are not a cleanup mechanism with, weakref.finalize, atexit (3.5)
if x is 1000: works in tests, fails in production The small-int cache is a CPython detail Use == (2.5)
getsizeof(big) says kilobytes but memory is gigabytes getsizeof is shallow tracemalloc; recursive helper; PSS (1.5)
A weak-value "cache" never hits Entries vanish as soon as nothing else holds them Use a bounded LRU (2.6)
BufferError when resizing a bytearray A live memoryview pins it Release views (6.4)
Memory grows, tracemalloc is flat Native allocations memray; compare allocators (8.3, 8.5)

Common misconceptions#

Misconception Reality
"b = a copies the list." It adds a second name to the same object. Copies are explicit (list(a), copy.copy, copy.deepcopy) (1.3)
"sys.getsizeof tells me how much memory my data uses." It measures one object, not what it refers to; a list of three 1000-character strings reports 88 bytes for 3,211 (1.5)
"Python has a garbage collector, so reference counting doesn't matter." Reference counting frees almost everything, immediately. The cyclic collector is a second mechanism for cycles (Part 2, Part 3)
"a is b is a faster ==." is is identity. It only seems to work for small ints and interned strings, which are CPython implementation details that have changed between versions (2.5)
"Immortal objects mean my data is shared between forked workers." Only a few runtime objects (None, True, small ints, static types) are immortal. Your lists and dicts are ordinary and are copied as they are touched (2.4, 5.2)
"__del__ is Python's destructor; put cleanup there." It may run late, run in the middle of a cycle collection, swallow its exceptions, or never run at exit. Use with, weakref.finalize or atexit (3.5)
"Python 3.14 has an incremental garbage collector." Python 3.14.0 to 3.14.4 did; 3.14.5 reverted to the generational collector from 3.13 after reports of memory pressure in production (3.4)
"Disabling the GC speeds things up safely." Reference counting still works, but every cycle leaks. It is justified only for short phases you know are acyclic (3.6)
"If RSS doesn't drop, I have a leak." Fragmentation, lazy return to the OS and high-water marks all keep RSS high without any leak (4.5)
"Freeing 99.9 percent of my objects frees 99.9 percent of the memory." One surviving object pins its whole 1 MiB arena; in the experiment 95 arenas stayed allocated (4.4)
"Fork gives me N workers for the price of one." Only until they read the data: refcount writes and the collector copy pages. Store shared data in buffers (Part 5)
"__slots__ always halves memory." It saved about 26 percent here against a plain class on 3.14; measure first. The big wins are columns and array (6.1, 6.2)
"A generator is always cheaper than a list." For one pass, yes. If you need several passes or random access, a generator makes you recompute, and a suspended one holds its locals alive (6.3)
"lru_cache is safe to put on any function." On a method its key includes self, so instances live until evicted; maxsize=None never evicts (7.2)
"asyncio.create_task(...) keeps the task alive." The event loop holds only a weak reference; keep your own until it finishes (7.2)
"tracemalloc shows who is holding my memory." It shows where memory was allocated. Use gc.get_referrers to find the holder (8.4)
"py-spy is a memory profiler." It is a sampling CPU profiler and stack dumper. Use tracemalloc or memray for memory (8.5)
"Summing per-process RSS gives the memory of my workers." Shared pages are counted in every process that maps them. Use PSS or the container total (8.1)

Key takeaways#

  • A Python name is a label on an object; assignment and argument passing copy the label, never the object. Every object has a header (a reference count and a type pointer, 16 bytes on a 64-bit build), and containers hold references, so small records cost far more than their payload.
  • sys.getsizeof is shallow. Use it to compare designs; use tracemalloc and OS numbers for real accounting.
  • Reference counting frees most objects the instant their last reference disappears (in CPython; a detail, not a language promise). with blocks, not "going out of scope", are how you release resources portably.
  • Immortal objects (3.12) have fixed refcounts so None, True, small ints and static types are never written to; that helps sub-interpreters and copy-on-write but covers only a few objects.
  • Never compare values with is: the small-int cache and interning are CPython details (the cached range is -5 to 256 on 3.14 and 1024 in the newest documentation). sys.intern pays only for many repeated, separately built strings.
  • Weak references let you refer without owning: back-pointers, deduplicating registries (WeakValueDictionary) and cleanup (weakref.finalize). They are not a bounded cache.
  • The cyclic collector frees unreachable cycles. It scans tracked containers by generation (default thresholds (2000, 10, 10) on 3.14.6) and its cost grows with live container objects, which shows up as pauses. Python 3.14.0 to 3.14.4 used an incremental collector; 3.14.5 reverted to the generational one. Check your patch release.
  • gc.freeze() after startup loading removes your big read-only data from scans and from copy-on-write damage by the collector; gc.callbacks measures pauses; gc.disable() risks unbounded cycle growth.
  • __del__ is not cleanup. PEP 442 made cycles with finalizers collectable and finalizers run once, but timing, exceptions and exit-time behaviour remain unreliable.
  • pymalloc serves objects up to 512 bytes from 16-byte-step size classes in 16 KiB pools inside 1 MiB arenas (on this build); larger objects go to malloc. An arena returns to the OS only when completely empty, so fragmentation keeps RSS high: copy survivors into compact objects, run batch work in a subprocess, recycle workers.
  • RSS is a high-water mark that hides sharing; judge memory with tracemalloc (Python allocations), PSS (fleets of workers) and the container total.
  • After fork, reading Python objects copies pages (refcounts and GC headers are written); keep big shared data in buffers (array, bytes, mmap, NumPy). Since 3.14 the default multiprocessing start method on Linux and other POSIX systems except macOS (which uses spawn) is forkserver, not fork.
  • Shrink data in order: fewer objects (columns, array), then smaller objects (slots=True), then lazier structures (generators, memoryview). Wide characters make a whole string 2 or 4 bytes per character.
  • A Python "leak" is memory that is still reachable: unbounded caches, lru_cache on methods, global registries, stored exceptions with frames, tasks without a holder, mutable defaults. Bound every long-lived structure by entries, bytes and age.
  • Find leaks by confirming growth after warm-up, diffing tracemalloc snapshots, finding the holder with gc.get_referrers, fixing, and adding a growth test.
  • For AI work: size embeddings with the arithmetic (float32, buffers, memory-mapped files), stream and batch corpora, budget concurrency times per-request memory, load models once, and treat RSS and GC pause time as metrics.

Where you'll use this in the AI path#

Where What it applies
01B.11 §2.3 dtype: why embeddings are float32 and §5.15 Performance and memory Contiguous buffers instead of lists of objects (6.2, 10.1)
01B.4 Part 3 worker pools and queues and §5.2 count-based batching Bounded queues and batches as memory control (10.2)
03.9 §4.9 A worker pool for inputs that don't fit in memory The streaming pattern at scale
05.9 §8.3 Timeouts, memory limits and resumability Memory limits in ingestion pipelines
06.2 §3.5 Progress, checkpoints and resumability Checkpointing batch jobs so a memory kill does not lose the run
06.4 §4.7 Compression ratios and index memory What quantization does to the arithmetic in 10.1
11B.3 §3.4 Backends: memory, SQLite, diskcache, Redis Where a bounded cache should live
11C.1 §5.2 Workers vs processes vs async Why per-worker memory and recycling settings matter
11A.1 Tracing and observability and 11A.2 Metrics, SLOs and alerting Exporting RSS and GC-pause metrics (8.6)
01B.7 FastAPI lifespan and app.state Loading models once at startup (10.4)
Next in this module: 01C.7 Shared Memory and Inter-Process Communication Sharing large data between processes on purpose: shared_memory, mmap, zero-copy
Earlier in this module: 01C.3 Race conditions and thread safety, 01C.5 The GIL Thread-safe caches (7.3); why refcounting and the GIL are linked (2.7)

Terms introduced in this lesson#

Term One-line definition
Name / reference A label that points at an object; binding, list slots, attributes and closures are all references
Object header The fixed start of every object: reference count and type pointer (16 bytes on 64-bit CPython)
Identity (id, is) Whether two names refer to the same object (not whether they are equal)
Shallow vs deep copy Duplicate the container only, versus the container and everything inside it
sys.getsizeof The size of one object, excluding what it refers to
Reference counting Freeing an object the moment its count of references reaches zero
Py_INCREF / Py_DECREF The C-level operations that add and remove a reference
Immortal object An object with a fixed reference count that is never freed or written to (3.12, PEP 683)
Small-integer cache CPython's pre-built int objects for a small range (-5 to 256 on 3.14.6), an implementation detail
Interning (sys.intern) Keeping one canonical copy of equal strings so they share an object
Weak reference A reference that does not keep its target alive and returns None once it is gone
weakref.finalize A cleanup callback tied to an object's collection, safer than __del__
Reference cycle Objects that refer to each other so counts never reach zero
Cyclic garbage collector The gc mechanism that finds and frees unreachable cycles among container objects
Generation A group of tracked objects collected at a given frequency (young survivors move to older generations)
Incremental GC A collector that scans the old generation in slices; shipped in 3.14.0 to 3.14.4 and reverted in 3.14.5
gc.freeze / permanent generation Moving all tracked objects out of collection scans (useful before fork)
Finalizer (__del__) Code run when an object is destroyed; unreliable for cleanup
PEP 442 Python 3.4 change letting cycles with __del__ be collected and finalizers run once
Resurrection A finalizer that makes its own object reachable again
pymalloc CPython's allocator for objects up to 512 bytes: blocks, pools, arenas
Arena / pool / block pymalloc's 1 MiB region / 16 KiB page-like unit for one size class / the allocation unit (16 to 512 bytes) on this build
Fragmentation Free memory scattered between live objects so it cannot be returned or reused for other sizes
PYTHONMALLOC Environment variable that selects the allocator (pymalloc, malloc, mimalloc, debug variants)
mimalloc The allocator used by the free-threaded build (optional in the default build, 3.13+)
Copy-on-write (CoW) Sharing memory pages until one process writes to a page, which is then copied
RSS / VMS / USS / PSS Resident, virtual, unique and proportional memory measures of a process
tracemalloc Standard-library tracer recording where Python allocated live memory; supports snapshot diffs
Memory leak (Python sense) Memory that is still reachable but no longer useful
__slots__ Declaring fixed attribute slots so instances have no __dict__
Columnar layout Storing each field as one packed array instead of one object per record
memoryview A zero-copy view of another object's buffer
Bounded cache A cache with explicit limits on entries, bytes and age
Growth test A test that measures net memory retained per call after warm-up

All terms are also collected in the glossary.


Exercises#

All solutions were run on Python 3.14.6 (GIL-enabled build); the scripts are saved with the lesson's working files. Where an exercise prints a number that depends on the build, the solution prints a yes/no check instead.

  1. Predict the counts (2.2). Run the code below in your head first. What do the four lines print? Then run it and explain each difference.

    python
    import sys
    
    x = []
    print("1:", sys.getrefcount(x))
    y = x
    holder = {"k": x}
    print("2:", sys.getrefcount(x))
    del holder
    print("3:", sys.getrefcount(x))
    y = None
    print("4:", sys.getrefcount(x))
  2. Alias or rebind? (1.3) Given x = [1]; y = x, what do x += [2] and x = x + [3] each do to y? What happens with a tuple?

  3. Break a cycle (3.7). A Node keeps a list of children and each child keeps a parent attribute. Rewrite it so that dropping the root frees the whole tree by reference counting alone, even with the cyclic collector disabled.

  4. Share, do not cache (2.6). A function parses a contract document by id. Make sure two callers that hold the same document at the same time get the same object, without keeping documents alive after nobody uses them. Count how many times parsing runs.

  5. Choose a layout (6.2). You will hold 5 million (chunk_id, token_count) pairs in memory for a statistics job. Using the per-record figures from the e09 experiment, estimate the memory of a dict per record, a slotted instance, and two array.array("q") columns. Which would you pick, and what would make you change your mind?

  6. Fix a method cache (7.2). Embedder.embed is decorated with @functools.lru_cache(maxsize=None). Explain what leaks and rewrite it so instances can be freed and the cache is bounded.

  7. Keep the message, not the traceback (7.2). A retry loop stores last_error = exc between attempts and the failing function has a large local. Show that the local stays alive, then fix it.

  8. Stream a file (10.2). Count the words in a 200,000-line text file two ways (read everything, read line by line). Verify that the answers match and that the streaming version uses far less memory.

  9. Watch the collector (3.3). Use gc.callbacks to count automatic collections per generation during a burst of allocations. Which generation is collected most often, and why?

  10. Budget the matrix (10.1). How many GiB do 2.5 million 1024-dimension embeddings need as float64, float32, float16 and int8, and as a list of lists of Python floats?

  11. Find the holder (8.4, 9.3). In the leak-hunt output, the biggest growth was attributed to build_prompt, a function that returns its string and keeps nothing. Explain why that is not a contradiction, and name the step that finds the real holder.

  12. Size a worker fleet (5.3, 8.1). A host has 16 GiB. Each of 8 workers is forked after the parent loads a 1.5 GiB embedding matrix. The matrix is held (a) as a list of lists of Python floats, and (b) as one float32 buffer from a memory-mapped file. Roughly how much memory does each design need for the matrix, and what should you read from the system to check?

Solution

1. The four lines are 2, 4, 3 and 2.

Output4 lines
1: 2
2: 4
3: 3
4: 2

The base count is 2 because getrefcount itself holds a temporary reference. y = x adds one and the dict value adds one (line 2 is 4); del holder frees the dict, taking its reference with it (3); rebinding y removes the last extra one (back to 2). Remember that exact values are an implementation detail and have changed between versions; compare differences, not absolutes.

2. x += [2] calls list.__iadd__, which extends the same list, so y sees the change. x = x + [3] builds a new list and rebinds only x. A tuple is immutable: t += (2,) rebinds t to a new tuple and u keeps the old one.

python
# ex02_alias.py: += on a list mutates in place; + builds a new list
x = [1]
y = x
x += [2]          # list.__iadd__: extends the SAME object
print("after x += [2]:  x =", x, " y =", y, " same object:", x is y)
x = x + [3]       # builds a NEW list and rebinds only the name x
print("after x = x+[3]: x =", x, " y =", y, " same object:", x is y)

t = (1,)
u = t
t += (2,)         # tuples are immutable: += rebinds t to a new tuple
print("tuple:", t, u, "same object:", t is u)
Output3 lines
after x += [2]:  x = [1, 2]  y = [1, 2]  same object: True
after x = x+[3]: x = [1, 2, 3]  y = [1, 2]  same object: False
tuple: (1, 2) (1,) same object: False

3. Make the back-reference weak: the child holds a weakref.ref to its parent, exposed through a property. The parent owns the children (strong), the children do not own the parent. With gc.disable() the tree is still freed by counting alone.

python
# ex03_cycle_weak.py: a parent/child tree that frees by reference counting alone
import gc
import weakref

class Node:
    def __init__(self, name, parent=None):
        self.name = name
        self.children: list["Node"] = []
        # a weak back-reference: the child does not keep its parent alive
        self._parent = weakref.ref(parent) if parent is not None else None
        if parent is not None:
            parent.children.append(self)
    @property
    def parent(self):
        return self._parent() if self._parent is not None else None

gc.disable()          # prove that reference counting alone frees it
gc.collect()
root = Node("root")
Node("a", root); Node("b", root)
probe = weakref.ref(root)
child = root.children[0]
print("child.parent is root:", child.parent is root)
del root, child
print("root freed without the cycle collector:", probe() is None)
gc.enable()
Output2 lines
child.parent is root: True
root freed without the cycle collector: True

4. Use a WeakValueDictionary keyed by id. While any caller holds the document, a second lookup returns the same object (parse count stays at 1); when everyone lets go the entry vanishes and the next call parses again (count 2). If you want documents to stay cached, you need a bounded LRU instead (7.3).

python
# ex04_weak_cache.py: share one parsed Document per id while anyone uses it
import weakref

class Document:
    parsed = 0
    def __init__(self, doc_id: str) -> None:
        self.doc_id = doc_id
        Document.parsed += 1                    # count how often we "parse"

_live: weakref.WeakValueDictionary[str, Document] = weakref.WeakValueDictionary()

def get_document(doc_id: str) -> Document:
    doc = _live.get(doc_id)
    if doc is None:
        doc = Document(doc_id)
        _live[doc_id] = doc
    return doc

a = get_document("contract-17")
b = get_document("contract-17")
print("same object while alive:", a is b, "| parsed:", Document.parsed)
del a, b
c = get_document("contract-17")
print("after everyone let go, parsed again:", Document.parsed)
Output2 lines
same object while alive: True | parsed: 1
after everyone let go, parsed again: 2

5. From the experiment: dict about 248 bytes per record, slotted instance about 112, two array("q") columns about 16 (for two 8-byte numbers). For 5,000,000 records that is roughly 1.2 GB, 0.5 GB and 80 MB. Pick the columns: the job scans numbers, so nothing needs to be an object. Change your mind if you need per-record behaviour (methods), random insertion and deletion, or fields of mixed types; then a slots=True dataclass is the reasonable compromise. Always re-measure with tracemalloc on your own build, because __slots__ savings shifted between Python versions.

6. The cache lives on the class, is unbounded and includes self in its key, so every Embedder that ever called embed stays alive. Cache a module-level function keyed on the text, with a maxsize; the method delegates to it.

python
# ex06_method_cache.py: cache on the data, not on self
import functools
import gc
import weakref

@functools.lru_cache(maxsize=256)
def _embed_text(text: str) -> tuple[float, ...]:      # module-level: keys are strings, not instances
    return (float(len(text)),)

class Embedder:
    def embed(self, text: str) -> tuple[float, ...]:
        return _embed_text(text)

e = Embedder()
probe = weakref.ref(e)
e.embed("hello")
del e
gc.collect()
print("Embedder instance freed:", probe() is None)
print("cache still bounded:", _embed_text.cache_info().maxsize)
Output2 lines
Embedder instance freed: True
cache still bounded: 256

7. A stored exception keeps its traceback, whose frame holds the large local. Store repr(exc) (or str(exc)), or set exc.__traceback__ = None, and the local can be freed.

python
# ex08_exception.py: keeping the message, not the traceback
import gc
import weakref

class Matrix:
    pass

def risky(probe_holder: list) -> None:
    big = Matrix()
    probe_holder.append(weakref.ref(big))
    raise ValueError("embedding failed")

def run(keep_exception: bool) -> bool:
    holder: list = []
    saved = None
    try:
        risky(holder)
    except ValueError as exc:
        saved = exc if keep_exception else repr(exc)    # the fix: keep text only
    gc.collect()
    alive = holder[0]() is not None
    return alive

print("storing the exception keeps the big local alive:", run(True))
print("storing repr(exc) lets it go:", run(False) is False)
Output2 lines
storing the exception keeps the big local alive: True
storing repr(exc) lets it go: True

8. The streaming version holds one line at a time; read_text().splitlines() holds the whole text and the list of lines.

python
# ex09_stream.py: count words in a big file without loading it
import tempfile
import tracemalloc
from pathlib import Path

def count_words_slurp(path: Path) -> int:
    return sum(len(line.split()) for line in path.read_text().splitlines())

def count_words_stream(path: Path) -> int:
    total = 0
    with path.open(encoding="utf-8") as f:
        for line in f:                          # one line at a time
            total += len(line.split())
    return total

def peak(fn, *a) -> tuple[int, int]:
    tracemalloc.start()
    result = fn(*a)
    _, p = tracemalloc.get_traced_memory()
    tracemalloc.stop()
    return p, result

with tempfile.TemporaryDirectory() as d:
    path = Path(d) / "big.txt"
    path.write_text("the quick brown fox jumps over the lazy dog\n" * 200_000, encoding="utf-8")
    p1, r1 = peak(count_words_slurp, path)
    p2, r2 = peak(count_words_stream, path)
    print("same answer:", r1 == r2, r1)
    print("streaming uses far less memory:", p2 * 20 < p1)
Output2 lines
same answer: True 1800000
streaming uses far less memory: True

9. Generation 0 is collected most often because it is triggered by the allocation counter, while older generations are only examined after the younger ones have been collected several times (the threshold1 and threshold2 multipliers). The script prints yes/no checks because exact counts depend on the build and on what else allocated.

python
# ex10_gc_watch.py: count automatic collections by generation during a workload
import gc
from collections import Counter

counts: Counter[int] = Counter()
def on_gc(phase: str, info: dict) -> None:
    if phase == "stop":
        counts[info["generation"]] += 1

gc.callbacks.append(on_gc)
try:
    junk = [[i] for i in range(500_000)]       # a burst of tracked allocations
    del junk
finally:
    gc.callbacks.remove(on_gc)

print("young collections happened:", counts[0] > 0)
print("young collections outnumber full ones:", counts[0] > counts[2])
print("generations seen:", sorted(counts))
Output3 lines
young collections happened: True
young collections outnumber full ones: True
generations seen: [0, 1, 2]

10. The arithmetic is n * dim * bytes_per_number / 2**30. The list-of-lists figure assumes 8 bytes per pointer plus 24 per float object, so 32 bytes per number.

python
# ex11_budget.py: memory for 2.5 million 1024-dimension embeddings
n, dim = 2_500_000, 1024
for name, size in [("float64", 8), ("float32", 4), ("float16", 2), ("int8", 1)]:
    print(f"{name:>8}: {n * dim * size / 2**30:6.2f} GiB")
print("list of lists of Python floats (approx):", f"{n * (dim * 32 + 56) / 2**30:.0f} GiB")
Output5 lines
 float64:  19.07 GiB
 float32:   9.54 GiB
 float16:   4.77 GiB
    int8:   2.38 GiB
list of lists of Python floats (approx): 76 GiB

Quantizing to int8 is a factor of eight below float64; representing as Python floats is a factor of about four above float64. Accuracy loss from float16 and int8 must be evaluated on your retrieval metrics, not assumed (06.4 §4.7).

11. tracemalloc reports where each live block was allocated. The prompt string was created inside build_prompt, so the line that built it owns the allocation, even though the reference that keeps it alive sits in the module-level _audit_log. A function returning an object does not hold it; whoever stored it does. To find the holder, use gc.get_referrers on a sample object, a type census, or read the allocation stack of the top growth entry and look at what the caller does with the result (8.4, 9.3).

12. The matrix is 1.5 GiB as float32 (4 bytes per number). (a) As Python floats in lists, each stored number costs about 32 bytes (an 8-byte pointer plus a 24-byte float object), eight times more: about 12 GiB per copy. Because the numbers are Python objects, each worker copies pages as it reads them (refcount writes), so in the worst case eight workers need about 96 GiB, far beyond the 16 GiB host. (b) One float32 buffer from a memory-mapped file is 1.5 GiB in the operating system's page cache, shared by all eight workers: about 1.5 GiB total. To check, compare PSS per worker (Linux smaps_rollup) or the container total, and the host's free memory, not summed RSS (8.1). On 3.14 the default start method is forkserver, so each worker would map the file itself, which is exactly the design that needs no inherited objects.


Check yourself#

  1. What does b = a do for a list, and how do you make an independent copy?
  2. Why does sys.getsizeof([big_string, big_string, big_string]) return a small number, and what do you use instead for real accounting?
  3. What does sys.getrefcount(x) return for an object held by one name, and why does the documentation say not to rely on exact values?
  4. Which objects are immortal in Python 3.12 and later, and what two problems did that solve?
  5. Why is a is b unreliable for integers and strings, and what should you use?
  6. What is the difference between weakref.ref, WeakValueDictionary and weakref.finalize, and why is a weak dictionary not a cache?
  7. Give two ways a reference cycle arises without anyone writing a.other = b; b.other = a. How do you avoid each?
  8. What does the cyclic collector scan, what triggers a collection, and why can it cause latency spikes in a service with a large in-memory corpus?
  9. What happened to the incremental garbage collector in Python 3.14, and how can you tell which behaviour you have?
  10. Name three reasons __del__ is the wrong place for resource cleanup, and three better tools.
  11. What are pymalloc's arenas, pools and blocks, and why can freeing 99.9 percent of your objects leave the process's RSS almost unchanged?
  12. Why does reading Python objects in a forked child copy memory, and what can you do about it?
  13. List four ways a Python program retains memory by accident, and the fix for each.
  14. When does tracemalloc not help, and what do you reach for next? What is py-spy for?
  15. You must serve a 1,000,000 by 1536 embedding matrix to four workers on one machine. What representation do you use, and how much memory should you plan for?

Further resources#


← 01C.5: The Global Interpreter Lock (GIL) | Module 01C overview | 01C.7: Shared Memory and Inter-Process Communication →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close