pattern/api/strangler-fig
- Bun
- ElysiaJS
- MariaDB
- PostgreSQL
- TypeScript
- mysql2
- node-postgres
- Docker
Um proxy na frente do legado passa o tráfego para o sistema novo endpoint por endpoint, com volta atrás a qualquer momento. Use para migrar sem big bang.
pattern/api/strangler-fig
Cenário
Saldo já migrado do core legado (MariaDB) para o novo (PostgreSQL); transferências seguem no legado. O cliente usa sempre o mesmo endereço.
Planta
Fluxo4 passos — reproduza para seguir o fluxo
Como funciona
4passos
Um proxy na frente do legado passa o tráfego para o sistema novo endpoint por endpoint, com volta atrás a qualquer momento
Esconde cada passo: lembre antes de tocar para revelar.
Vocabulário compartilhado
migration_routes diz o sistema de cada endpoint
Saldo vai ao core novo
Transferência vai ao legado, traduzida para o formato dele
Rollback = UPDATE na tabela
Trade-offs
O que se ganha, o que se paga
Vantagens
Rollback por endpoint
Migração incremental
Custos
Proxy a mais para operar
Dois sistemas e bancos em paralelo
Código
pattern/api/strangler-fig
8 arquivos./
sql/
src/
Executar com Docker
./docker.shuntil docker exec strangler-fig-legacy-db healthcheck.sh --connect --innodb_initialized >/dev/null 2>&1; do sleep 1; doneuntil docker exec strangler-fig-new-db pg_isready -h 127.0.0.1 -U postgres -d new_core_db >/dev/null 2>&1; do sleep 1; donebun install# dependênciasbun run demo# roda o cenáriodocker rm -f strangler-fig-legacy-db strangler-fig-new-dbSaída: saldo de 00042-1 servido pelo core new com balanceCents 485000; transferência servida pelo legacy com outcome completed.
Código
src/demo.ts// Demo: the strangler proxy in front of the legacy core; balance already moved to the new core, transfers still on legacy.
import { Elysia, t } from "elysia";
import mysql from "mysql2/promise";
import pg from "pg";
const poolLegacy = mysql.createPool({ uri: Bun.env.STRANGLER_FIG_LEGACY_DATABASE_URL ?? "mysql://app:app_password@localhost:3306/legacy_core_db" });
const poolNew = new pg.Pool({ connectionString: Bun.env.STRANGLER_FIG_NEW_DATABASE_URL ?? "postgres://postgres:postgres@localhost:5432/new_core_db" });
const LEGACY_URL = Bun.env.STRANGLER_FIG_LEGACY_URL ?? "http://localhost:4061";
const NEW_URL = Bun.env.STRANGLER_FIG_NEW_URL ?? "http://localhost:4062";
// The domain shape every client sees, whichever system served it.
type AccountBalance = { accountNumber: string; holderName: string; balanceCents: number };
// The legacy core on MariaDB: Portuguese routes and fields, reais as decimal strings.
const legacy = new Elysia()
.get("/conta/:nr/saldo", async ({ params }) => (await poolLegacy.query<mysql.RowDataPacket[]>("SELECT NR_CONTA, NM_TITULAR, CAST(VL_SALDO AS CHAR) AS VL_SALDO FROM contas WHERE NR_CONTA = ?", [params.nr]))[0][0])
.post("/transferencia", async ({ body }) => {
await poolLegacy.query("UPDATE contas SET VL_SALDO = VL_SALDO + IF(NR_CONTA = ?, -?, ?) WHERE NR_CONTA IN (?, ?)", [body.NR_ORIGEM, body.VL, body.VL, body.NR_ORIGEM, body.NR_DESTINO]);
return { CD_RETORNO: "00" };
}, { body: t.Object({ NR_ORIGEM: t.String(), NR_DESTINO: t.String(), VL: t.String() }) })
.listen(new URL(LEGACY_URL).port);
// The new core on PostgreSQL: the domain's English, integer cents.
const core = new Elysia().get("/accounts/:number/balance", async ({ params }) => (await poolNew.query<AccountBalance>(`SELECT number AS "accountNumber", holder_name AS "holderName", balance_cents::int AS "balanceCents" FROM accounts WHERE number = $1`, [params.number])).rows[0]).listen(new URL(NEW_URL).port);
// The migration dial, one row per endpoint: every proxy instance reads the same table, and rollback is one UPDATE.
const routeLoad = async (endpoint: string) => (await poolNew.query<{ mode: "legacy" | "new" }>("SELECT mode FROM migration_routes WHERE endpoint = $1", [endpoint])).rows[0]?.mode ?? "legacy";
// The only address clients call: per endpoint it picks a system and translates legacy answers to the domain shape.
const proxy = new Elysia()
.get("/accounts/:number/balance", async ({ params, set }) => {
const system = await routeLoad("balance");
set.headers["x-served-by"] = system;
if (system === "new") return (await (await fetch(`${NEW_URL}/accounts/${params.number}/balance`)).json()) as AccountBalance;
const row = (await (await fetch(`${LEGACY_URL}/conta/${params.number}/saldo`)).json()) as { NR_CONTA: string; NM_TITULAR: string; VL_SALDO: string };
return { accountNumber: row.NR_CONTA, holderName: row.NM_TITULAR, balanceCents: Number(row.VL_SALDO.replace(".", "")) };
})
.post("/transfers", async ({ body, set }) => {
set.headers["x-served-by"] = await routeLoad("transfer");
const response = await fetch(`${LEGACY_URL}/transferencia`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ NR_ORIGEM: body.accountFrom, NR_DESTINO: body.accountTo, VL: (body.amountCents / 100).toFixed(2) }) });
return { outcome: response.ok ? "completed" : "refused" };
}, { body: t.Object({ accountFrom: t.String(), accountTo: t.String(), amountCents: t.Integer({ minimum: 1 }) }) });
await poolLegacy.query("INSERT INTO contas (NR_CONTA, NM_TITULAR, VL_SALDO) VALUES ('00042-1', 'JOAO SILVA', 4850.00), ('00077-3', 'ANA LIMA', 1200.00) ON DUPLICATE KEY UPDATE VL_SALDO = VALUES(VL_SALDO)");
await poolNew.query("INSERT INTO accounts (number, holder_name, balance_cents) VALUES ('00042-1', 'JOAO SILVA', 485000) ON CONFLICT (number) DO UPDATE SET balance_cents = 485000");
await poolNew.query("UPDATE migration_routes SET mode = 'new' WHERE endpoint = 'balance'");
for (const request of [new Request("http://proxy/accounts/00042-1/balance"), new Request("http://proxy/transfers", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ accountFrom: "00042-1", accountTo: "00077-3", amountCents: 15_000 }) })]) {
const response = await proxy.handle(request);
console.log(` [CLIENT] ${request.method} ${new URL(request.url).pathname} → served by ${response.headers.get("x-served-by")}: ${await response.text()}`);
}
await Promise.all([legacy.stop(true), core.stop(true)]);
await Promise.all([poolLegacy.end(), poolNew.end()]);
Nível
avançado
8/13
Domínio financeiro
Padrões do catálogo que implementa
Infraestrutura
MariaDBbanco relacional
mariadb:11:3306
PostgreSQLbanco relacional
postgres:16-alpine:5432
Banco
sql/01_legacy_core.sql
sql/02_new_core.sql
Variáveis de ambiente
Trilhapasso 3 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 Strangler Fig?
Isola o legado na fronteira. Abrir Anti-Corruption Layer
Seu progresso
0/157 estudados
Fica salvo só neste navegador.