Lifespanで接続をプールする
リクエスト間でDBクライアントとHTTPクライアントを再利用します。
「Lifespanで接続をプールする」はCoddyKit上の無料MCP Academyレッスンです。 これはレッスン3/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはMCP Academy学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 MCP Academyコースには全4レッスンが含まれています。
このレッスンの一部はまだ翻訳されておらず、英語で表示されています。
Connecting Costs Time
Opening a fresh database or HTTP connection on every call is slow. The handshake adds latency that piles up fast under load. 🐢
Reuse with a Pool
A connection pool keeps a set of live connections ready, lending one per request and taking it back when the work is done.
Build the Pool at Startup
The lifespan hook is the perfect home: create the pool once when the server boots, before any tool runs.
@asynccontextmanager
async def lifespan(server):
pool = await create_pool(DSN)
yield {"pool": pool}Yield It as Shared State
Whatever you yield from the lifespan becomes shared context, so every handler reaches the same pool without rebuilding it.
Reach It via Context
Inside a tool, grab the pool from the request context rather than opening your own connection each time.
pool = ctx.request_context.lifespan_context["pool"]Borrow, Use, Return
Acquire a connection from the pool, run your query, and let it return automatically. The with block handles checkout and release.
async with pool.acquire() as conn:
rows = await conn.fetch(sql)Cap the Pool Size
Set a max size so the pool never opens more connections than your database can handle, even when calls flood in.
pool = await create_pool(DSN, max_size=10)Share One HTTP Client Too
The same idea fits HTTP: build one httpx client in the lifespan and reuse it so connections stay warm and pooled.
client = httpx.AsyncClient()
yield {"http": client}Pools Are Thread-Safe
A good async pool is built for concurrency, safely handing connections to many requests running at the same time.
Watch for Leaks
Always release what you borrow. A connection you forget to return is a leak that slowly starves the pool until calls stall.
Close It on Shutdown
After the lifespan yield, close the pool so connections drain cleanly when the server stops.
yield {"pool": pool}
await pool.close()Quick Check
Where do you build a connection pool?
Recap: Pooling
You pooled connections in the lifespan: build once, share via context, borrow per call, and close on shutdown. Next, cache and rate-limit. 🎯
よくある質問
「Lifespanで接続をプールする」レッスンは無料ですか?
はい。「Lifespanで接続をプールする」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、MCP Academyコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 MCP Academyコースには全4レッスンが含まれています。
「Lifespanで接続をプールする」で何を学びますか?
リクエスト間でDBクライアントとHTTPクライアントを再利用します。 ブラウザで直接実行するハンズオンコードでMCP Academyを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
MCP Academyを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのMCP Academyは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン3/4です。
「Lifespanで接続をプールする」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このMCP Academyレッスンでコードを書いて実行できますか?
はい。すべてのMCP Academyレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- SQLクエリを安全に公開する
- REST APIをツールとしてラップする
- Lifespanで接続をプールする
- 上流サービスをキャッシュしてレート制限する