backend-hang-debug
診斷並修復 FastAPI 掛起問題
FastAPI 應用程式可能在 ThreadPoolExecutor 關閉阻塞事件循環時掛起,特別是在 SSE 串流斷開連線時。此技能提供可重複的分診工作流程,使用 py-spy 捕獲即時堆疊並應用非阻塞執行器模式來恢復回應能力。
下载技能 ZIP
在 Claude 中上传
前往 设置 → 功能 → 技能 → 上传技能
开启并开始使用
测试它
正在使用“backend-hang-debug”。 我的 FastAPI 新聞串流路由導致應用程式���起。當串流作用中時健康檢查超時。
预期结果:
- 掛起可能是由 ThreadPoolExecutor.shutdown(wait=True) 在用戶端斷開連線時阻塞事件循環引起的。
- 1. 使用以下命令捕獲即時堆疊:sudo py-spy dump --pid $(pgrep -f 'uvicorn app.main')
- 2. 在 api/routes/stream.py 中尋找 ThreadPoolExecutor.shutdown 框架
- 3. 重構為使用非阻塞執行器:在上下文管理器外部建立執行器,在斷開時使用 cancel(),並在 finally 區塊中調用 shutdown(wait=False, cancel_futures=True)。
- 4. 使用以下命令驗證:curl -m 5 http://localhost:8000/health 在作用中串流期間
安全审计
安全This is a documentation-only skill containing markdown instructions for debugging FastAPI hangs. The static analyzer flagged 74 pattern matches, but all are false positives: the skill contains no executable code, scripts, network operations, or filesystem access beyond reading its own file. The 'commands' flagged are documentation examples showing diagnostic commands users might run on their own systems. Pure informational content safe for publication.
风险因素
⚙️ 外部命令 (44)
🌐 网络访问 (11)
📁 文件系统访问 (3)
质量评分
你能构建什么
除錯生產環境掛起
診斷 FastAPI 應用程式在作用中 SSE 串流連線期間為何停止回應健康檢查
分診事件循環問題
使用 py-spy 捕獲阻塞堆疊框架並識別 ThreadPoolExecutor.shutdown 作為根本原因
修復串流斷開
實作非阻塞執行器模式,使中止串流請求不會凍結後端
试试这些提示
我的 FastAPI 應用程式停止回應請求。我該如何使用 py-spy 找出什麼阻塞了事件循環?
我捕獲了 py-spy 傾印並在框架中看到 ThreadPoolExecutor.shutdown。這是什麼意思?我該如何修復?
幫助我重構我的 stream.py 以使用非阻塞 ThreadPoolExecutor 模式,該模式在關閉時不會阻塞。
我已經應用了非阻塞執行器模式。我該如何使用 py-spy 驗證事件循環不再被阻塞?
最佳实践
- 始終在非同步上下文中對執行器使用 shutdown(wait=False, cancel_futures=True) 以防止事件循環阻塞。
- 在重啟服務前捕獲 py-ssy 堆疊以保留阻塞操作的證據。
- 在開發期間測試串流中止場景,以在生產部署前及早發現掛起問題。
避免
- 在非同步程式碼中使用 'with ThreadPoolExecutor()' 作為上下文管理器——它會調用 shutdown(wait=True) 造成阻塞。
- 在非同步函數中等待 executor.shutdown()——這會同步阻塞事件循環。
- 在不取消待處理 futures 的情況下忽略用戶端斷開連線——它們可能持有資源並導致資源洩漏。