pattern/deployment/blue-green
- AbortSignal
- Bun
- ElysiaJS
- TypeScript
Dois ambientes completos atrás de um roteador: a versão nova sobe na cor ociosa, passa por smoke test e recebe 100% numa troca atômica; rollback é a troca inversa. Use quando o rollback precisa ser imediato.
pattern/deployment/blue-green
Cenário
Motor de PIX 1.2.0 no azul; 2.0.0 sobe no verde, passa no smoke test, recebe o tráfego e depois volta ao azul no rollback.
Planta
Estados5 passos — reproduza para seguir o fluxo
Como funciona
4passos
Dois ambientes completos atrás de um roteador, com troca atômica após smoke test e rollback imediato
Esconde cada passo: lembre antes de tocar para revelar.
Vocabulário compartilhado
O roteador guarda a cor ativa
Versão nova na cor ociosa, sem tráfego
Smoke/health ok e PIX sintético com tarifa zero
Corte e rollback = troca do ponteiro
Trade-offs
O que se ganha, o que se paga
Vantagens
Rollback em segundos
Smoke antes do cliente
Custos
Dois ambientes durante o deploy
Tudo ou nada; schema serve as duas versões
Código
pattern/deployment/blue-green
5 arquivos./
src/
Executar só Bun
bun install# dependênciasbun run demo# roda o cenárioSaída: P-1 atendido pelo azul (1.2.0); smoke test aprovado e corte para o verde; P-2 atendido pelo verde (2.0.0); rollback e P-3 de volta no azul (1.2.0).
Código
src/demo.ts// Demo: the PIX engine 2.0.0 goes to the idle green environment, passes a smoke test, takes all traffic, and is rolled back.
import { Elysia, t } from "elysia";
type Color = "blue" | "green";
const PORTS: Record<Color, number> = { blue: Number(Bun.env.BLUE_GREEN_BLUE_PORT ?? 4302), green: Number(Bun.env.BLUE_GREEN_GREEN_PORT ?? 4303) };
// A release of the PIX engine, as an HTTP service.
const pixEngineStart = (color: Color, version: string) =>
new Elysia()
.get("/health", () => ({ status: "ok", version }))
.post("/pix", ({ body }) => ({ pixId: body.pixId, status: "settled", feeCents: 0, version }), { body: t.Object({ pixId: t.String(), amountCents: t.Integer({ minimum: 1 }) }) })
.listen(PORTS[color]);
const SMOKE_TIMEOUT_MS = 1_000;
// The synthetic transaction: healthy is not enough — a known PIX must come back settled with zero fee.
async function smokeTest(color: Color): Promise<boolean> {
const url = `http://localhost:${PORTS[color]}`;
if (!(await fetch(`${url}/health`, { signal: AbortSignal.timeout(SMOKE_TIMEOUT_MS) })).ok) return false;
const response = await fetch(`${url}/pix`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ pixId: "SMOKE-1", amountCents: 10_000 }) });
const body = (await response.json()) as { status: string; feeCents: number };
return body.status === "settled" && body.feeCents === 0;
}
// The router keeps one pointer: cutover and rollback are the same atomic switch, in opposite directions.
let active: Color = "blue";
const idle = (): Color => (active === "blue" ? "green" : "blue");
const router = new Elysia().post("/pix", async ({ request }) => {
const upstream = await fetch(`http://localhost:${PORTS[active]}/pix`, { method: "POST", headers: request.headers, body: await request.text() });
return new Response(upstream.body, { status: upstream.status, headers: { "content-type": "application/json", "x-served-by": active } });
}, { parse: "none" });
const pixSend = async (pixId: string) => {
const response = await router.handle(new Request("http://router/pix", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ pixId, amountCents: 25_000 }) }));
return `served by ${response.headers.get("x-served-by")}: ${await response.text()}`;
};
const engines = [pixEngineStart("blue", "1.2.0"), pixEngineStart("green", "2.0.0")];
console.log(` [PIX] ${await pixSend("P-1")}`);
const smokePassed = await smokeTest(idle());
if (smokePassed) active = idle();
console.log(` [CUTOVER] smoke test ${smokePassed ? "passed" : "failed"}, active → ${active}`);
console.log(` [PIX] ${await pixSend("P-2")}`);
active = idle();
console.log(` [ROLLBACK] active → ${active}`);
console.log(` [PIX] ${await pixSend("P-3")}`);
await Promise.all(engines.map((engine) => engine.stop(true)));
Nível
introdutório
1/13
Domínio financeiro
Padrões do catálogo que implementa
Variáveis de ambiente
Trilhapasso 6 de 7
Escala e deploy
Relações
Onde ele se encaixa
Por que se relacionam
Próximo passo
Teste rápido
Qual é o próximo passo depois de Blue-Green Deployment?
Expõe a versão aos poucos. Abrir Canary Deployment
Seu progresso
0/157 estudados
Fica salvo só neste navegador.