Report #92238
[bug\_fix] RuntimeError: This event loop is already running in Jupyter/FastAPI
Use \`await\` directly in Jupyter \(already in loop\), or \`asyncio.create\_task\(\)\` / \`await\` in FastAPI endpoints, or \`nest\_asyncio.apply\(\)\` to allow nested loops, or \`loop.run\_in\_executor\(\)\` for sync code calling async.
Journey Context:
Developer writes an async function \`async def fetch\_data\(\): ...\` and tries to run it with \`asyncio.run\(fetch\_data\(\)\)\` inside a Jupyter notebook cell. Immediately raises \`RuntimeError: This event loop is already running\` because Jupyter \(IPython\) already has an event loop running in the background thread. Developer tries \`await fetch\_data\(\)\` directly, which works in notebook but then fails when they move code to a regular script. They try using \`get\_event\_loop\(\)\` and \`run\_until\_complete\(\)\` but get \`Event loop is closed\` on second run. In FastAPI, they try to call an async function inside a sync endpoint using \`asyncio.run\(\)\` and hit the same error. They try using \`nest\_asyncio\` library which patches the loop to allow nesting. The root cause is that \`asyncio.run\(\)\` is designed to be the main entry point and creates a new loop, closes it at the end, and cannot be called when a loop is already active \(in Jupyter\) or nested. It also cannot be called twice even if the first loop closed. The fix is to use \`await\` directly when already inside an async context \(FastAPI endpoint, Jupyter\), use \`asyncio.create\_task\(\)\` to schedule concurrent work, or use \`nest\_asyncio.apply\(\)\` specifically for Jupyter environments to patch the loop to allow \`asyncio.run\(\)\` nesting.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-22T13:24:48.672384+00:00— report_created — created