Pular para o conteúdo

Microsserviços

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.

passos
4
arquivos
9
testes
0
tecnologias
9

Cenário

Transferência de R$ 3.000,00: payments (PostgreSQL) chama fraud (MariaDB) e accounts (PostgreSQL).

Planta

Sequência
8/8
POST /transfers1INSERT transfer pending2POST /analyses (timeout, x-correlation-id)3INSERT IGNORE por transfer_id4aprovado5POST /transfers (mesmo transfer_id)6idempotência, débito e crédito7UPDATE completed8Clientepayments-servicepayments-db PostgreSQLfraud-servicefraud-db MariaDBaccounts-serviceaccounts-db PostgreSQL
8

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

  1. 1

    payments grava pending antes de chamar alguém

  2. 2

    Chama fraud e accounts por HTTP com timeout e x-correlation-id

  3. 3

    fraud e accounts aplicam cada transferId uma vez

  4. 4

    Nenhum serviço toca banco alheio; payments fecha no próprio ledger

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

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

./

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

sql/

  • 01_accounts.sqlschema
  • 01_fraud.sqlschema
  • 01_payments.sqlschema

src/

  • demo.tsdemo

Executar com Docker

  1. ./docker.sh
  2. 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
  3. 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
  4. until docker exec microservices-fraud-db healthcheck.sh --connect --innodb_initialized >/dev/null 2>&1; do sleep 1; done
  5. bun install# dependências
  6. bun run demo# roda o cenário
  7. 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.

Requisitos
BunDocker
Sobe junto
MariaDBPostgreSQL

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

Linhas de TypeScript
59
Tipo
B — dois ou mais serviços (docker compose)

Domínio financeiro

  • Crédito/Empréstimo

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

  • accounts
  • account_transfers

sql/01_fraud.sql

  • fraud_analyses

sql/01_payments.sql

  • transfers

Variáveis de ambiente

MICROSERVICES_ACCOUNTS_DATABASE_URL
postgres://postgres:postgres@localhost:5432/accounts_db
accounts-service: its own PostgreSQL.
MICROSERVICES_FRAUD_DATABASE_URL
mysql://fraud:fraud@localhost:3306/fraud_db
fraud-service: its own MariaDB.
MICROSERVICES_PAYMENTS_DATABASE_URL
postgres://postgres:postgres@localhost:5433/payments_db
payments-service: its own PostgreSQL.

Trilhapasso 4 de 6

Do monólito aos serviços

  1. 1Arquitetura Monolítica
  2. 2Monólito Modular
  3. 3Strangler Fig
  4. 4Microsserviços
  5. 5Database per Service
  6. 6API Gateway

Parecidos

Por que se relacionam

Teste rápido

Qual é o próximo passo depois de Microsserviços?

Próximo projeto, ArquiteturaMonólito Modular
Esc

↑ ↓ navegarEnter abrir239 resultados