python
system_error
ai_generated
true
警告:事件循环被阻塞,异步路由中检测到阻塞调用,事件循环停滞 5.2 秒。
WARNING: (tracemalloc) ... asyncio: Task was destroyed but it is pending! Blocking call detected in async def route, event loop stalled for 5.2s
ID: python/fastapi-async-route-blocking-event-loop
80%修复率
86%置信度
0证据数
2025-05-27首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 0.100.x | active | — | — | — |
| 0.110.x | active | — | — | — |
根因分析
`async def` 路由直接调用了同步/阻塞函数(requests、time.sleep、重 CPU 操作),冻结了事件循环。
English
An `async def` route calls a synchronous/blocking function (requests, time.sleep, heavy CPU) directly, freezing the event loop.
解决方案
-
95% 成功率
Use httpx.AsyncClient: `async with httpx.AsyncClient() as c: r = await c.get(url)`
-
90% 成功率
Offload with `await asyncio.to_thread(blocking_fn, args)` or `run_in_executor`.
无效尝试
常见但无效的做法:
-
80% 失败
Each worker still blocks its own loop under load.
-
90% 失败
Does not yield for blocking I/O; loop still stalls.