python runtime_error ai_generated true

RuntimeWarning: coroutine 'sleep' was never awaited / requests.exceptions.ConnectionError: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response'))

ID: python/fastapi-async-blocking-event-loop

Also available as: JSON · Markdown · 中文
80%Fix Rate
83%Confidence
0Evidence
2024-11-08First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active — — —

Root Cause

Blocking synchronous calls (requests, time.sleep, heavy IO) inside an async def endpoint block the event loop, causing timeouts and dropped connections.

generic

中文

在 async def 端点内进行阻塞式同步调用(requests、time.sleep、重 IO)会阻塞事件循环,导致超时和连接中断。

Workarounds

  1. 95% success
    import httpx
    async with httpx.AsyncClient() as client:
        r = await client.get(url)
  2. 90% success
    from starlette.concurrency import run_in_threadpool
    result = await run_in_threadpool(blocking_fn, arg)

Dead Ends

Common approaches that don't work:

  1. 80% fail

    Does not unblock the event loop; requests still queue.

  2. 70% fail

    Each worker still has one blocked loop; capacity is limited.