Pular para o conteúdo

Connection Pool

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.

passos
4
arquivos
7
testes
0
tecnologias
5

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ência
6/6
alt[sucesso][erro]transferência1pool.connect() e BEGIN2lock em ordem de id, débito, crédito3COMMIT4ROLLBACK5client.release() no finally6DemotransactionExecutePostgreSQL
6

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

  1. 1

    pg.Pool com max, idleTimeoutMillis, connectionTimeoutMillis e handler de error

  2. 2

    transactionExecute: BEGIN, callback, COMMIT; ROLLBACK no erro

  3. 3

    client.release() no finally

  4. 4

    Contas travadas em ordem de id; saldo conferido sob o lock

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

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

./

  • .env.exampleinfra
  • docker.shinfra
  • package.jsoninfra
  • README.md
  • tsconfig.jsoninfra

sql/

  • 01_schema.sqlschema

src/

  • demo.tsdemo

Executar com Docker

  1. ./docker.sh
  2. until docker exec connection-pool-db pg_isready -h 127.0.0.1 -U postgres >/dev/null 2>&1; do sleep 1; done
  3. bun install# dependências
  4. bun run demo# roda o cenário
  5. docker rm -f connection-pool-db

Saí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.

Requisitos
BunDocker
Sobe junto
PostgreSQL

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

Linhas de TypeScript
46
Tipo
B — um serviço (docker.sh)

Domínio financeiro

  • Crédito/Empréstimo
  • Conta corrente
  • Saldo

Padrões do catálogo que implementa

Infraestrutura

  • PostgreSQLbanco relacional

    postgres:16-alpine:5432

Banco

sql/01_schema.sql

  • accounts

Variáveis de ambiente

CONNECTION_POOL_DATABASE_URL
postgres://postgres:postgres@localhost:5432/pg_pool_manager
Accounts database.

Parecidos

Por que se relacionam

Teste rápido

Qual destes combina com Connection Pool?

Próximo projeto, Dados & PersistênciaCQRS (Command Query Responsibility Segregation)
Esc

↑ ↓ navegarEnter abrir239 resultados