Introducing Livops 2.0! Promo codeCEOgives you 8,000 so‘m on your balance.What’s new

RuntimeError: Event loop is closed — how to fix it in Python asyncio

RuntimeError: Event loop is closed means code asked an asyncio event loop to do something after that loop had been closed: an aiohttp or httpx client created inside one asyncio.run() and used in the next, a session closed after the program's loop ended, python-telegram-bot's run_polling() restarted in the same process, or, on Windows, a transport cleaned up at exit. Create clients inside the running loop, close them before it ends, and run the loop once.

By Livops team, the people who build and run LivopsUpdated

The error, as Python raises it:

RuntimeError: Event loop is closed

And the form it takes on Windows, printed when the program exits[8][9]:

Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x...>
Traceback (most recent call last):
  ...
RuntimeError: Event loop is closed

This page explains what a closed loop is, the four ways a Python program — very often a Telegram bot on aiogram or python-telegram-bot, or a script using aiohttp or httpx — ends up using one, and the fix for each. It ends with how it looks on Livops.

What does the error mean?

An asyncio event loop runs your coroutines, and when it is done it is closed. asyncio.run() creates a new loop, runs your coroutine on it and closes the loop at the end[1]; before closing, it cancels the tasks still pending, finalizes async generators and shuts down the default executor[5]. Closing a loop is irreversible, and no other methods should be called on it afterwards[2].

CPython enforces that. call_soon(), create_task() and run_until_complete() all check first whether the loop is closed, and if it is they raise RuntimeError('Event loop is closed')[3]. You rarely call these yourself, but the libraries you use do: when a socket transport is closed, for example, it schedules its last callback with the loop’s call_soon()[4]. So the error usually comes from deep inside aiohttp, httpx or asyncio, not from your line, and what it means is: an object made on a loop that has ended was asked to do something.

Event loop is closed or already running?

They are opposite mistakes, and they are often confused:

Message What happened Fix
Event loop is closed Code used a loop, or a client tied to it, after the loop finished Create clients inside the loop, close them before it ends
This event loop is already running Code tried to start a loop inside a loop that is still running Start the loop once and await inside it

The second one is explained in RuntimeError: This event loop is already running. Trying to fix one by adding or removing asyncio.run() calls often produces the other.

Causes, most common first

1. A client created in one asyncio.run() and used in the next

session = None

async def fetch(url):
    global session
    if session is None:
        session = aiohttp.ClientSession()   # tied to the loop running now
    async with session.get(url) as r:
        return await r.text()

asyncio.run(fetch("https://example.com"))  # loop 1: creates the session
asyncio.run(fetch("https://example.org"))  # loop 2: session still points at loop 1

An aiohttp ClientSession stores the event loop that is running when it is created[14], and its pooled connections live on that loop. Every asyncio.run() makes a fresh loop and closes it at the end[1], so the second call reaches back into loop 1, which is closed. The same happens with an httpx AsyncClient or a database pool kept in a global variable and reused across several asyncio.run() calls — a common shape in scripts that call asyncio.run() from a sync function in a loop or a scheduler.

2. A session closed after the loop has ended

async def main():
    global session
    session = aiohttp.ClientSession()
    ...

asyncio.run(main())
asyncio.run(session.close())   # RuntimeError: Event loop is closed

Closing is also work on the loop: the session’s connections close their transports, and a transport’s close() calls call_soon() on the loop it belongs to[4], which raises because that loop is closed[3]. Cleanup in an atexit handler, in a finally: after asyncio.run(), or in a __del__ method runs into the same thing.

3. python-telegram-bot: run_polling() restarted in the same process

Application.run_polling() takes the thread’s current event loop with asyncio.get_event_loop(), creating one only if there is none, and runs everything on it[20]. Its close_loop parameter defaults to True: the current event loop is closed on shutdown[19]. That loop stays the thread’s current loop[2], so a second run_polling() in the same process — a while True: restart wrapper, or a second Application started after the first returned — is handed the closed loop, and its first run_until_complete() raises[3][20].

4. Windows: _ProactorBasePipeTransport.__del__ at exit

Since Python 3.8 the default event loop on Windows is ProactorEventLoop[7]. In older Python versions its transports’ __del__ called close(), which scheduled work on the loop; when the garbage collector got to a transport after asyncio.run() had closed the loop, that raised and was printed as “Exception ignored in”[8][9]. The original report saw it at the end of asyncio.run() with SSL connections, after the program’s work was already done[8].

It was a CPython bug, tracked as issue 92841 and fixed with pull request 92842[9]: the changelog entry says asyncio no longer throws the error on interpreter exit after asynchronous socket activity. The fix is in Python 3.10.6[10] and in 3.11, from 3.11.0 beta 2[11]. In current CPython the Proactor transport’s __del__ closes the socket directly instead of going through the loop[6].

How to fix it

One loop, clients created inside it

The structure that avoids all four: one async def main(), run once with asyncio.run(), and every client created inside it with async with, so it is closed before the loop is.

import asyncio
import aiohttp

async def main() -> None:
    async with aiohttp.ClientSession() as session:
        for url in urls:
            async with session.get(url) as r:
                print(r.status)

asyncio.run(main())

This is the shape aiohttp’s quickstart shows; without async with, await session.close() has to be called yourself[12]. aiohttp also asks for one session per application rather than a session per request[12], so open it once and pass it around. httpx works the same way: async with httpx.AsyncClient() as client:, or await client.aclose() to close it explicitly, and one client rather than many[15].

asyncio.run() should ideally be called only once in a program[1]. If sync code has to make several async calls in a row, use one asyncio.Runner, which is meant for several top-level calls on the same loop[1]; the loop is closed when the with block ends[1][5].

with asyncio.Runner() as runner:
    runner.run(connect())
    runner.run(send_report())   # same loop as connect()

aiogram 3: open in startup, close in shutdown

The Bot’s own HTTP session is aiogram’s business: start_polling() and run_polling() close the bot sessions on shutdown unless close_bot_session=False is passed[16][17]. Your own clients — an aiohttp session to another API, a database pool — belong in the dispatcher’s startup and shutdown observers[18]. When polling stops, aiogram runs the shutdown callbacks first and then closes the bot sessions[16][17], all while the loop is still running.

import asyncio
import aiohttp
from aiogram import Bot, Dispatcher

dp = Dispatcher()
http: aiohttp.ClientSession | None = None

async def on_startup() -> None:
    global http
    http = aiohttp.ClientSession()      # created on the running loop

async def on_shutdown() -> None:
    await http.close()                  # closed before the loop ends

async def main() -> None:
    dp.startup.register(on_startup)
    dp.shutdown.register(on_shutdown)
    await dp.start_polling(Bot(TOKEN))

asyncio.run(main())

python-telegram-bot: post_init and post_shutdown

ApplicationBuilder.post_shutdown() sets a coroutine that run_polling() and run_webhook() run after the application has shut down, and the builder’s own example uses it to close a database connection[21]. Create the client in post_init, close it in post_shutdown:

import httpx
from telegram.ext import Application

async def post_init(app: Application) -> None:
    app.bot_data["http"] = httpx.AsyncClient()

async def post_shutdown(app: Application) -> None:
    await app.bot_data["http"].aclose()

app = (
    Application.builder().token(TOKEN)
    .post_init(post_init)
    .post_shutdown(post_shutdown)
    .build()
)
app.run_polling()

run_polling() stops the updater and the application, runs post_stop, shutdown() and then post_shutdown[19], and only after that closes the loop[20]. Call run_polling() once per process. If something really must run it a second time in the same process, pass close_loop=False[19]; otherwise let the process exit and be started again.

On Windows: upgrade Python, and close what you open

If the traceback ends in _ProactorBasePipeTransport.__del__ and only appears at exit, check python --version: anything older than 3.10.6 still has the bug[10]. The reporter of the original issue made it go away by closing every transport before leaving scope[8]. With aiohttp, closing a session leaves the underlying connections open for a short while; aiohttp’s documentation suggests await asyncio.sleep(0) before the loop ends, or about 250 ms for SSL connections, otherwise a ResourceWarning: unclosed transport may be emitted[13].

Find what was left open

Run the program with python -W default bot.py: asyncio’s development guide recommends turning on the display of ResourceWarning, and -W default is the way it names[22]. aiohttp reports a session that was never closed as “Unclosed client session”[14], which points straight at the object to move into a startup and shutdown pair.

On Livops

  • If it stops the bot at start. An exception at startup ends the process and the deploy fails as start_failed; the traceback is the bot’s last words on the Logs page. A bot’s old version is stopped before the new one starts, because two copies polling Telegram would conflict, so the bot is down until a deploy succeeds. See The app did not start.
  • If it comes from a handler. The traceback is on the project’s Logs page; livops logs <service> -f follows it from the terminal (CLI). If a bot crashes because of a bug in its own code, Livops sends you the line it failed on in Telegram.
  • If the bot just exits. A program that ran to the end and exited with code 0 — for example a missing await before start_polling() — is a different case: The program finished on its own.
  • Where it runs. A polling bot runs as a worker, an always-on background process, with no public URL (Cron and workers). Its start command, such as .venv/bin/python bot.py, is set in Settings → Start or as a worker: line in a Procfile (No start command).

A bot costs 19 credits a month (19,000 so’m); see Pricing.

Questions

What does RuntimeError Event loop is closed mean?

Something asked an asyncio event loop to schedule work after that loop had been closed. Closing a loop is final, and asyncio checks for it before scheduling a callback, creating a task or running the loop. The code that fails is usually a client, a session or a connection that was created on a loop that has since ended.

How is it different from This event loop is already running?

They are opposite mistakes. Already running means the code tried to start a loop inside one that is still running. Event loop is closed means the code used a loop, or an object tied to it, after that loop had finished. The first is fixed by starting the loop only once; the second by creating clients inside the loop and closing them before it ends.

Why does it happen when I call asyncio.run() twice?

Each asyncio.run() creates a new event loop and closes it at the end. A client created during the first call, such as an aiohttp ClientSession kept in a global variable, stays tied to the first loop. Using or closing it in the second call reaches into the closed loop. Run one async main function once, or create the client again inside each call.

Why do I see Exception ignored in _ProactorBasePipeTransport.__del__ on Windows?

It is a CPython bug in the Windows Proactor event loop: at exit, a transport's cleanup tried to schedule work on the loop that asyncio.run() had already closed. It was fixed in Python 3.10.6 and in 3.11. Upgrade Python, and close your HTTP sessions before the loop ends so no transport is left for the garbage collector.

How do I close an aiohttp session in an aiogram bot?

Bot sessions are closed by aiogram itself: start_polling and run_polling close them on shutdown unless close_bot_session=False is passed. For a session of your own, create it in a startup callback registered with dp.startup.register and close it in one registered with dp.shutdown.register, which aiogram runs before it closes the bot sessions.

How do I close a client in python-telegram-bot?

Create it in post_init and close it in post_shutdown, both set on the ApplicationBuilder. run_polling runs post_shutdown after the application has shut down and before it closes the event loop, so the client is closed while its loop is still open.

Should I restart the bot in a while True loop when it crashes?

Not around run_polling in python-telegram-bot: it closes the event loop on shutdown by default, so the next run in the same process meets a closed loop. Let the process exit and be started again by whatever runs it, or pass close_loop=False if you really must run it twice.

Sources

  1. Python documentation — asyncio Runners (asyncio.run, asyncio.Runner) (docs.python.org). Checked .
  2. Python documentation — asyncio Event Loop (docs.python.org). Checked .
  3. CPython source — Lib/asyncio/base_events.py (raw.githubusercontent.com). Checked .
  4. CPython source — Lib/asyncio/selector_events.py (raw.githubusercontent.com). Checked .
  5. CPython source — Lib/asyncio/runners.py (raw.githubusercontent.com). Checked .
  6. CPython source — Lib/asyncio/proactor_events.py (raw.githubusercontent.com). Checked .
  7. Python documentation — asyncio Platform Support (docs.python.org). Checked .
  8. CPython issue 83413 — asyncio crashes when tearing down the proactor event loop (github.com). Checked .
  9. CPython issue 92841 — asyncio internals throw RuntimeError: Event loop is closed on script exit (github.com). Checked .
  10. Python 3.10 changelog (docs.python.org). Checked .
  11. Python 3.11 changelog (docs.python.org). Checked .
  12. aiohttp documentation — Client Quickstart (docs.aiohttp.org). Checked .
  13. aiohttp documentation — Advanced Client Usage (Graceful Shutdown) (docs.aiohttp.org). Checked .
  14. aiohttp 3.14.5 source — aiohttp/client.py (raw.githubusercontent.com). Checked .
  15. HTTPX documentation — Async Support (python-httpx.org). Checked .
  16. aiogram documentation — Long-polling (docs.aiogram.dev). Checked .
  17. aiogram source — aiogram/dispatcher/dispatcher.py (raw.githubusercontent.com). Checked .
  18. aiogram source — aiogram/dispatcher/router.py (raw.githubusercontent.com). Checked .
  19. python-telegram-bot documentation — telegram.ext.Application (docs.python-telegram-bot.org). Checked .
  20. python-telegram-bot source — telegram/ext/_application.py (raw.githubusercontent.com). Checked .
  21. python-telegram-bot source — telegram/ext/_applicationbuilder.py (raw.githubusercontent.com). Checked .
  22. Python documentation — Developing with asyncio (docs.python.org). Checked .

Put your project online today

Connect GitHub or drop a folder. No card is asked for.

Deploy your bot

Got a question? — @livops_uz