pattern/architecture/microservices
- AbortSignal
- Bun
- ElysiaJS
- MariaDB
- PostgreSQL
- TypeScript
- mysql2
- node-postgres
- Docker
Um serviço por contexto de negócio, com banco, deploy e escala próprios, falando só por API; toda chamada com timeout e todo efeito idempotente.
pattern/architecture/microservices
Cenário
Transferência de R$ 3.000,00: payments (PostgreSQL) chama fraud (MariaDB) e accounts (PostgreSQL).
Planta
Sequência8 passos — reproduza para seguir o fluxo
Como funciona
4passos
Um serviço por contexto de negócio, com banco, deploy e escala próprios, falando só por API
Esconde cada passo: lembre antes de tocar para revelar.
Vocabulário compartilhado
payments grava pending antes de chamar alguém
Chama fraud e accounts por HTTP com timeout e x-correlation-id
fraud e accounts aplicam cada transferId uma vez
Nenhum serviço toca banco alheio; payments fecha no próprio ledger
Trade-offs
O que se ganha, o que se paga
Vantagens
Deploy, escala e banco independentes
Times autônomos
Custos
Timeout, retry e idempotência obrigatórios
Mais infraestrutura e observabilidade
Código
pattern/architecture/microservices
9 arquivos./
sql/
src/
Executar com Docker
./docker.shuntil docker exec microservices-accounts-db pg_isready -h 127.0.0.1 -U postgres -d accounts_db >/dev/null 2>&1; do sleep 1; doneuntil docker exec microservices-payments-db pg_isready -h 127.0.0.1 -U postgres -d payments_db >/dev/null 2>&1; do sleep 1; doneuntil docker exec microservices-fraud-db healthcheck.sh --connect --innodb_initialized >/dev/null 2>&1; do sleep 1; donebun install# dependênciasbun run demo# roda o cenáriodocker rm -f microservices-accounts-db microservices-payments-db microservices-fraud-dbSaída: 200 com status completed e o correlationId; saldos finais Alice R$ 77000.00 e Bruno R$ 3500.00.
Código
src/demo.ts// Demo: payments orchestrates a transfer over fraud (MariaDB) and accounts (PostgreSQL), each its own service and database, only HTTP between them.
import { Elysia, t } from "elysia";
import mysql from "mysql2/promise";
import pg from "pg";
const poolAccounts = new pg.Pool({ connectionString: Bun.env.MICROSERVICES_ACCOUNTS_DATABASE_URL ?? "postgres://postgres:postgres@localhost:5432/accounts_db" });
const poolFraud = mysql.createPool({ uri: Bun.env.MICROSERVICES_FRAUD_DATABASE_URL ?? "mysql://fraud:fraud@localhost:3306/fraud_db" });
const poolPayments = new pg.Pool({ connectionString: Bun.env.MICROSERVICES_PAYMENTS_DATABASE_URL ?? "postgres://postgres:postgres@localhost:5433/payments_db" });
const schemaTransfer = t.Object({ transferId: t.String(), sourceAccountId: t.String(), destinationAccountId: t.String(), amountCents: t.Integer({ minimum: 1 }) });
const FRAUD_LIMIT_CENTS = 5_000_000;
const SERVICE_TIMEOUT_MS = 800;
// fraud-service: scores the transfer and keeps one analysis per transfer id in its own MariaDB.
const fraud = new Elysia().post("/analyses", async ({ body, headers }) => {
const approved = body.amountCents <= FRAUD_LIMIT_CENTS;
await poolFraud.query("INSERT IGNORE INTO fraud_analyses (transfer_id, amount_cents, approved, risk, correlation_id) VALUES (?, ?, ?, ?, ?)", [body.transferId, body.amountCents, approved, approved ? "low" : "high", headers["x-correlation-id"] ?? "none"]);
return { approved };
}, { body: schemaTransfer }).listen(0);
// accounts-service: the only writer of balances; the transfer id is its idempotency key, so a retry never moves money twice.
const accounts = new Elysia().post("/transfers", async ({ body }) => {
const client = await poolAccounts.connect();
try {
await client.query("BEGIN");
const { rowCount } = await client.query("INSERT INTO account_transfers (transfer_id, source_account_id, destination_account_id, amount_cents) VALUES ($1, $2, $3, $4) ON CONFLICT DO NOTHING", [body.transferId, body.sourceAccountId, body.destinationAccountId, body.amountCents]);
if (rowCount === 0) {
await client.query("ROLLBACK");
return { applied: false };
}
await client.query("UPDATE accounts SET balance_cents = balance_cents - $2 WHERE id = $1", [body.sourceAccountId, body.amountCents]);
await client.query("UPDATE accounts SET balance_cents = balance_cents + $2 WHERE id = $1", [body.destinationAccountId, body.amountCents]);
await client.query("COMMIT");
return { applied: true };
} catch (error) {
await client.query("ROLLBACK");
throw error;
} finally {
client.release();
}
}, { body: schemaTransfer }).listen(0);
// Every remote call has a timeout and carries the correlation id: the network can fail mid-operation, and one id finds the whole transfer.
const serviceCall = (port: number, path: string, body: object, correlationId: string) =>
fetch(`http://localhost:${port}${path}`, { method: "POST", headers: { "content-type": "application/json", "x-correlation-id": correlationId }, body: JSON.stringify(body), signal: AbortSignal.timeout(SERVICE_TIMEOUT_MS) }).then((response) => response.json() as Promise<{ approved?: boolean }>);
// payments-service: records the transfer before any remote call, so its ledger always knows where the transfer stopped.
const payments = new Elysia().post("/transfers", async ({ body }) => {
const transfer = { transferId: crypto.randomUUID(), ...body };
const correlationId = crypto.randomUUID();
await poolPayments.query("INSERT INTO transfers (id, source_account_id, destination_account_id, amount_cents, status, correlation_id) VALUES ($1, $2, $3, $4, 'pending', $5)", [transfer.transferId, body.sourceAccountId, body.destinationAccountId, body.amountCents, correlationId]);
const { approved } = await serviceCall(fraud.server!.port!, "/analyses", transfer, correlationId);
if (approved) await serviceCall(accounts.server!.port!, "/transfers", transfer, correlationId);
const status = approved ? "completed" : "blocked";
await poolPayments.query("UPDATE transfers SET status = $2, updated_at = now() WHERE id = $1", [transfer.transferId, status]);
return { status, correlationId };
}, { body: t.Object({ sourceAccountId: t.String(), destinationAccountId: t.String(), amountCents: t.Integer({ minimum: 1 }) }) });
const suffix = Date.now().toString(36).toUpperCase();
await poolAccounts.query("INSERT INTO accounts (id, holder_name, balance_cents) VALUES ($1, 'Alice Ferreira', 8000000), ($2, 'Bruno Martins', 50000)", [`CC-A-${suffix}`, `CC-B-${suffix}`]);
const response = await payments.handle(new Request("http://localhost/transfers", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ sourceAccountId: `CC-A-${suffix}`, destinationAccountId: `CC-B-${suffix}`, amountCents: 300_000 }) }));
console.log(` [PAYMENTS] R$ 3000.00 Alice → Bruno → ${response.status} ${await response.text()}`);
const { rows } = await poolAccounts.query<{ id: string; balance_cents: string }>("SELECT id, balance_cents FROM accounts WHERE id = ANY($1) ORDER BY id", [[`CC-A-${suffix}`, `CC-B-${suffix}`]]);
console.log(` [ACCOUNTS] ${rows.map((row) => `${row.id} R$ ${(Number(row.balance_cents) / 100).toFixed(2)}`).join(", ")}`);
await Promise.all([fraud.stop(true), accounts.stop(true)]);
await Promise.all([poolAccounts.end(), poolPayments.end(), poolFraud.end()]);
Nível
avançado
11/13
Domínio financeiro
Padrões do catálogo que implementa
Infraestrutura
PostgreSQLbanco relacional
postgres:16-alpine:5432
PostgreSQLbanco relacional
postgres:16-alpine:5433
MariaDBbanco relacional
mariadb:11:3306
Banco
sql/01_accounts.sql
sql/01_fraud.sql
sql/01_payments.sql
Variáveis de ambiente
Trilhapasso 4 de 6
Do monólito aos serviços
Parecidos
Relações
Onde ele se encaixa
Por que se relacionam
Próximo passo
Teste rápido
Qual é o próximo passo depois de Microsserviços?
Cada serviço dono dos dados. Abrir Database per Service
Seu progresso
0/157 estudados
Fica salvo só neste navegador.