python runtime_error ai_generated true

WARNING: Blocking call detected in async endpoint: time.sleep(5)

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

Also available as: JSON · Markdown · 中文
80%Fix Rate
85%Confidence
0Evidence
2024-06-30First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.9+ active
3.10+ active
3.11+ active
3.12+ active

Root Cause

A synchronous blocking function (time.sleep, requests, CPU-bound work) was called directly inside an async def endpoint, freezing the event loop.

generic

中文

在 async def 端点中直接调用了同步阻塞函数(time.sleep、requests、CPU 密集型工作),冻结了事件循环。

Workarounds

  1. 95% success
    from fastapi.concurrency import run_in_threadpool
    
    @app.get('/x')
    async def x():
        result = await run_in_threadpool(blocking_fn, arg)
  2. 93% success
    async with httpx.AsyncClient() as client:
        r = await client.get(url)

Dead Ends

Common approaches that don't work:

  1. 75% fail

    Each worker still blocks its own loop; throughput does not improve for a single request.

  2. 80% fail

    Yielding once does not prevent the subsequent block from stalling the loop.