1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Python】asyncio 内部構造とイベントループ最適化: 高負荷 Web サービスにおけるブロッキング検知

1
Posted at

【Python】asyncio 内部構造とイベントループ最適化: 高負荷 Web サービスにおけるブロッキング検知

はじめに (Introduction)

Python の AsyncIO は協調的マルチタスク(Cooperative Multitasking)モデルを採用しています。これは、各コルーチンが await 式で自発的に制御をイベントループに返却(Yield)することを前提としています。

もし 1 つのエンドポイントで time.sleep()、同期ファイル I/O、または計算量の多い CPU 処理(暗号化や画像リサイズなど)を実行してしまうと、イベントループ全体が停止し、その間サーバーは他の全リクエストのネットワークパケットを一切処理できなくなります。

本記事では、イベントループの内部動作メカニズムと、本番環境でブロッキングタスクを自動検知・退避させる実践的アーキテクチャを解説します。

イベントループの内部構造 (Event Loop Internals)

+--------------------+       I/O Event       +------------------------+
| Socket Ready Event | --------------------> | asyncio Epoll/Kqueue   |
+--------------------+                       +------------------------+
                                                         |
                                          Execute Ready Tasks (< 50ms)
                                                         v
+--------------------+                       +------------------------+
| ThreadPoolExecutor | <-------------------- | Slow Callback Detector |
| (CPU/Blocking I/O) |   asyncio.to_thread   | (loop.slow_callback)   |
+--------------------+                       +------------------------+

イベントループの 1 イテレーション

  1. OS の I/O 多重化 API(Linux では epoll、macOS/BSD では kqueue)を呼び出し、待機中のソケットが読み取り/書き込み可能か判定。
  2. 実行可能状態になったコールバックキュー(_ready deque)からタスクを 1 件ずつ取り出して実行。
  3. タイマーキュー(_scheduled ヒープ)から満了したタイマータスクを実行。

ブロッキング監視とスレッドオフロードの実装 (Implementation)

from __future__ import annotations

import asyncio
import logging
import time
from typing import Any
from concurrent.futures import ThreadPoolExecutor

from fastapi import FastAPI, HTTPException

logger = logging.getLogger("eventloop_monitor")
logger.setLevel(logging.WARNING)

# CPU バウンド処理専用の専用スレッドプール
cpu_executor = ThreadPoolExecutor(max_workers=8, thread_name_prefix="cpu_offload")


def heavy_cpu_computation(iterations: int) -> int:
    '''ブロッキングな計算処理 (GIL を占有)'''
    total = 0
    for i in range(iterations):
        total += (i ^ 0x5A) % 1000
    return total


app = FastAPI(title="Event Loop Watchdog Service")


@app.on_event("startup")
async def configure_event_loop_monitoring() -> None:
    loop = asyncio.get_running_loop()
    # 50ms 以上ループを占有したコールバックを警告検知
    loop.slow_callback_duration = 0.05
    logger.info("AsyncIO slow callback detector configured (threshold: 50ms)")


@app.get("/compute/bad")
async def blocking_endpoint(n: int = 5_000_000) -> dict[str, Any]:
    # アンチパターン: イベントループ上で直接 CPU 計算を実行
    # この処理中、他の接続は全てフリーズする
    start = time.perf_counter()
    result = heavy_cpu_computation(n)
    elapsed = time.perf_counter() - start
    return {"mode": "blocking_danger", "result": result, "elapsed_ms": elapsed * 1000}


@app.get("/compute/optimized")
async def non_blocking_endpoint(n: int = 5_000_000) -> dict[str, Any]:
    # ベストプラクティス: asyncio.to_thread または専用 Executor に退避
    start = time.perf_counter()
    loop = asyncio.get_running_loop()
    result = await loop.run_in_executor(cpu_executor, heavy_cpu_computation, n)
    elapsed = time.perf_counter() - start
    return {"mode": "offloaded_safe", "result": result, "elapsed_ms": elapsed * 1000}

Python 3.11+ TaskGroup による構造化並行性 (Structured Concurrency)

複数の非同期タスクを協調動作させる場合、従来の asyncio.gather() は例外発生時に他のタスクがゾンビ状態になりやすい課題がありました。Python 3.11 で導入された TaskGroup を使用することで、安全なリソース回収が保証されます。

async def parallel_fetch_pipeline(user_ids: list[int]) -> list[dict[str, Any]]:
    results: list[dict[str, Any]] = []

    async with asyncio.TaskGroup() as tg:
        tasks = [tg.create_task(fetch_user_profile(uid)) for uid in user_ids]

    # TaskGroup のブロックを抜けた時点で、全タスクの完了または例外の安全な伝播が保証される
    return [t.result() for t in tasks]

まとめ (Conclusion)

  • イベントループを 50ms 以上ブロックする処理は、マイクロ秒単位でレイテンシに悪影響を及ぼす。
  • CPU 計算や同期 I/O ライブラリは必ず loop.run_in_executor や asyncio.to_thread でオフロードする。
  • TaskGroup を採用し、構造化並行性でゾンビタスクのリークを根絶する。

Author: Aman Kumar | Systems & AI Engineer

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?