【FastAPI】uvloop × asyncpg で構築する毎秒数万リクエストを捌く超高スループット非同期パイプライン
PythonのWebアプリケーションフレームワークにおいて、FastAPIは標準的な選択肢として確固たる地位を確立しています。しかし、毎秒数万リクエストを超える超高並行(High Concurrency)環境や、低レイテンシ(Low Latency)が強く求められるリアルタイムデータパイプラインの構築においては、標準の asyncio イベントループや一般的なORMのオーバーヘッドがボトルネックとなるケースが存在します。
本記事では、Pythonのパフォーマンスを限界まで引き出すため、uvloop と asyncpg を組み合わせた完全非同期アーキテクチャの設計パターンおよび本番環境適用コードを解説します。
コンポーネント選定の技術的アプローチ
-
uvloop: C言語(libuv)で記述された
asyncioの代替イベントループ。標準ループと比較して 2〜4倍のパフォーマンス を発揮し、Node.js や Go に匹敵する Concurrency を実現します。 - asyncpg: PostgreSQL 向けの最高速非同期ドライバー。DB-API / ORM 抽象化層をバイパスし、PostgreSQLのフロントエンド/バックエンドプロトコル(Binary Protocol)を直接操作することで、SQLAlchemy や psycopg2/3 に対して圧倒的なスループットを誇ります。
-
FastAPI (
lifespan): リソースの起動・停止を厳密に制御するコンテキストマネージャを活用し、 Connection Pool の生成と安全なシャットダウンを保証します。
システムアーキテクチャ (ASCII Architecture Diagram)
以下は、Client からデータストアに到達するまでのエンドツーエンド非同期パイプラインの構成図です。データフローにおけるコンテキストスイッチを最小化する設計を行っています。
+-------------------------------------------------------------------+
| Client Traffic |
+-------------------------------------------------------------------+
|
v (HTTP/1.1, HTTP/2 Payload)
+-------------------------------------------------------------------+
| FastAPI Application Layer |
| |
| +-------------------------------------------------------------+ |
| | Uvicorn Web Engine with uvloop (C-based libuv) | |
| +-------------------------------------------------------------+ |
| | |
| v (Event-driven Concurrency) |
| +-------------------------------------------------------------+ |
| | Non-blocking Async Request Handlers (Pydantic v2 Validation) | |
| +-------------------------------------------------------------+ |
| | |
| +------------------+------------------+ |
| | | |
| v v |
| +-----------------------+ +-----------------------+ |
| | asyncpg Connection | | Async In-Memory Queue | |
| | Pool Manager | | (Background Pipeline) | |
| +-----------------------+ +-----------------------+ |
+--------------|-------------------------------------|--------------+
| (Postgres Binary Protocol) |
v v
+----------------------------+ +----------------------------+
| PostgreSQL Data Cluster | | Async Worker / Data Sink |
+----------------------------+ +----------------------------+
実動コード実装 (Production-Ready Implementation)
以下は、uvloop の全域適用、asyncpg のコネクションプール管理、Pydantic v2 による超高速バリデーション、バッチインサート処理を包含する実装コードです。
import asyncio
from contextlib import asynccontextmanager
import json
import os
import sys
from typing import List, Optional
from fastapi import FastAPI, HTTPException, status
from pydantic import BaseModel, Field
import asyncpg
import uvloop
# ----------------------------------------------------------------------
# 1. Global Event Loop Initialization (Must be called before loop creation)
# ----------------------------------------------------------------------
uvloop.install()
# Database DSN Config
DATABASE_URL = os.getenv(
"DATABASE_URL",
"postgresql://postgres:postgres@localhost:5432/high_perf_db"
)
# ----------------------------------------------------------------------
# 2. Data Models (Pydantic V2)
# ----------------------------------------------------------------------
class EventIngestPayload(BaseModel):
user_id: str = Field(..., example="usr_998234")
event_type: str = Field(..., example="click_banner")
metadata: dict = Field(default_factory=dict, example={"campaign_id": "cmp_001"})
class IngestResponse(BaseModel):
status: str
inserted_count: int
# ----------------------------------------------------------------------
# 3. Application State & Lifespan Context Manager
# ----------------------------------------------------------------------
class AppState:
pool: Optional[asyncpg.Pool] = None
state = AppState()
@asynccontextmanager
async def lifespan(app: FastAPI):
"""
FastAPI Lifespan Context: Setup and teardown resources securely.
"""
# Startup: Initialize high-performance asyncpg connection pool
try:
state.pool = await asyncpg.create_pool(
dsn=DATABASE_URL,
min_size=20, # Minimum active connections
max_size=100, # Maximum concurrent connections
max_queries=50000, # Recycle connection after N queries
max_inactive_connection_lifetime=300.0,
command_timeout=10.0,
)
print("INFO: uvloop initialized and asyncpg Pool allocated successfully.")
except Exception as e:
print(f"FATAL: Database connection pool allocation failed: {e}", file=sys.stderr)
raise e
yield
# Shutdown: Safely close all active connection pools
if state.pool:
await state.pool.close()
print("INFO: asyncpg Pool released gracefully.")
# ----------------------------------------------------------------------
# 4. FastAPI Application Definition
# ----------------------------------------------------------------------
app = FastAPI(
title="High-Throughput Async Ingestion Pipeline",
version="1.0.0",
lifespan=lifespan
)
# ----------------------------------------------------------------------
# 5. Pipeline Endpoints
# ----------------------------------------------------------------------
@app.get("/healthz", status_code=status.HTTP_200_OK)
async def health_check():
"""
Liveness probe endpoint. Checks connection pool readiness.
"""
if state.pool is None:
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="Database pool not initialized"
)
return {"status": "ready", "event_loop": "uvloop"}
@app.post(
"/api/v1/events/batch",
response_model=IngestResponse,
status_code=status.HTTP_201_CREATED
)
async def ingest_batch_events(payloads: List[EventIngestPayload]):
"""
Batch ingests high-volume telemetry events into PostgreSQL using binary protocol.
"""
if not state.pool:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Connection pool uninitialized"
)
# Pre-process records into tuple for asyncpg executemany/copy execution
records = [
(item.user_id, item.event_type, json.dumps(item.metadata))
for item in payloads
]
# Efficient binary protocol batch insert statement
query = """
INSERT INTO user_events (user_id, event_type, metadata)
VALUES ($1, $2, $3::jsonb);
"""
try:
async with state.pool.acquire() as conn:
# Execute inside a non-blocking transaction block
async with conn.transaction():
await conn.executemany(query, records)
except asyncpg.PostgresError as db_err:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"Database execution error: {str(db_err)}"
)
return IngestResponse(status="inserted", inserted_count=len(records))
超高パフォーマンスを引き出すチューニング原則
1. Uvicorn Worker プロセスの最適化
本番環境で実行する際は、CPUsのコア数に応じたワーカープロセスの並列化を実施します。
uvicorn main:app \
--host 0.0.0.0 \
--port 8000 \
--workers 4 \
--loop uvloop \
--http h11 \
--no-access-log
※ --no-access-log フラグを有効化することで、ログ出力時の I/O ボトルネックを削除し、スループットを最大 15〜20% 向上させることが可能です。
2. コネクションプール(min_size / max_size)の最適化
asyncpg のコネクション取得待ちが発生しないよう、システムの同時接続数(Concurrency)に合わせてチューニングします。
- min_size: 起動時に常駐させるTCP接続数。ハンドシェイクのオーバーヘッドを無くすため、ある程度高めに設定(例: 20)。
-
max_size: データベース側の
max_connectionsパラメータとワーカープロセス数(workers)の積を超えないよう制限をかけます。
まとめ
Python における非同期処理の速度限界は、標準ライブラリの選定とアーキテクチャの統一によって大きく打破できます。uvloop の C 言語層イベント駆動処理と asyncpg のバイナリプロトコル直接通信を組み合わせることで、従来の同期型アプローチや不要な ORM レイヤーに由来するオーバーヘッドを排除し、最高水準のスループットを維持するパイプラインを構築可能です。
システムエンジニアリングにおける最適化の極致を目指すプログラミングにおいて、本構成は強力なリファレンスとなります。
Written by Aman Kumar (https://github.com/aman179102)