Pular para o conteúdo

Strangler Fig

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.

passos
4
arquivos
8
testes
0
tecnologias
8

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

Fluxo
4/4
ClientesProxy stranglerrota por endpointCore legadoMariaDBCore novoPostgreSQLmigration_routestransfer: legacybalance: new
4

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

  1. 1

    migration_routes diz o sistema de cada endpoint

  2. 2

    Saldo vai ao core novo

  3. 3

    Transferência vai ao legado, traduzida para o formato dele

  4. 4

    Rollback = UPDATE na tabela

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

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

./

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

sql/

  • 01_legacy_core.sqlschema
  • 02_new_core.sqlschema

src/

  • demo.tsdemo

Executar com Docker

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

Saída: saldo de 00042-1 servido pelo core new com balanceCents 485000; transferência servida pelo legacy com outcome completed.

Requisitos
BunDocker
Sobe junto
MariaDBPostgreSQL

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

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

Domínio financeiro

  • Conta corrente
  • Saldo

Padrões do catálogo que implementa

  • Strangler Fig

Infraestrutura

  • MariaDBbanco relacional

    mariadb:11:3306

  • PostgreSQLbanco relacional

    postgres:16-alpine:5432

Banco

sql/01_legacy_core.sql

  • contas

sql/02_new_core.sql

  • accounts
  • migration_routes

Variáveis de ambiente

STRANGLER_FIG_LEGACY_DATABASE_URL
mysql://app:app_password@localhost:3306/legacy_core_db
STRANGLER_FIG_NEW_DATABASE_URL
postgres://postgres:postgres@localhost:5432/new_core_db
STRANGLER_FIG_LEGACY_URL
http://localhost:4061
STRANGLER_FIG_NEW_URL
http://localhost:4062

Trilhapasso 3 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 Strangler Fig?

Próximo projeto, API & IntegraçãoAPI Versioning
Esc

↑ ↓ navegarEnter abrir239 resultados