Introduction

Memory leaks in long-running Python applications cause instability. This guide covers systematic detection and resolution using built-in tools.

Symptoms

  • Memory usage continuously increasing
  • Process killed by OOM killer
  • Memory not released after task completion
  • gc.collect() not reducing memory

Step-by-Step Fix

  1. 1.Enable tracemalloc for tracking:
  2. 2.```python
  3. 3.import tracemalloc
  4. 4.tracemalloc.start()

# Take snapshots snapshot1 = tracemalloc.take_snapshot() # ... run code ... snapshot2 = tracemalloc.take_snapshot()

top_stats = snapshot2.compare_to(snapshot1, 'lineno') for stat in top_stats[:10]: print(stat) ```

  1. 1.Use objgraph to find reference cycles:
  2. 2.```python
  3. 3.import objgraph

objgraph.show_most_common_types() objgraph.show_growth()

# Find back references objgraph.show_back_refs( objgraph.by_type('MyClass')[:3], max_depth=5 ) ```