← Back to Python, page 4

python-0074 · Hard senior

A Python web service's memory grows steadily until it is restarted. How do you investigate?

Confirm the growth with metrics, then compare memory snapshots over time: tracemalloc snapshots show which lines allocate the growing memory, and gc or objgraph show which object types increase. Usual causes are unbounded caches, lists or dicts that keep growing, references held by closures or global registries, and C extensions. Fix the retention, then verify with a load test.

Full answer
python
import tracemalloc
LEAK = []
def handle_request(i):
    payload = "x" * 10_000
    LEAK.append(payload)
    return len(payload)

tracemalloc.start()
for i in range(50): handle_request(i)
before = tracemalloc.take_snapshot()
for i in range(500): handle_request(i)
after = tracemalloc.take_snapshot()
top = after.compare_to(before, "lineno")[0]
print("top growth at line", top.traceback[0].lineno, "| grew by more than 4 MB:", top.size_diff > 4_000_000)

Output:

text
top growth at line 4 | grew by more than 4 MB: True

The run simulates a leak: a module-level list keeps every request's payload. Comparing two tracemalloc snapshots taken before and after a batch of requests points at line 4, which creates each payload: tracemalloc reports where memory was allocated, and the list is what keeps those allocations alive. In a real service the next step is to find what holds references to objects allocated at the reported line.

A practical sequence:

  1. Check whether memory plateaus (normal allocator behaviour, caches warming) or grows without bound.
  2. Reproduce with a load test locally or on a staging copy.
  3. Take tracemalloc snapshots a few minutes apart and compare with compare_to(..., 'lineno').
  4. Inspect growing object types with gc.get_objects() counts or objgraph.
  5. Typical fixes: bound caches (lru_cache(maxsize=...)), clear per-request state, remove event-listener registrations, avoid storing request objects in globals.
  6. If Python-level memory is flat but the process grows, suspect C extensions or fragmentation; tools such as memray help.

Restarting workers periodically (for example gunicorn's max_requests) is a mitigation, not a fix.

python
import tracemalloc
LEAK = []
def handle_request(i):
    payload = "x" * 10_000
    LEAK.append(payload)
    return len(payload)

tracemalloc.start()
for i in range(50): handle_request(i)
before = tracemalloc.take_snapshot()
for i in range(500): handle_request(i)
after = tracemalloc.take_snapshot()
top = after.compare_to(before, "lineno")[0]
print("top growth at line", top.traceback[0].lineno, "| grew by more than 4 MB:", top.size_diff > 4_000_000)

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Confirm unbounded growth first
  • Compare tracemalloc snapshots
  • Track growing object types
  • Common causes are unbounded containers and caches
  • Periodic restarts only mitigate

Common mistakes

  • Restarting forever without investigating
  • Assuming the garbage collector is broken

Follow-ups

  • How does memray differ from tracemalloc?
  • Why might memory not return to the OS after objects are freed?

Tips

  • Compare snapshots