pattern/resilience/chaos-engineering
- AbortSignal
- Bun
- ElysiaJS
- TypeScript
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.
pattern/resilience/chaos-engineering
Cenário
Hipótese: com 150 ms de latência em 20% dos PIX no BACEN, 99% liquidam e p99 < 400 ms.
Planta
Sequência7 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
Baseline com a falha desligada
PUT /chaos liga a falha em runtime
Coorte fixaHash FNV-1a do id abaixo do percentual
Resultado julgado contra a hipótese; DELETE /chaos no finally
Trade-offs
O que se ganha, o que se paga
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./
src/
Executar só Bun
bun install# dependênciasbun run demo# roda o cenárioSaída: baseline com successRate 1; com a falha, successRate 1 e p99 entre 150 e 200 ms → hypothesis held; ROLLBACK desliga a falha.
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
Domínio financeiro
Padrões do catálogo que implementa
Variáveis de ambiente
Parecidos
Por que se relacionam
Teste rápido
Qual padrão vem antes de Chaos Engineering?
Prova tudo isso sob falha real. Abrir Graceful Degradation
Seu progresso
0/157 estudados
Fica salvo só neste navegador.