Python's reference counting and cyclic garbage collector handle everyday scripts effortlessly. However, when you deploy long-running background workers, FastAPI microservices, or continuous data pipelines, silent memory growth (RSS climbing steadily until an OOM kill) is one of the hardest production bugs to track down.
Here are five subtle memory traps in production Python services—and the exact patterns that prevent them.
1. Unbounded @lru_cache on Instance Methods
Using @functools.lru_cache directly on a class method stores a reference to self inside the global function cache. Even after your request or worker object finishes its job, the cache keeps the entire instance alive in memory forever.
The Anti-Pattern:
class DataProcessor:
@lru_cache(maxsize=1024)
def transform(self, item_id: int) -> dict:
return {"id": item_id}
The Fix: Move the cache to a standalone pure function or use @cache only on static/module-level helpers so self can be garbage collected cleanly.
2. Mutable Default Arguments Accumulating State
Default function arguments are evaluated once at function definition time—not on every call. In long-lived workers, appending to a default list or dict acts as an unintentional global memory sink:
# Bad: `buffer` grows indefinitely across every worker cycle
def enqueue_event(event: dict, buffer: list = []) -> list:
buffer.append(event)
return buffer
# Good: Allocate fresh state per invocation
def enqueue_event(event: dict, buffer: list | None = None) -> list:
if buffer is None:
buffer = []
buffer.append(event)
return buffer
3. Holding Large Exceptions in Local Variables (exc_info)
In Python 3, an exception object holds a __traceback__ attribute, which in turn keeps references to every local variable in every stack frame where the exception occurred. If you assign an exception to a variable outside the except block, you pin massive payloads or DataFrames in RAM:
# Dangerous if `raw_payload` is 50 MB
last_error = None
try:
raw_payload = fetch_large_batch()
process(raw_payload)
except ValueError as exc:
last_error = exc # Keeps `raw_payload` alive via exc.__traceback__!
The Fix: Extract only the string message (str(exc)) or clear the traceback explicitly with exc.__traceback__ = None if you must store the object.
4. Circular References with __del__ or Unclosed Async Tasks
Creating fire-and-forget tasks via asyncio.create_task() without keeping a strong reference—or storing callbacks that reference parent objects—can either cause tasks to be garbage-collected mid-execution or create reference cycles in C extensions (lxml, numpy, custom wrappers) that Python's cyclic GC cannot inspect.
Always track background tasks in a bounded set with a cleanup callback:
background_tasks: set[asyncio.Task] = set()
task = asyncio.create_task(sync_metrics())
background_tasks.add(task)
task.add_done_callback(background_tasks.discard)
5. Loading Entire Files or Query Results Instead of Streaming
Calling .fetchall() on large SQL queries or reading multi-gigabyte JSON/CSV exports into a single list spikes RSS memory immediately. Python's OS allocator (malloc) rarely returns freed heap pages back to the operating system even after the list goes out of scope.
Use generators (yield) and server-side cursors (yield_per(1000)) so peak memory stays flat regardless of dataset size.
Quick Production Profiling Tip
If you suspect a slow leak in staging, Python's built-in tracemalloc module pinpoints the exact file and line number allocating unfreed blocks without needing heavy external profilers:
import tracemalloc
tracemalloc.start(10)
# ... run 1,000 worker iterations ...
snapshot = tracemalloc.take_snapshot()
for stat in snapshot.statistics("lineno")[:5]:
print(stat)
What is the trickiest memory leak or OOM issue you have ever debugged in Python? Share your war stories in the comments!
Top comments (6)
One nuance: maxsize=1024 bounds the number of cache entries, but their keys can retain self until eviction or cache_clear(). In a small reproducer, a weak reference to an instance before and after clearing the cache can help check whether the cache was keeping it alive. An unbounded @cache can retain instances indefinitely.
Great nuance, Aiko! You're totally right—with
maxsize=1024,selfstays pinned until those specific keys are evicted (which can take forever if the instance is short-lived and rarely called again), whereas@cacheholds it indefinitely. Usingweakref.refin a quick test reproducer is a super clean way to verify whether a cache is blocking garbage collection. Thanks for adding that!The lru_cache one is easy to miss because the cache looks bounded. A capped size still pins self until eviction.
Exactly! Because
maxsizemakes it look "safe and bounded" at first glance, it easily slips past code reviews—until you realize 1,024 distinctselfinstances can still sit pinned in memory long after their tasks finish. Glad it resonated!maxsize looking safe and bounded is exactly how it slips past review. Pinned self instances are the part nobody checks for.
100%—until a heap profiler like
tracemallocorobjgraphflags thousands of lingering service objects, nobody ever suspects the cache decorator!