Pular para o conteúdo

Chaos Engineering

Injeta falha controlada num serviço real para provar com números que o comportamento se mantém: hipótese, baseline, blast radius mínimo e rollback garantido.

passos
4
arquivos
5
testes
0
tecnologias
4

Cenário

Hipótese: com 150 ms de latência em 20% dos PIX no BACEN, 99% liquidam e p99 < 400 ms.

Planta

Sequência
7/7
baseline sem falha1POST /settlements2PUT /chaos (latência + blast radius)3POST /settlements4settled, parte lenta5compara com a hipótese6DELETE /chaos (rollback, sempre)7ExperimentoCliente PIXLiquidação BACEN
7

7 passos — reproduza para seguir o fluxo

Como funciona

4passos

Injeta falha controlada num serviço real para provar com números que o comportamento se mantém

Esconde cada passo: lembre antes de tocar para revelar.

Vocabulário compartilhado

  1. 1

    Baseline com a falha desligada

  2. 2

    PUT /chaos liga a falha em runtime

  3. 3

    Coorte fixaHash FNV-1a do id abaixo do percentual

  4. 4

    Resultado julgado contra a hipótese; DELETE /chaos no finally

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

Vantagens

  • Resiliência provada com falha real

  • Coorte limitada e reproduzível

Custos

  • Exige observabilidade antes

  • Injetor no caminho de produção precisa de proteção

Código

pattern/resilience/chaos-engineering

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: baseline com successRate 1; com a falha, successRate 1 e p99 entre 150 e 200 ms → hypothesis held; ROLLBACK desliga a falha.

Requisitos
Bun

Código

src/demo.ts

// Demo: a chaos experiment on the BACEN settlement — 150 ms of latency on 20% of PIX; does "99% settle, p99 < 400 ms" hold?
import { Elysia, t } from "elysia";

const BACEN_URL = Bun.env.CHAOS_ENGINEERING_BACEN_URL ?? "http://localhost:4204";
const HYPOTHESIS = { minSuccessRate: 0.99, maxP99Ms: 400 };
const CHAOS_LATENCY_MS = 150;
const CHAOS_BLAST_RADIUS_PERCENT = 20;
const CHAOS_JITTER_RATIO = 0.3;
const SETTLEMENT_TIMEOUT_MS = 500;
const SAMPLE_COUNT = 50;
type ChaosFlag = { enabled: boolean; latencyMs: number; blastRadiusPercent: number };

// Blast radius as a fixed cohort: FNV-1a of the transaction id below the percentage — always in, or always out.
function chaosBucket(transactionId: string): number {
  let hash = 0x811c9dc5;
  for (const char of transactionId) hash = Math.imul(hash ^ char.charCodeAt(0), 0x01000193) >>> 0;
  return hash % 100;
}

// The settlement service with its fault injector, switched by a runtime flag: no deploy to start or roll back.
let flag: ChaosFlag = { enabled: false, latencyMs: 0, blastRadiusPercent: 0 };
const bacen = new Elysia()
  .put("/chaos", ({ body }) => (flag = { ...body, enabled: true }), { body: t.Object({ latencyMs: t.Integer(), blastRadiusPercent: t.Integer({ minimum: 1, maximum: 100 }) }) })
  .delete("/chaos", () => (flag = { enabled: false, latencyMs: 0, blastRadiusPercent: 0 }))
  .post("/settlements", async ({ body }) => {
    // Up to 30% jitter on top: a fixed delay draws a step in the histogram that no real degradation does.
    if (flag.enabled && chaosBucket(body.transactionId) < flag.blastRadiusPercent) await Bun.sleep(flag.latencyMs + Math.random() * flag.latencyMs * CHAOS_JITTER_RATIO);
    return { transactionId: body.transactionId, status: "settled" };
  }, { body: t.Object({ transactionId: t.String() }) })
  .listen(new URL(BACEN_URL).port);

// The client under test: a PIX settlement with a hard timeout; a timeout is a failed sample.
async function steadyStateMeasure(prefix: string) {
  const samples = await Promise.all(Array.from({ length: SAMPLE_COUNT }, async (_, index) => {
    const started = performance.now();
    const ok = await fetch(`${BACEN_URL}/settlements`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ transactionId: `${prefix}-${index}` }), signal: AbortSignal.timeout(SETTLEMENT_TIMEOUT_MS) }).then((response) => response.ok, () => false);
    return { ok, ms: performance.now() - started };
  }));
  const latencies = samples.map((sample) => sample.ms).toSorted((left, right) => left - right);
  return { successRate: samples.filter((sample) => sample.ok).length / samples.length, p99Ms: Math.round(latencies[Math.ceil(latencies.length * 0.99) - 1] ?? 0) };
}
const hypothesisHolds = (state: { successRate: number; p99Ms: number }) => state.successRate >= HYPOTHESIS.minSuccessRate && state.p99Ms <= HYPOTHESIS.maxP99Ms;

const baseline = await steadyStateMeasure("baseline");
console.log(`  [BASELINE]   ${JSON.stringify(baseline)}`);
await fetch(`${BACEN_URL}/chaos`, { method: "PUT", headers: { "content-type": "application/json" }, body: JSON.stringify({ latencyMs: CHAOS_LATENCY_MS, blastRadiusPercent: CHAOS_BLAST_RADIUS_PERCENT }) });
try {
  const injected = await steadyStateMeasure("injected");
  console.log(`  [INJECTED]   ${JSON.stringify(injected)} → hypothesis ${hypothesisHolds(injected) ? "held" : "refuted"}`);
} finally {
  // Rollback always runs: at the end, on abort, or on an exception.
  await fetch(`${BACEN_URL}/chaos`, { method: "DELETE" });
  console.log("  [ROLLBACK]   chaos flag off");
}
await bacen.stop(true);

Nível

introdutório

1/13

Linhas de TypeScript
50
Tipo
A — código puro

Domínio financeiro

  • PIX
  • Liquidação
  • BACEN/SPI

Padrões do catálogo que implementa

  • Chaos Engineering

Variáveis de ambiente

CHAOS_ENGINEERING_BACEN_URL
http://localhost:4204

Parecidos

Por que se relacionam

Teste rápido

Qual padrão vem antes de Chaos Engineering?

Próximo projeto, ResiliênciaCircuit Breaker
Esc

↑ ↓ navegarEnter abrir239 resultados