Pular para o conteúdo

Blue-Green Deployment

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.

passos
4
arquivos
5
testes
0
tecnologias
4

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

Estados
5/5
AzulAtivoVerdeImplantadoVerdeAtivodeploy da versãonova na cor ociosasmoke test falhou,tráfego intocadosmoke test ok,corte atômicorollback
5

5 passos — reproduza para seguir o fluxo

  • chamada
  • resposta ou assíncrono
  • falha
  • passo
  • toque num nó para focar
  • repouso ou sucesso
  • transição
  • falha ou recusa
  • Outras plantas de estados

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

/health+1
  1. 1

    O roteador guarda a cor ativa

  2. 2

    Versão nova na cor ociosa, sem tráfego

  3. 3

    Smoke/health ok e PIX sintético com tarifa zero

  4. 4

    Corte e rollback = troca do ponteiro

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

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

./

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

src/

  • demo.tsdemo

Executar só Bun

  1. bun install# dependências
  2. bun run demo# roda o cenário

Saí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).

Requisitos
Bun

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)));

Por que se relacionam

Teste rápido

Qual é o próximo passo depois de Blue-Green Deployment?

Próximo projeto, Deploy & TopologiaCanary Deployment
Esc

↑ ↓ navegarEnter abrir239 resultados