Órbita
- Código
- Arquitetura
- Dados
- Integração
- Resiliência
Quando usar
Domínios independentes com times e ciclos de deploy próprios
Órbita
Quando usar
Domínios independentes com times e ciclos de deploy próprios
Problema
Monólito que trava deploy e escala de times
Quando usar
Domínios independentes com times e ciclos de deploy próprios
microservices
Divide o sistema em serviços pequenos, autônomos e implantados de forma independente.
Planta de sequência
Reproduzir passo a passoComo funciona
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
README.mdpattern/architecture/microservices
thiagoeti/pattern/microservicesUm 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.
Transferência de R$ 3.000,00: payments (PostgreSQL) chama fraud (MariaDB) e accounts (PostgreSQL).
payments grava pending antes de chamar alguémfraud e accounts por HTTP com timeout e x-correlation-idfraud e accounts aplicam cada transferId uma vezpayments fecha no próprio ledgersrc/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 (## Executar, $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 = ## Executar", [body.sourceAccountId, body.amountCents]);
await client.query("UPDATE accounts SET balance_cents = balance_cents + $2 WHERE id = ## Executar", [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 (## Executar, $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 = ## Executar", [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 (## Executar, '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(## Executar) 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()]);
./docker.sh
until docker exec microservices-accounts-db pg_isready -h 127.0.0.1 -U postgres -d accounts_db >/dev/null 2>&1; do sleep 1; done
until docker exec microservices-payments-db pg_isready -h 127.0.0.1 -U postgres -d payments_db >/dev/null 2>&1; do sleep 1; done
until docker exec microservices-fraud-db healthcheck.sh --connect --innodb_initialized >/dev/null 2>&1; do sleep 1; done
bun install
bun run demo
docker rm -f microservices-accounts-db microservices-payments-db microservices-fraud-db
Saída: 200 com status completed e o correlationId; saldos finais Alice R$ 77000.00 e Bruno R$ 3500.00.
| Vantagem | Desvantagem |
|---|---|
| Deploy, escala e banco independentes | Timeout, retry e idempotência obrigatórios |
| Times autônomos | Mais infraestrutura e observabilidade |