Contents
In brief
In a short script, Python’s garbage collector barely registers. In a long-running worker, a FastAPI microservice, or a continuous data pipeline, RSS can climb for weeks until the process hits an OOM kill.
A Dev.to write-up walks through five traps where the algorithm is fine and a hidden reference is not. The fix pattern is the same: control object lifetimes and stop loading gigabytes into one list.
What happened
The author treats the leak like a basement drip: dry floors in the morning, a puddle by Friday. Reference counting and the cyclic GC handle one-shot scripts. Background processes accumulate five familiar patterns.
First: @lru_cache on an instance method. The cache is global and stores self, so the instance survives the request. Move the cache to a pure module-level function or a static helper.
Second: mutable default arguments. The list or dict is built once at definition time. In a worker, append into that default becomes an accidental global sink. Use None in the signature and allocate a fresh container inside the call.
Third: stored exceptions. In Python 3 an exception keeps __traceback__, and frames keep locals. Assigning last_error = exc outside except can pin a 50 MB payload from that frame. Keep str(exc) or clear exc.__traceback__.
Fourth: fire-and-forget asyncio.create_task() and reference cycles. A task with no strong ref can be collected mid-run; parent-holding callbacks do the opposite and retain whole object trees. Track tasks in a bounded set and drop them with add_done_callback(...discard).
Fifth: .fetchall() and whole-file reads. RSS spikes immediately, and freed heap pages often never return to the OS. Generators and server-side cursors (yield_per) keep the peak flat. For locating the culprit, built-in tracemalloc is enough.
Why it matters
Worker OOM rarely looks like “line N in the profiler.” More often it is a slow memory slope after deploy. The team sees “it dies overnight sometimes” and raises Kubernetes limits instead of dropping the retaining reference.
It hurts most in services where one process runs thousands of cycles: each cycle leaves a little object “just in case.” A day later the container hits the limit, a restart hides the bug, metrics look fine—until the next evening.
Knowing these five patterns saves days of hunting with heavy external profilers. Often tracemalloc over a thousand staging iterations points to the file and line allocating unfreed blocks.
In practice
- Ban
@lru_cacheon instance methods in review; cache pure functions instead. - Grep the repo for
= []and= {}in signatures—replace withNoneplus allocation inside. - Do not store exception objects in “last error” fields without clearing the traceback.
- Keep background
asynciotasks in a bounded set with adiscardcallback. - Stream large SQL and files; on staging run
tracemalloc.start(10)across worker iterations.
Takeaway
Long-running Python almost never “leaks by itself”—it keeps what you accidentally gifted it. Drop instance-level global caches, fresh containers instead of mutable defaults, short messages instead of whole exceptions, explicit task tracking, and streaming loads—and RSS stops climbing toward the ceiling.



Comments