backend-hang-debug
ニュース配信ルートでFastAPIが停止する原因を、py-spyで特定し、ThreadPoolExecutorのシャットダウンを妨げないパターンを適用して、問題を診断・修正するSkill。
📜 元の英語説明(参考)
Diagnose and fix FastAPI hangs caused by blocking ThreadPoolExecutor shutdown in the news stream route; includes py-spy capture and non-blocking executor pattern.
🇯🇵 日本人クリエイター向け解説
ニュース配信ルートでFastAPIが停止する原因を、py-spyで特定し、ThreadPoolExecutorのシャットダウンを妨げないパターンを適用して、問題を診断・修正するSkill。
※ jpskill.com 編集部が日本のビジネス現場向けに補足した解説です。Skill本体の挙動とは独立した参考情報です。
下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o backend-hang-debug.zip https://jpskill.com/download/17502.zip && unzip -o backend-hang-debug.zip && rm backend-hang-debug.zip
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/17502.zip -OutFile "$d\backend-hang-debug.zip"; Expand-Archive "$d\backend-hang-debug.zip" -DestinationPath $d -Force; ri "$d\backend-hang-debug.zip"
完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。
💾 手動でダウンロードしたい(コマンドが難しい人向け)
- 1. 下の青いボタンを押して
backend-hang-debug.zipをダウンロード - 2. ZIPファイルをダブルクリックで解凍 →
backend-hang-debugフォルダができる - 3. そのフォルダを
C:\Users\あなたの名前\.claude\skills\(Win)または~/.claude/skills/(Mac)へ移動 - 4. Claude Code を再起動
⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。
🎯 このSkillでできること
下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。
📦 インストール方法 (3ステップ)
- 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
- 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
- 3. 展開してできたフォルダを、ホームフォルダの
.claude/skills/に置く- · macOS / Linux:
~/.claude/skills/ - · Windows:
%USERPROFILE%\.claude\skills\
- · macOS / Linux:
Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。
詳しい使い方ガイドを見る →- 最終更新
- 2026-05-18
- 取得日時
- 2026-05-18
- 同梱ファイル
- 1
📖 Skill本文(日本語訳)
※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。
バックエンドハングのデバッグ
目的
- SSEニュースストリームにおける同期executorのシャットダウンが原因で、FastAPIアプリが応答しなくなる(例:
curl http://localhost:8000/がタイムアウトする)イベントループのハングを検出し、解決します。 py-spyを使用してライブスタックをキャプチャし、ブロッキングコードを特定するための、再現可能なトリアージフローを提供します。
範囲
- バックエンド:
backend/app/api/routes/stream.py(ニュースストリーム),backend/app/services/rss_ingestion.py(RSSワーカー), 起動プロセス。 - ツール: ライブスタックダンプ用の
py-spy; スモークテスト用のタイムアウト付きcurl。
クイックトリアージ
- ハングの再現:
curl -m 5 http://localhost:8000/およびcurl -m 5 http://localhost:8000/healthを実行し、タイムアウトに注意してください。 - プロセスチェック:
ss -tlnp | grep 8000でリスナーを確認します。ls /proc/$(pgrep -f "uvicorn app.main")/fd | wc -lでFDリークを除外します。 - スタックキャプチャ (バックエンドのvenv内):
uv pip install py-spyを実行後、sudo /home/bender/classwork/Thesis/backend/.venv/bin/py-spy dump --pid $(pgrep -f "uvicorn app.main")を実行します (マルチプロセスの場合はワーカーのpidも)。api/routes/stream.pyのフレームでThreadPoolExecutor.shutdownを探します。
修正パターン (ノンブロッキングexecutor)
event_generator内の同期コンテキストマネージャーwith ThreadPoolExecutor(...):を、長寿命のexecutorと明示的な ノンブロッキング シャットダウンに置き換えます。- コンテキストマネージャーの外でexecutorを作成します。
- クライアントが切断されたら、シャットダウンを待機する代わりに、保留中のfutureをキャンセルします。
finallyで、executor.shutdown(wait=False, cancel_futures=True)を呼び出します。
- 理由: コンテキストマネージャーは
shutdown(wait=True)を呼び出し、RSSワーカーのスレッドがネットワークI/Oでハングすると、イベントループをブロックします。
実装手順
backend/app/api/routes/stream.pyで ストリームexecutorの使用法を更新 します。executor = concurrent.futures.ThreadPoolExecutor(max_workers=5)をインスタンス化します。loop.run_in_executor(executor, _process_source_with_debug, ...)を介して作業をディスパッチします。- 切断時に、保留中のfutureを
cancel()します。 finallyで、executor.shutdown(wait=False, cancel_futures=True)を実行します。
- RSS executorは現状維持 (
rss_ingestion.py) とします。これはバックグラウンドスレッドで実行されるためですが、リクエストのタイムアウトが妥当な範囲内(現在はRSSrequests.getごとに60秒)であることを確認してください。 - 再テスト:
- uvicornを再起動します。
curl -m 5 http://localhost:8000/healthが応答するはずです。 - ストリームリクエストを開始し、クライアントを中断します。サーバーは応答性を維持する必要があります。
py-spy dumpを再実行して、メインスレッドにThreadPoolExecutor.shutdown(wait=True)フレームがないことを確認します。
- uvicornを再起動します。
検証チェックリスト
- [ ]
curl -m 5 http://localhost:8000/が応答を返します (ハングしない)。 - [ ]
curl -m 5 http://localhost:8000/healthが成功します。 - [ ]
/news/streamを中断しても、後続のリクエストがフリーズしません。 - [ ]
py-spy dumpは、イベントループがThreadPoolExecutor.shutdownでブロックされていないことを示しています。 - [ ] バックエンドがストリームでビジーの間、フロントエンドがルート/ヘルスを待機して停止することがなくなりました。
注記と将来の強化
- 低速なハンドラーで高速に失敗するように、リクエストタイムアウトミドルウェアの追加を検討してください。
- 長寿命のスレッドを減らすために、ソースごとのネットワークタイムアウトと、RSSフィードのより短いリトライを追加します。
- マルチワーカーのuvicornを使用している場合は、ハングを診断するときに、各ワーカーのpidで
py-spyを実行します。
📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開
Backend Hang Debug
Purpose
- Detect and resolve event-loop hangs where the FastAPI app stops responding (e.g.,
curl http://localhost:8000/times out) due to synchronous executor shutdown in the SSE news stream. - Provide a repeatable triage flow using
py-spyto capture live stacks and pinpoint blocking code.
Scope
- Backend:
backend/app/api/routes/stream.py(news stream),backend/app/services/rss_ingestion.py(RSS workers), startup processes. - Tooling:
py-spyfor live stack dumps;curlwith timeouts for smoke tests.
Quick Triage
- Reproduce hang:
curl -m 5 http://localhost:8000/andcurl -m 5 http://localhost:8000/health; note timeouts. - Process check:
ss -tlnp | grep 8000to confirm listener;ls /proc/$(pgrep -f "uvicorn app.main")/fd | wc -lto rule out FD leak. - Stack capture (inside backend venv):
uv pip install py-spythensudo /home/bender/classwork/Thesis/backend/.venv/bin/py-spy dump --pid $(pgrep -f "uvicorn app.main")(and worker pid if multiprocess). Look forThreadPoolExecutor.shutdowninapi/routes/stream.pyframes.
Fix Pattern (non-blocking executor)
- Replace synchronous context manager
with ThreadPoolExecutor(...):insideevent_generatorwith a long-lived executor plus explicit non-blocking shutdown:- Create executor outside the context manager.
- On client disconnect, cancel pending futures instead of awaiting shutdown.
- In
finally, callexecutor.shutdown(wait=False, cancel_futures=True).
- Rationale: context manager calls
shutdown(wait=True), blocking the event loop if RSS worker threads hang on network I/O.
Implementation Steps
- Update stream executor usage in
backend/app/api/routes/stream.py:- Instantiate
executor = concurrent.futures.ThreadPoolExecutor(max_workers=5). - Dispatch work via
loop.run_in_executor(executor, _process_source_with_debug, ...). - On disconnect,
cancel()pending futures. - In
finally,executor.shutdown(wait=False, cancel_futures=True).
- Instantiate
- Keep RSS executor as-is (
rss_ingestion.py) since it runs in background threads, but ensure request timeouts remain reasonable (currently 60s per RSSrequests.get). - Retest:
- Restart uvicorn;
curl -m 5 http://localhost:8000/healthshould respond. - Start a stream request and abort the client; server must stay responsive.
- Re-run
py-spy dumpto verify noThreadPoolExecutor.shutdown(wait=True)frames in main thread.
- Restart uvicorn;
Verification Checklist
- [ ]
curl -m 5 http://localhost:8000/returns a response (no hang). - [ ]
curl -m 5 http://localhost:8000/healthsucceeds. - [ ] Aborting
/news/streamdoes not freeze subsequent requests. - [ ]
py-spy dumpshows event loop not blocked onThreadPoolExecutor.shutdown. - [ ] Frontend no longer stalls waiting on root/health while backend is busy with streams.
Notes & Future Hardening
- Consider adding request timeout middleware to fail fast on slow handlers.
- Add per-source network timeouts and shorter retries for RSS feeds to reduce long-lived threads.
- If multi-worker uvicorn is used, run
py-spyon each worker pid when diagnosing hangs.