RuntimeError: This event loop is already running in asyncio
A second loop tried to drive the same thread. Await inside async code, move blocking work to a thread, and never nest asyncio.run in a server.

Introduction & Quick Summary
RuntimeError: This event loop is already runningSomething asked asyncio to start a loop while a loop was already running in the same thread. Each thread can drive one loop at a time, and run_until_complete, run_forever and asyncio.run all try to drive it, so the second nested attempt raises this error instead of blocking forever.
Where it comes from, most common first:
asyncio.run()inside a coroutine. A notebook cell, anasync deftest, or an async framework endpoint that calls a synchronous library which itself callsasyncio.run.- A sync library wrapped in an async app. Playwright's sync API,
requestsadapters, or a blocking SDK that creates its own loop inside a FastAPI or Jupyter process. loop.run_until_completeon a loop that is already running, often through a deprecatedasyncio.get_event_loop()handle captured earlier.- A Jupyter kernel. The kernel runs its own loop for the whole session, so any top-level
asyncio.run(main())cell fails. nest_asynciopartially applied. A patched loop somewhere and an unpatched one elsewhere produce the error in a different cell or thread than the one that was fixed.
| Context | What is already running | Correct call |
|---|---|---|
| Jupyter cell | Kernel loop | await main() at top level |
async def function | Its own coroutine's loop | await something() |
| FastAPI async endpoint | Server loop | await, or run sync work in a thread |
pytest with pytest-asyncio | Test loop | Mark async and await |
| Plain script | Nothing | asyncio.run(main()) is correct here |
Core Mechanics, Signatures & Reproducible Setup
asyncio.run() creates a new loop, sets it as current for the thread, runs the coroutine to completion, cancels remaining tasks and closes the loop. Its guard is explicit: if events.get_running_loop() succeeds, it raises this error rather than nesting. loop.run_until_complete() behaves the same way on a loop that is already running.
Reproduce it in three lines:
import asyncio
async def inner():
return 1
async def outer():
return asyncio.run(inner()) # RuntimeError: This event loop is already running
asyncio.run(outer())The same call from a notebook fails even at top level, because the cell itself runs inside the kernel's loop:
# Jupyter cell
import asyncio
asyncio.run(main())
# RuntimeError: asyncio.run() cannot be called from a running event loop# Jupyter cell, correct form
await main()The rule that resolves almost every case: inside an async def, nothing calls asyncio.run. You await the coroutine, and the caller that owns the loop decides when to run it.
Key Comparison Table
| Function | Creates a loop | Fails inside a running loop | Use case |
|---|---|---|---|
asyncio.run(coro) | Yes | Yes | Script entry point |
loop.run_until_complete(coro) | No | Yes | Owning a loop manually |
await coro | No | No | Inside async code |
asyncio.run_coroutine_threadsafe | No | No | From another thread |
loop.call_soon_threadsafe | No | No | Scheduling from a thread |
asyncio.create_task(coro) | No | No | Fire and forget in a loop |
| Situation | Recommended approach | Avoid |
|---|---|---|
| Sync library in async app | await asyncio.to_thread(fn) | asyncio.run inside the endpoint |
| Async library in sync code | asyncio.run(...) at the top | A module-level loop |
| Notebook | Top-level await | asyncio.run |
| Script with one async main | asyncio.run(main()) in __main__ | Building a loop by hand |
| Cross-thread call | run_coroutine_threadsafe | run_until_complete on a foreign thread |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
Case 1: A sync SDK called from an async FastAPI endpoint
@app.get("/report")
async def report():
return generate_report() # generate_report calls asyncio.run internallyTwo correct shapes, depending on whether the work is blocking or genuinely async:
@app.get("/report")
async def report():
return await asyncio.to_thread(generate_report) # blocking work off the loop@app.get("/report")
def report(): # sync endpoint runs in a threadpool
return generate_report()Declaring the endpoint def instead of async def is often the smallest fix, because FastAPI runs sync endpoints in a worker thread where asyncio.run succeeds.
Case 2: Playwright's sync API inside an async test
It looks like you are using Playwright Sync API inside the asyncio loop.
Please use the Async API instead.The error text differs but the cause is identical. Convert to the async API:
from playwright.async_api import async_playwright
async def scrape(url: str) -> str:
async with async_playwright() as p:
browser = await p.chromium.launch()
page = await browser.new_page()
await page.goto(url)
html = await page.content()
await browser.close()
return htmlCase 3: Calling an async helper from synchronous code in the same process
def handler(payload):
loop = asyncio.get_event_loop()
return loop.run_until_complete(process(payload)) # fails if handler is called from async codeIf handler can be reached from both worlds, do not reach for the loop. Either make it async and await it, or run it in a thread that owns nothing:
def handler(payload):
return asyncio.run(process(payload)) # safe only when the caller is syncCase 4: Background work from a sync callback
A signal handler, a thread pool worker, or a library callback runs outside the loop thread, so it cannot await and must not start a nested loop. Post the coroutine to the running loop:
future = asyncio.run_coroutine_threadsafe(notify(event), loop)
result = future.result(timeout=5)Capture loop once with asyncio.get_running_loop() inside async setup, and never call get_event_loop() from a thread that does not own one.
Case 5: nest_asyncio and its limits
import nest_asyncio, asyncio
nest_asyncio.apply()
asyncio.run(main()) # now works, by re-entering the loopIt re-enters a running loop by patching internals. That is acceptable in a notebook, but in a server it breaks cancellation, nested TaskGroup cleanup and any library that relies on loop shutdown, so do not ship it as the fix.
Case 6: Test frameworks that already own a loop
import pytest
@pytest.mark.asyncio
async def test_fetch():
result = await fetch()
assert resultWith pytest-asyncio, the test function must be async and awaited by the plugin. A plain def test_... that calls asyncio.run works only if no other fixture started a loop; the moment an async fixture is added, it fails with this error.
Common Compilation/Runtime Mistakes & Version Gotchas
get_event_loop()deprecation. Python 3.12 warns when there is no current loop, and later versions raise instead of creating one implicitly. Replace it withget_running_loop()inside async code or with an explicitnew_event_loop().- Two libraries, two loops. A library that calls
asyncio.set_event_loopat import time breaks any framework that owns the loop later. Look for module-level loop creation in third-party code before blaming your own. - uvloop. Installing uvloop changes the policy but not the rule; nested runs still raise, and tracebacks point at uvloop internals instead of asyncio.
asyncio.runcloses the loop. After it returns, any task or connection created against that loop is attached to a closed loop, producingEvent loop is closederrors on the next use. Keep one loop per process for long-lived resources.TaskGroupandgatherswallowing the original cause. When the error happens inside a gathered coroutine, the message can be wrapped in anExceptionGroup; read the innermost traceback.- Threads share nothing. A loop is per thread; moving blocking work to a thread fixes this error, while moving async work to a thread without
run_coroutine_threadsafecreates a different one.
If the failing path starts in a scheduled job, verify the schedule itself with the cron expression tool before changing code, since a job that overlaps its previous run is a common source of nested execution. To compare two entry points, one working and one not, the diff tool over the two scripts shows the added asyncio.run. When the event payload that triggered the path needs inspection, the JSON formatter reads it without another round trip.
Primary references: the asyncio runner documentation states the nesting rule for asyncio.run, and developing with asyncio covers loop ownership across threads.
Official references
primary documentationThe Python documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython Typer Rich Integration and Progress Bars
python typer rich integration and progress bars: Learn to integrate Rich progress bars into Typer CLI applications, covering track, Progress, dynamic.
Python Wildcard Pattern Matching with fnmatch and glob
Learn Python's wildcard pattern matching with fnmatch, glob, and pathlib to filter strings and file paths using *, ?, and character sets.
Python 3.14 PEP 649: NameError from lazy annotations
Annotations are no longer strings. A NAME only imported under TYPE_CHECKING now raises when FastAPI or Pydantic reads the signature.
asyncpg DuplicatePreparedStatement on PgBouncer and Supabase
asyncpg caches prepared statements per connection while a transaction pooler rotates connections underneath it. The cache setting, pool sizing and retry.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.