Two Silent Python Memory Leaks That Slip Past Code Review and How to Catch Them
Long-running Python services such as FastAPI servers and Celery workers still run out of memory in production, despite automatic reference counting and cyclic garbage collection. Most of these leaks stem from unintended strong references that keep short-lived objects alive indefinitely. Such leaks often escape unit tests, since a single test creates one object and then exits. The author demonstrates two common cases in a Python 3.12 lab: applying functools.lru_cache to an instance method, which pins each instance in the cache, and an event bus that retains subscribers that never unsubscribed. Fixes include moving the cache to a module-level function keyed on primitive values and using weakref.WeakMethod, with pytest memory-growth assertions to guard against regressions.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in