Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~5 min readPython
#Python#asyncio#FastAPI#Debugging
An asyncio event loop ring already occupied, a cyan coroutine queue and an amber nested run attempt blocked

Introduction & Quick Summary

text
RuntimeError: This event loop is already running

Something 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, an async def test, or an async framework endpoint that calls a synchronous library which itself calls asyncio.run.
  • A sync library wrapped in an async app. Playwright's sync API, requests adapters, or a blocking SDK that creates its own loop inside a FastAPI or Jupyter process.
  • loop.run_until_complete on a loop that is already running, often through a deprecated asyncio.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_asyncio partially 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.
ContextWhat is already runningCorrect call
Jupyter cellKernel loopawait main() at top level
async def functionIts own coroutine's loopawait something()
FastAPI async endpointServer loopawait, or run sync work in a thread
pytest with pytest-asyncioTest loopMark async and await
Plain scriptNothingasyncio.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:

python
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:

python
# Jupyter cell import asyncio asyncio.run(main()) # RuntimeError: asyncio.run() cannot be called from a running event loop
python
# 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

FunctionCreates a loopFails inside a running loopUse case
asyncio.run(coro)YesYesScript entry point
loop.run_until_complete(coro)NoYesOwning a loop manually
await coroNoNoInside async code
asyncio.run_coroutine_threadsafeNoNoFrom another thread
loop.call_soon_threadsafeNoNoScheduling from a thread
asyncio.create_task(coro)NoNoFire and forget in a loop
SituationRecommended approachAvoid
Sync library in async appawait asyncio.to_thread(fn)asyncio.run inside the endpoint
Async library in sync codeasyncio.run(...) at the topA module-level loop
NotebookTop-level awaitasyncio.run
Script with one async mainasyncio.run(main()) in __main__Building a loop by hand
Cross-thread callrun_coroutine_threadsaferun_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

python
@app.get("/report") async def report(): return generate_report() # generate_report calls asyncio.run internally

Two correct shapes, depending on whether the work is blocking or genuinely async:

python
@app.get("/report") async def report(): return await asyncio.to_thread(generate_report) # blocking work off the loop
python
@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

text
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:

python
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 html

Case 3: Calling an async helper from synchronous code in the same process

python
def handler(payload): loop = asyncio.get_event_loop() return loop.run_until_complete(process(payload)) # fails if handler is called from async code

If 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:

python
def handler(payload): return asyncio.run(process(payload)) # safe only when the caller is sync

Case 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:

python
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

python
import nest_asyncio, asyncio nest_asyncio.apply() asyncio.run(main()) # now works, by re-entering the loop

It 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

python
import pytest @pytest.mark.asyncio async def test_fetch(): result = await fetch() assert result

With 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 with get_running_loop() inside async code or with an explicit new_event_loop().
  • Two libraries, two loops. A library that calls asyncio.set_event_loop at 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.run closes the loop. After it returns, any task or connection created against that loop is attached to a closed loop, producing Event loop is closed errors on the next use. Keep one loop per process for long-lived resources.
  • TaskGroup and gather swallowing the original cause. When the error happens inside a gathered coroutine, the message can be wrapped in an ExceptionGroup; 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_threadsafe creates 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 documentation

The Python documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.