python runtime_error ai_generated true

RuntimeError: Event loop is closed

ID: python/fastapi-event-loop-closed

Also available as: JSON · Markdown · 中文
80%Fix Rate
84%Confidence
0Evidence
2025-01-22First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active — — —

Root Cause

Async resources (httpx.AsyncClient, aiohttp session) created in one event loop are reused after that loop closed, common in tests or reload.

generic

中文

在一个事件循环中创建的异步资源(httpx.AsyncClient、aiohttp session)在该循环关闭后被复用,常见于测试或重载场景。

Workarounds

  1. 90% success
    Create clients inside lifespan and close on shutdown:
    @asynccontextmanager
    async def lifespan(app):
        app.state.client = httpx.AsyncClient()
        yield
        await app.state.client.aclose()
  2. 85% success
    Use pytest-asyncio with a single loop fixture for tests.

Dead Ends

Common approaches that don't work:

  1. 75% fail

    Creates a fresh loop but existing clients bound to the old loop still fail.

  2. 80% fail

    Subsequent requests hang or raise again on the closed loop.