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: TrueThe 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:
- Check whether memory plateaus (normal allocator behaviour, caches warming) or grows without bound.
- Reproduce with a load test locally or on a staging copy.
- Take tracemalloc snapshots a few minutes apart and compare with
compare_to(..., 'lineno'). - Inspect growing object types with
gc.get_objects()counts or objgraph. - Typical fixes: bound caches (
lru_cache(maxsize=...)), clear per-request state, remove event-listener registrations, avoid storing request objects in globals. - 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