Python has automatic reference counting and a cyclic garbage collector, so it is easy to assume memory leaks only happen in C extensions. In reality, long-running Python workers—FastAPI servers, Celery consumers, WebSocket hubs—still OOM-kill in production every week.

Almost all of those leaks come from unintended strong references that keep short-lived objects alive forever. Even worse, they rarely show up during unit tests because a single test creates one object and exits.

In this post, we will reproduce two of the most common Python memory leaks in a zero-dependency Python 3.12 lab, measure them with tracemalloc, fix both cleanly, and lock the fixes down with automated pytest memory-growth assertions.

Complete runnable repository (Python 3.12 stdlib + pytest): https://github.com/ruiheng903-ux/python-memory-leak-lab

Leak #1: Putting @functools.lru_cache on an Instance Method

This looks completely innocent during code review:

from functools import lru_cache class LeakySessionProcessor: def __init__(self, session_id: str, payload_kb: int = 64) -> None: self.session_id = session_id self._buffer = bytearray(payload_kb * 1024) @lru_cache(maxsize=1024) def compute_score(self, factor: int) -> int: return (len(self._buffer) // 1024) * factor 

Why It Leaks

@lru_cache attaches a single cache dictionary to the function object on the class, not to each instance. Because compute_score is a method, its first argument is self. Every time a new LeakySessionProcessor calls compute_score(3), the cache key (self, 3) stores a strong reference to self—which pins the entire instance and its 64 KB _buffer in memory until evicted.

Over 500 short-lived sessions, all 500 instances stay pinned in RAM (31.41 MB retained), even after every caller drops its reference and gc.collect() runs.

The Fix: Cache Primitive Inputs in a Pure Helper

Instead of caching on self, move @lru_cache to a module-level pure function keyed only on lightweight primitive values:

@lru_cache(maxsize=1024) def _compute_score_pure(buffer_kb: int, factor: int) -> int: return buffer_kb * factor class FixedSessionProcessor: def __init__(self, session_id: str, payload_kb: int = 64) -> None: self.session_id = session_id self._buffer = bytearray(payload_kb * 1024) def compute_score(self, factor: int) -> int: return _compute_score_pure(len(self._buffer) // 1024, factor) 

Now the cache only holds (64, 3) -> 192. As soon as a FixedSessionProcessor goes out of scope, Python's reference counter frees its 64 KB buffer immediately.

Leak #2: Global Event Buses Holding Bound Methods

Another classic production leak shows up in pub/sub dispatchers, WebSocket managers, and plugin registries:

class LeakyEventBus: def __init__(self) -> None: self._listeners: list[Callable[[str], None]] = [] def subscribe(self, callback: Callable[[str], None]) -> None: self._listeners.append(callback) 

When a short-lived worker registers bus.subscribe(self.on_event), Python creates a bound method object that holds a strong reference back to self. If the worker exits without calling unsubscribe() (for example, due to an early return or unhandled exception), the global bus keeps the dead worker—and all of its buffers—alive forever.

The Fix: weakref.WeakMethod with Lazy Pruning

Python's standard library provides weakref.WeakMethod specifically for bound methods. Calling ref() returns the bound method if the owner instance is still alive, or None once the owner has been garbage-collected:

import weakref from typing import Callable class WeakEventBus: def __init__(self) -> None: self._listeners: list[weakref.WeakMethod[Callable[[str], None]]] = [] def subscribe(self, callback: Callable[[str], None]) -> None: self._listeners.append(weakref.WeakMethod(callback)) def publish(self, event: str) -> int: alive: list[weakref.WeakMethod[Callable[[str], None]]] = [] delivered = 0 for ref in self._listeners: cb = ref() if cb is not None: cb(event) alive.append(ref) delivered += 1 self._listeners = alive return delivered 

Dead subscribers are automatically collected when callers drop them, and their stale weak references are pruned on the next publish cycle.

Verified tracemalloc Benchmark Results

Running python benchmark_leaks.py creates 500 short-lived objects (each holding a 64 KB bytearray), forces gc.collect(), and measures retained and peak heap allocations with tracemalloc:

=== Memory Leak Benchmark (500 short-lived objects x 64 KB) === Scenario Retained (MB) Peak (MB) Pinned Objects ---------------------------------------------------------------------------------- 1a. @lru_cache on method (Leaky) 31.41 31.49 500 1b. Pure-function cache (Fixed) 0.00 0.08 0 2a. Strong-ref EventBus (Leaky) 31.38 31.38 500 2b. WeakMethod EventBus (Fixed) 0.00 0.06 0 

Both fixes drop retained heap memory from ~31.4 MB down to 0.00 MB and cut peak memory usage by over 99%.

Catching Memory Regressions Automatically in pytest

Instead of waiting for a production OOM alert at 3 AM, you can run a fast tracemalloc budget test inside your normal pytest suite:

def test_fixed_session_processor_does_not_leak_memory() -> None: gc.collect() tracemalloc.start() try: base_current, _ = tracemalloc.get_traced_memory() for i in range(300): proc = FixedSessionProcessor(f"s-{i}", payload_kb=64) assert proc.compute_score(2) == 128 gc.collect() after_current, _ = tracemalloc.get_traced_memory() finally: tracemalloc.stop() growth_mb = (after_current - base_current) / (1024 * 1024) assert growth_mb < 0.5, f"Unexpected memory growth: {growth_mb:.2f} MB" 

One subtle Python gotcha worth noting when writing leak tests: Python for loops do not create a new variable scope. If you check bus.subscriber_count == 0 right after a loop that assigned sub = FixedSubscriber(...), the loop variable sub still holds a strong reference to the final iteration's object until you explicitly del sub (or wrap the loop body in a helper function).

Running the full suite:

tests/test_memory.py::test_session_processors_return_identical_scores PASSED [ 25%] tests/test_memory.py::test_fixed_session_processor_does_not_leak_memory PASSED [ 50%] tests/test_memory.py::test_weak_event_bus_prunes_dead_subscribers PASSED [ 75%] tests/test_memory.py::test_leaky_event_bus_retains_dead_subscribers PASSED [100%] ============================== 4 passed in 0.12s ============================== 

Key Takeaways

  • Never put @lru_cache directly on an instance method unless the instance lives for the entire lifetime of the process. Extract a pure function keyed on primitives (or use a bounded per-instance cache).
  • Use weakref.WeakMethod for callback registries and event buses whenever subscribers have shorter lifecycles than the bus.
  • Put tracemalloc assertions in CI. Testing 300–500 object lifecycles takes ~0.1 seconds and catches reference leaks before they ever reach staging.