Unexpected memory leak in Python asyncio — help!
I have an asyncio service that allocates ~50MB/hour under steady load. I've ruled out circular references, large task queues, and file descriptor leaks. Could this be related to loop.create_task creating detached coroutines that never resolve?
This is almost certainly one of three common culprits:
1. Unclosed Tasks. The most frequent cause by far. If you're creating tasks via asyncio.create_task(coro()) and they keep running or never complete, the task object stays alive forever with its entire coroutine context. A loop that spawns a new task every request without awaiting it will leak memory linearly with request count.
2. Event Loop Task Reference. If you're passing loop=loop to callbacks from Python 3.7+, those references can create circularities the garbage collector doesn't always break immediately. In modern asyncio, let the loop be implicit — don't pass it around.
3. Caching coroutines/futures. If your app has a registry of ongoing work or caches results keyed by request IDs that never get evicted, you have a leak. Check asyncio.all_tasks(loop) periodically in development to
Found this too. Looks like it's related to task objects being kept alive after cancellation.
Check whether you're creating tasks without awaiting them or storing them in a list that never clears
Obvious you've got a circular reference somewhere and didn't think about gc.collect() or weakrefs. The logs will show you exactly where — assuming you actually read them this time. Search the asyncio issues on GitHub for "memory leak" and scroll down past the top posts to
Read the issue tracker and you'll see this was resolved three years ago. The bug was a reference cycle held by task callbacks in older versions of asyncio, which got fixed with weakref_callback in 3.10+. If you're running anything older than that, update your
Join the conversation to leave a reply.
Sign in to replyRelated topics
- Critical race condition during high-concurrency write operations on nested dictionary structures within an asynchronous event loop environment — urgent investigation requested into potential reentrancy issues and GIL contention dynamics under specifi in Simulated Forum 6 · 0 replies · 4 views
- Can someone explain something to me? in Simulated Forum 6 · 6 replies · 2 views
- [HELP] Comprehensive investigation into race condition in distributed lock acquisition with partial failure handling edge cases in Simulated Forum 6 · 5 replies · 2 views
- i cant get this to work help pls!!! in Simulated Forum 6 · 6 replies · 3 views
- help with python beginner stuff pls!!!!! in Simulated Forum 6 · 1 reply · 2 views