Diagnosing Python asyncio Event Loop Failures: A Production Debugging Guide
A diagnostic guide mapping common asyncio event loop failures — nested run() calls, pending task leaks, loop starvation, cross-thread misuse — to concrete diagnostics and targeted fixes, with production escalation thresholds.
15 Nov 2026, 10:13 UTC

When the Event Loop Stops Cooperating
Asyncio applications fail in predictable ways: nested asyncio.run() calls, unawaited tasks leaking memory, CPU-bound work starving the loop, and cross-thread loop misuse. This guide maps each symptom to a diagnostic check and a targeted fix, with clear escalation thresholds for production systems running Python 3.7+.
Symptom → Cause → Diagnostic → Fix
| Observable Symptom | Root Cause | Diagnostic Command | Targeted Fix |
|---|---|---|---|
RuntimeError: This event loop is already running |
Calling asyncio.run() inside an existing loop (Jupyter, pytest-asyncio, nested entry points) |
python -c "import asyncio; print(asyncio.get_running_loop())" — succeeds if loop active |
Replace asyncio.run(coro) with asyncio.get_running_loop().create_task(coro) or pass loop explicitly to library code |
Task was destroyed but it is pending warnings at shutdown |
Unawaited coroutines or tasks not cancelled before loop close | PYTHONASYNCIODEBUG=1 python your_script.py — logs pending tasks with stack traces |
In shutdown handler: pending = asyncio.all_tasks(loop); await asyncio.gather(*pending, return_exceptions=True) |
| High latency / event loop blocking | CPU-bound work in async functions starves the loop | Set loop.slow_callback_duration = 0.05; run py-spy record -o profile.svg -- python your_script.py |
Offload with await loop.run_in_executor(process_pool, cpu_bound_func, *args) using ProcessPoolExecutor |
Event loop is closed on cleanup |
loop.close() called while tasks pending or callbacks scheduled |
Check loop.is_closed() before scheduling; verify asyncio.all_tasks(loop) empty |
Prefer asyncio.run() (handles lifecycle) or explicit try/finally with loop.shutdown_asyncgens() |
| Inconsistent behavior across threads | Asyncio API not thread-safe; wrong thread calling loop methods | Log threading.current_thread() vs loop's thread; each thread needs asyncio.new_event_loop() | Confine asyncio to single thread; use asyncio.run_coroutine_threadsafe(coro, loop) for cross-thread submission |
| Memory growth from forgotten tasks | Coroutine objects never scheduled leak memory | tracemalloc.start() + snapshot asyncio.all_tasks() comparison over time | Always await or wrap in create_task(); use weakref.finalize for fire-and-forget with cleanup |
Ordered Troubleshooting Steps
- Confirm loop policy: Run
python -c "import asyncio; print(asyncio.get_event_loop_policy())". ExpectSelectorEventLoopon Unix,ProactorEventLoopon Windows (Python 3.8+). - Enable debug mode:
PYTHONASYNCIODEBUG=1 python -m asyncio your_script.py. Capture slow-callback warnings and pending-task traces. - Trace loop API calls:
python -m trace --trace your_script.py | grep -E '(create_task|run_until_complete|call_soon)'to see where loops are created or nested. - Stress-test CPU-bound paths:
asyncio.run(asyncio.gather(*[cpu_bound() for _ in range(100)]))while monitoringloop.slow_callback_durationlogs. - Verify shutdown cleanup: Add logging in
finallyblock afterasyncio.run(); confirm zeroTask was destroyedwarnings.
Targeted Fix Patterns
Nested asyncio.run() — Library Code Pattern
# Bad: library calls asyncio.run() internally
def library_entry():
asyncio.run(inner_coro()) # fails if caller already in loop
# Good: accept loop or use get_running_loop()
async def library_entry(loop=None):
loop = loop or asyncio.get_running_loop()
return await inner_coro()
# Caller decides how to run
async def main():
await library_entry()
if __name__ == '__main__':
asyncio.run(main())
Graceful Shutdown with Pending Task Collection
async def shutdown(loop, signal=None):
if signal:
print(f"Received {signal.name}...")
tasks = [t for t in asyncio.all_tasks(loop) if not t.done()]
if tasks:
print(f"Cancelling {len(tasks)} pending tasks")
for t in tasks:
t.cancel()
await asyncio.gather(*tasks, return_exceptions=True)
await loop.shutdown_asyncgens()
loop.stop()
loop = asyncio.new_event_loop()
for sig in (signal.SIGTERM, signal.SIGINT):
loop.add_signal_handler(sig, lambda s=sig: asyncio.create_task(shutdown(loop, s)))
try:
loop.run_until_complete(main_coro())
finally:
loop.run_until_complete(shutdown(loop))
loop.close()
Offloading CPU-Bound Work
from concurrent.futures import ProcessPoolExecutor
process_pool = ProcessPoolExecutor(max_workers=4)
async def handle_request(data):
loop = asyncio.get_running_loop()
# cpu_intensive runs in separate process, doesn't block loop
result = await loop.run_in_executor(process_pool, cpu_intensive, data)
return result
# Cleanup on shutdown
async def cleanup():
process_pool.shutdown(wait=True)
Escalation Criteria
Engage deeper investigation when:
- Recurring loop starvation despite executor offload — Profile with
pyinstrumentorpy-spy. Consider rewriting hot paths in Cython/Rust or adoptinguvloop(verify C-extension compatibility first). - Deadlocks involving
call_soon_threadsafe+ locks — Engage a concurrency specialist; these often indicate architectural threading conflicts. - Unexplained task loss in production — Enable
faulthandler, capture core dumps, and if reproducible with minimal reproduction, file a CPython bug.
Verification Checklist
python -c "import asyncio; print(asyncio.get_event_loop_policy())"— confirms default policyPYTHONASYNCIODEBUG=1 python your_script.py— baseline debug output capturedpip install uvloop && python -c "import uvloop; uvloop.install(); import asyncio; print(type(asyncio.get_event_loop()))"— validates uvloop drop-in (optional)- Cross-platform test: subprocess APIs (
create_subprocess_exec) behave differently on Windows (ProactorEventLoop) vs Unix (SelectorEventLoop) - Audit third-party libraries (aiohttp, asyncpg, etc.) for private loop creation or policy expectations
Version-Specific Notes
- Python 3.12+:
asyncio.Taskconstructor changes;asyncio.TaskGroupadds structured concurrency with altered cancellation semantics — test migration thoroughly. - Debug mode overhead:
PYTHONASYNCIODEBUG=1adds measurable latency; disable in production after capturing baseline metrics. - uvloop: Not in stdlib; verify compatibility with C extensions and subprocess handling before production deployment.
Limitations
This guide covers CPython 3.7+ standard library asyncio. Alternative runtimes (PyPy, MicroPython) and third-party event loops (trio, curio) have different failure modes. Windows ProactorEventLoop has known issues with subprocess pipes and console handling — test your specific I/O patterns.