Skip to content

Lesson 3 of 9 · 23m

Memory Profiling: Where the Bytes Actually Live

RSS is not object size, leaks are usually caches, and Python's allocator makes small objects stranger than they look. Measure memory growth before rewriting anything.

The first memory investigation usually starts with top, a rising RSS number, and someone saying "we have a leak." Sometimes. More often the application is faithfully retaining exactly what the code asked it to retain: an unbounded cache, rows kept after iteration, debug payloads attached to exceptions, or a million tiny objects with terrible overhead.

Memory optimization begins by separating three questions: how much is resident, what objects exist, and which allocation sites keep growing.

RSS is the bill, not the itemized receipt

Resident set size includes the interpreter, shared libraries, allocator arenas, fragmentation, native extension buffers, and Python objects. Freeing an object does not guarantee RSS drops because CPython's allocator retains arenas for reuse. A service can be stable at 800 MB even though live data is only 200 MB.

This is why "memory went down after my patch" needs evidence. Watch the process across restarts and traffic cycles, not just immediately after a GC.

Use tracemalloc for allocation sites

import tracemalloc
tracemalloc.start(25)
run_import()
current, peak = tracemalloc.get_traced_memory()
print(f"current={current / 1024**2:.1f} MiB peak={peak / 1024**2:.1f} MiB")
for stat in tracemalloc.take_snapshot().statistics("lineno")[:12]:
    print(stat)

For growth, take snapshots at stable points — for example after each batch — and compare them:

before = tracemalloc.take_snapshot()
process_batch(batch)
after = tracemalloc.take_snapshot()
for stat in after.compare_to(before, "lineno")[:10]:
    print(stat)

tracemalloc shows Python allocations by traceback. It will not fully explain large buffers allocated inside native code, which is why NumPy-heavy services can look calm in tracemalloc while RSS climbs.

Object counts answer a different question

objgraph is useful when you suspect retained object graphs rather than large buffers:

import objgraph
objgraph.show_most_common_types(limit=15)
objgraph.show_growth(limit=15)
objgraph.show_backrefs(objgraph.by_type("InvoiceRow")[:1], max_depth=6)

The pattern that hurts in production is usually mundane: a class-level cache keyed by mutable input, a listener registry that never unsubscribes, or a "temporary" list appended for observability and never cleared.

Reduce memory with shape, not hope

  • Stream records instead of materializing lists.
  • Store numeric columns in NumPy arrays or Arrow tables instead of Python objects.
  • Use __slots__ only when instance count is huge and inheritance constraints are understood.
  • Bound caches explicitly with functools.lru_cache(maxsize=...) or your own eviction policy.
  • Prefer compact scalar types; a Python int is an object, not a machine word.

Field notes

  • sys.getsizeof is shallow. A small list can own megabytes of children.
  • Calling gc.collect() in production to hide a leak trades memory for latency spikes. Fix ownership instead.
  • Copy-on-write after fork can make multiprocessing memory look cheap until children start mutating shared pages.
  • Memory regressions deserve the same before/after evidence as CPU regressions: same input, same traffic, same process lifetime.

Was this lesson helpful?

Sign in to rate