pattern/persistence/connection-pool
- Bun
- PostgreSQL
- TypeScript
- node-postgres
- Docker
Um pg.Pool por processo e transação que sempre faz COMMIT ou ROLLBACK e devolve a conexão. Use em toda escrita atômica no PostgreSQL.
pattern/persistence/connection-pool
Cenário
Ao mesmo tempo, R$ 250,00 vão da ACC-001 para a ACC-002 e R$ 5.000,00 sem saldo voltam no sentido oposto: o segundo é desfeito e as conexões voltam ao pool.
Planta
Sequência6 passos — reproduza para seguir o fluxo
Como funciona
4passos
Um pg.Pool por processo e transação que sempre faz COMMIT ou ROLLBACK e devolve a conexão
Esconde cada passo: lembre antes de tocar para revelar.
Vocabulário compartilhado
pg.Pool com max, idleTimeoutMillis, connectionTimeoutMillis e handler de error
transactionExecute: BEGIN, callback, COMMIT; ROLLBACK no erro
client.release() no finally
Contas travadas em ordem de id; saldo conferido sob o lock
Trade-offs
O que se ganha, o que se paga
Vantagens
Conexões limitadas e reaproveitadas
Nenhuma conexão vaza em erro
Custos
max mal dimensionado vira fila
Transação longa segura a conexão
Código
pattern/persistence/connection-pool
7 arquivos./
sql/
src/
Executar com Docker
./docker.shuntil docker exec connection-pool-db pg_isready -h 127.0.0.1 -U postgres >/dev/null 2>&1; do sleep 1; donebun install# dependênciasbun run demo# roda o cenáriodocker rm -f connection-pool-dbSaída: R$ 250.00 de ACC-001 para ACC-002 commita; R$ 5000.00 de ACC-002 para ACC-001 faz rollback por saldo insuficiente; saldos ACC-001 R$ 750.00 e ACC-002 R$ 750.00, com as 2 conexões ociosas de volta ao pool.
Código
src/demo.ts// Demo: one pg.Pool per process and a transaction helper that always commits or rolls back and always releases the client.
import pg from "pg";
const pool = new pg.Pool({
connectionString: Bun.env.CONNECTION_POOL_DATABASE_URL ?? "postgres://postgres:postgres@localhost:5432/pg_pool_manager",
max: 10,
idleTimeoutMillis: 30_000,
connectionTimeoutMillis: 5_000,
});
// An idle client losing its connection emits on the pool: without a listener the process dies.
pool.on("error", (error) => console.error(`[POOL] idle client error: ${error.message}`));
// BEGIN → callback → COMMIT; ROLLBACK on any error; release in finally, on every exit path.
async function transactionExecute<T>(callback: (client: pg.PoolClient) => Promise<T>): Promise<T> {
const client = await pool.connect();
try {
await client.query("BEGIN");
const result = await callback(client);
await client.query("COMMIT");
return result;
} catch (error) {
await client.query("ROLLBACK");
throw error;
} finally {
client.release();
}
}
// Both rows locked in id order, so opposite transfers queue instead of deadlocking; the balance is checked under the lock.
function transferExecute(accountFrom: string, accountTo: string, amountCents: number): Promise<void> {
return transactionExecute(async (client) => {
await client.query("SELECT id FROM accounts WHERE number = ANY($1) ORDER BY id FOR UPDATE", [[accountFrom, accountTo]]);
const debit = await client.query("UPDATE accounts SET balance_cents = balance_cents - $1 WHERE number = $2 AND balance_cents >= $1", [amountCents, accountFrom]);
if (debit.rowCount !== 1) throw new Error(`insufficient funds on ${accountFrom}`);
await client.query("UPDATE accounts SET balance_cents = balance_cents + $1 WHERE number = $2", [amountCents, accountTo]);
});
}
const brl = (cents: number | string): string => `R$ ${(Number(cents) / 100).toFixed(2)}`;
const transfers = [["ACC-001", "ACC-002", 25_000], ["ACC-002", "ACC-001", 500_000]] as const;
// Opposite transfers fired together: each takes its own pooled client and both lock in the same order.
const outcomes = await Promise.allSettled(transfers.map(([accountFrom, accountTo, amountCents]) => transferExecute(accountFrom, accountTo, amountCents)));
outcomes.forEach((outcome, index) => {
const [accountFrom, accountTo, amountCents] = transfers[index]!;
const status = outcome.status === "fulfilled" ? "committed" : `rolled back (${(outcome.reason as Error).message})`;
console.log(` [TRANSFER] ${brl(amountCents)} ${accountFrom} → ${accountTo}: ${status}`);
});
const { rows } = await pool.query<{ number: string; balance_cents: string }>("SELECT number, balance_cents FROM accounts ORDER BY number");
console.log(` [BALANCE] ${rows.map((row) => `${row.number} ${brl(row.balance_cents)}`).join(" | ")}; idle clients ${pool.idleCount}/${pool.totalCount}`);
await pool.end();
Nível
intermediário
4/13
Domínio financeiro
Padrões do catálogo que implementa
Infraestrutura
PostgreSQLbanco relacional
postgres:16-alpine:5432
Banco
sql/01_schema.sql
Variáveis de ambiente
Parecidos
Por que se relacionam
Teste rápido
Qual destes combina com Connection Pool?
Um pool para o primário, outro para réplicas. Abrir Read Replicas
Seu progresso
0/157 estudados
Fica salvo só neste navegador.