0Pricing
MCP Academy · Aula

Agrupar conexões no ciclo de vida

Reutilize clientes de DB e HTTP entre as solicitações.

Agrupar conexões no ciclo de vida é uma aula grátis de MCP Academy no CoddyKit. Esta é a aula 3 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de MCP Academy, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de MCP Academy inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

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. 🎯

Perguntas Frequentes

A aula “Agrupar conexões no ciclo de vida” é grátis?

Sim — o texto completo de “Agrupar conexões no ciclo de vida” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de MCP Academy, atualize para CoddyKit PRO. O curso de MCP Academy inclui 4 aulas no total.

O que vou aprender em “Agrupar conexões no ciclo de vida”?

Reutilize clientes de DB e HTTP entre as solicitações. Você pratica MCP Academy com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar MCP Academy?

Nenhuma experiência prévia é necessária. MCP Academy no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 3 de 4.

Quanto tempo leva a aula “Agrupar conexões no ciclo de vida”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de MCP Academy?

Sim. Cada aula de MCP Academy inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Expor consultas SQL com segurança
  2. Transformar uma API REST em ferramentas
  3. Agrupar conexões no ciclo de vida
  4. Armazenar em cache e limitar a taxa dos serviços upstream
← Voltar para MCP Academy