pattern/resilience/resilience-kit
- AbortSignal
- Bun
- Bun.spawn
- ElysiaJS
- TypeBox
- TypeScript
Compõe bulkhead, fallback, timeout, circuit breaker e retry numa pipeline, de fora para dentro. Use em chamada a serviço externo com SLA de latência.
pattern/resilience/resilience-kit
Cenário
Corretora cota USD/BRL num provedor primário com secundário de reserva. O primário alterna entre saudável, instável, fora e lento; moeda não suportada é recusada sem retry nem fallback.
Planta
Fluxo7 passos — reproduza para seguir o fluxo
Como funciona
6passos
Compõe bulkhead, fallback, timeout, circuit breaker e retry numa pipeline, de fora para dentro
Esconde cada passo: lembre antes de tocar para revelar.
Vocabulário compartilhado
RetrySó erro de infraestrutura (5xx, 429, timeout, conexão), backoff exponencial com full jitter
Circuit breakerConta falhas de infraestrutura; aberto, não chama; HALF_OPEN deixa uma sonda
TimeoutCobre a cadeia e aborta o fetch via AbortSignal
FallbackSecundário só em falha de infraestrutura; recusa de negócio (422) chega ao cliente
BulkheadSemáforo com fila limitada; fila cheia recusa na hora
Um kit por dependência via kitCreate
Trade-offs
O que se ganha, o que se paga
Vantagens
Retry e backoff limitados a 1.500 ms antes do fallback
Recusa de negócio (422) não é mascarada
Custos
Limiares acoplados: retry e backoff precisam caber no timeout
Secundário cota com spread, pior que o primário
Código
pattern/resilience/resilience-kit
6 arquivos./
src/
Executar só Bun
bun install# dependênciasbun run demo# roda o cenárioSaída: saudável → R$ 5.4120 do primário; XYZ recusada com quote.currency_unsupported; um 503 recuperado pelo retry; na queda, R$ 5.4932 do secundário e o circuito abre na terceira chamada; a sonda fecha o circuito; com o primário lento, 3 chamadas caem no secundário após 1.500 ms e a quarta recebe ErrorBulkheadFull.
Código
src/api_quote.ts// FX quote provider as its own Elysia process; the demo switches the primary between up, flaky, down and slow.
import { Elysia, t } from "elysia";
export const QUOTE_PRIMARY_PORT = 4117;
export const QUOTE_SECONDARY_PORT = 4118;
type QuoteMode = "up" | "flaky" | "down" | "slow";
// Mid-market USD/BRL in hundredths of a cent; the secondary adds a conservative spread because it quotes less often.
const QUOTE_RATES: Record<string, number> = { USD: 54_120 };
export const apiQuoteCreate = (provider: string, spreadBasisPoints: number) => {
let mode: QuoteMode = "up";
let failuresLeft = 0;
return new Elysia()
.get("/health", () => ({ status: "up" }))
.put(
"/mode",
({ body }) => {
mode = body.mode;
failuresLeft = body.failures ?? 0;
return { mode };
},
{ body: t.Object({ mode: t.UnionEnum(["up", "flaky", "down", "slow"]), failures: t.Optional(t.Integer({ minimum: 0 })) }) },
)
.get(
"/quotes/:currency",
async ({ params, status }) => {
if (mode === "down" || (mode === "flaky" && failuresLeft-- > 0)) return status(503, { error: "quote.unavailable" });
if (mode === "slow") await Bun.sleep(2_000);
const rate = QUOTE_RATES[params.currency];
if (rate === undefined) return status(422, { error: "quote.currency_unsupported" });
return { provider, currency: params.currency, rate: Math.round(rate * (1 + spreadBasisPoints / 10_000)) };
},
{ params: t.Object({ currency: t.String({ minLength: 3, maxLength: 3 }) }) },
);
};
if (import.meta.main) {
const secondary = Bun.argv.includes("--secondary");
const port = secondary ? QUOTE_SECONDARY_PORT : QUOTE_PRIMARY_PORT;
const app = apiQuoteCreate(secondary ? "secondary" : "primary", secondary ? 150 : 0).listen(port);
console.log(`[QUOTE] ${secondary ? "secondary" : "primary"} listening on port ${app.server?.port}`);
}
src/demo.ts// Demo: one kit protects the FX quote of the primary provider; the secondary provider is the independent fallback.
import { Value } from "@sinclair/typebox/value";
import { t } from "elysia";
import { QUOTE_PRIMARY_PORT, QUOTE_SECONDARY_PORT } from "./api_quote.ts";
import { ErrorProvider, kitCreate } from "./resilience_kit.ts";
// Enrichment profile: a quote is not a debit, so a short timeout, a sensitive circuit and a fallback are acceptable.
const kitQuote = kitCreate({
bulkhead: { slots: 2, queueMax: 1 },
timeoutMs: 1_500,
circuit: { failureThreshold: 3, openTimeoutMs: 1_000 },
retry: { attemptsMax: 2, delayBaseMs: 100, delayMaxMs: 500 },
});
const schemaQuote = t.Object({ provider: t.String(), rate: t.Integer() });
const schemaQuoteError = t.Object({ error: t.String() });
async function quoteFetch(port: number, currency: string, signal?: AbortSignal): Promise<{ provider: string; rate: number }> {
const response = await fetch(`http://localhost:${port}/quotes/${currency}`, { signal });
const body: unknown = await response.json();
if (!response.ok) throw new ErrorProvider(response.status, Value.Check(schemaQuoteError, body) ? body.error : `HTTP ${response.status}`);
if (!Value.Check(schemaQuote, body)) throw new Error("quote out of contract");
return body;
}
async function quoteShow(label: string, currency = "USD"): Promise<void> {
try {
const { value, source } = await kitQuote.run((signal) => quoteFetch(QUOTE_PRIMARY_PORT, currency, signal), () => quoteFetch(QUOTE_SECONDARY_PORT, currency));
console.log(` [QUOTE] ${label}: ${currency} R$ ${(value.rate / 10_000).toFixed(4)} from ${value.provider} (${source}), circuit ${kitQuote.circuit.stateGet()}`);
} catch (error) {
console.log(` [QUOTE] ${label}: refused — ${error instanceof Error ? `${error.name}: ${error.message}` : String(error)}`);
}
}
async function primaryModeSet(mode: string, failures = 0): Promise<void> {
await fetch(`http://localhost:${QUOTE_PRIMARY_PORT}/mode`, { method: "PUT", headers: { "content-type": "application/json" }, body: JSON.stringify({ mode, failures }) });
console.log(`\n--- primary provider: ${mode} ---`);
}
async function providersHealthWait(): Promise<void> {
for (const port of [QUOTE_PRIMARY_PORT, QUOTE_SECONDARY_PORT]) {
for (let i = 0; i < 60 && !(await fetch(`http://localhost:${port}/health`).catch(() => null))?.ok; i++) await Bun.sleep(50);
}
}
async function scenariosRun(): Promise<void> {
await primaryModeSet("up");
await quoteShow("healthy provider");
await quoteShow("business refusal is never retried nor masked", "XYZ");
await primaryModeSet("flaky", 1);
await quoteShow("one 503, the retry recovers");
await primaryModeSet("down");
for (let i = 1; i <= 4; i++) await quoteShow(`outage, call ${i}`);
await primaryModeSet("up");
await Bun.sleep(1_100); // the demo waits on purpose: the open timeout elapses in real time
await quoteShow("after the open timeout, one probe closes the circuit");
await primaryModeSet("slow");
await Promise.all([1, 2, 3, 4].map((i) => quoteShow(`slow provider, concurrent call ${i}`)));
}
async function main(): Promise<void> {
console.log("=== RESILIENCE KIT — bulkhead, fallback, timeout, circuit breaker and retry around an FX quote ===");
const providers = [["src/api_quote.ts"], ["src/api_quote.ts", "--secondary"]].map((args) => Bun.spawn(["bun", "run", ...args], { stdout: "ignore", stderr: "inherit" }));
try {
await providersHealthWait();
await scenariosRun();
} finally {
for (const provider of providers) provider.kill();
await Promise.all(providers.map((provider) => provider.exited));
}
}
await main();
src/resilience_kit.ts// Resilience kit: bulkhead → fallback → timeout → circuit breaker → retry → operation, each layer protecting the next.
// The provider answered with an HTTP error: 5xx and 429 are infrastructure, 4xx is a business refusal.
export class ErrorProvider extends Error {
override name = "ErrorProvider";
constructor(readonly status: number, message: string) {
super(message);
}
}
export class ErrorTimeout extends Error {
override name = "ErrorTimeout";
}
export class ErrorCircuitOpen extends Error {
override name = "ErrorCircuitOpen";
}
export class ErrorBulkheadFull extends Error {
override name = "ErrorBulkheadFull";
}
// Only infrastructure failures are transient; a business refusal is permanent: never retried, never counted by the circuit.
export function errorIsTransient(error: unknown): boolean {
if (error instanceof ErrorTimeout) return true;
// The timeout aborted the fetch: the provider did not answer in time.
if (error instanceof DOMException && error.name === "AbortError") return true;
if (error instanceof ErrorProvider) return error.status >= 500 || error.status === 429;
// fetch rejects with TypeError on connection refused or reset.
return error instanceof TypeError;
}
const messageOf = (error: unknown): string => (error instanceof Error ? error.message : String(error));
const sleepReal = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));
export interface InterfaceRetryConfig {
attemptsMax: number;
delayBaseMs: number;
delayMaxMs: number;
}
// Innermost layer: exponential backoff with a ceiling and full jitter; stops once the outer deadline aborted the chain.
export async function retryWith<T>(operation: () => Promise<T>, config: InterfaceRetryConfig, signal?: AbortSignal, sleep = sleepReal, random = Math.random): Promise<T> {
for (let attempt = 1; ; attempt++) {
try {
return await operation();
} catch (error) {
if (!errorIsTransient(error) || attempt >= config.attemptsMax || signal?.aborted) throw error;
const delayMs = Math.floor(random() * Math.min(config.delayBaseMs * 2 ** (attempt - 1), config.delayMaxMs));
console.log(` [RETRY] attempt ${attempt} failed (${messageOf(error)}), next in ${delayMs} ms`);
await sleep(delayMs);
}
}
}
export type CircuitState = "CLOSED" | "OPEN" | "HALF_OPEN";
export interface InterfaceCircuitConfig {
failureThreshold: number;
openTimeoutMs: number;
now?: () => number;
}
// Wraps the retry: while OPEN the retry never starts; in HALF_OPEN exactly one probe goes through.
export class CircuitBreaker {
private state: CircuitState = "CLOSED";
private failureCount = 0;
private openedAt = 0;
private probeInFlight = false;
private readonly now: () => number;
constructor(private readonly config: InterfaceCircuitConfig) {
this.now = config.now ?? Date.now;
}
stateGet(): CircuitState {
return this.state;
}
async execute<T>(operation: () => Promise<T>): Promise<T> {
this.admit();
try {
const result = await operation();
this.close();
return result;
} catch (error) {
// A business refusal proves the provider is up: it closes the circuit like a success.
if (errorIsTransient(error)) this.fail();
else this.close();
throw error;
} finally {
this.probeInFlight = false;
}
}
private admit(): void {
if (this.state === "OPEN") {
if (this.now() - this.openedAt < this.config.openTimeoutMs) throw new ErrorCircuitOpen("circuit OPEN: fast-fail");
this.transition("HALF_OPEN");
}
if (this.state === "HALF_OPEN") {
if (this.probeInFlight) throw new ErrorCircuitOpen("circuit HALF_OPEN: probe in flight");
this.probeInFlight = true;
}
}
private close(): void {
this.failureCount = 0;
if (this.state !== "CLOSED") this.transition("CLOSED");
}
private fail(): void {
this.failureCount++;
if (this.state === "HALF_OPEN" || this.failureCount >= this.config.failureThreshold) {
this.openedAt = this.now();
this.transition("OPEN");
}
}
private transition(to: CircuitState): void {
console.log(` [CIRCUIT] ${this.state} → ${to}`);
this.state = to;
}
}
// Covers the whole inner chain; the signal cancels the fetch, the race stops waiting on anything that ignores it.
export function timeoutWith<T>(operation: (signal: AbortSignal) => Promise<T>, limitMs: number): Promise<T> {
const controller = new AbortController();
const aborted = new Promise<never>((_, reject) =>
controller.signal.addEventListener("abort", () => reject(new ErrorTimeout(`exceeded ${limitMs} ms`)), { once: true }),
);
const timer = setTimeout(() => controller.abort(), limitMs);
return Promise.race([operation(controller.signal), aborted]).finally(() => clearTimeout(timer));
}
export type FallbackSource = "primary" | "fallback";
// An independent source answers when the chain failed for infrastructure; a business refusal is never masked.
export async function fallbackWith<T>(primary: () => Promise<T>, fallback: () => Promise<T>): Promise<{ value: T; source: FallbackSource }> {
try {
return { value: await primary(), source: "primary" };
} catch (error) {
if (!errorIsTransient(error) && !(error instanceof ErrorCircuitOpen)) throw error;
console.log(` [FALLBACK] primary failed (${messageOf(error)}), asking the secondary provider`);
return { value: await fallback(), source: "fallback" };
}
}
// Outermost layer: a semaphore over whole chains; past the bounded queue it sheds load at once instead of piling up.
export class Bulkhead {
private active = 0;
private readonly waiters: (() => void)[] = [];
constructor(
private readonly slots: number,
private readonly queueMax: number,
) {}
async execute<T>(operation: () => Promise<T>): Promise<T> {
await this.acquire();
try {
return await operation();
} finally {
this.release();
}
}
private async acquire(): Promise<void> {
if (this.active < this.slots) {
this.active++;
return;
}
if (this.waiters.length >= this.queueMax) throw new ErrorBulkheadFull(`bulkhead full: ${this.active} in flight, ${this.waiters.length} queued`);
// The slot is handed over by release, so active is not incremented here.
await new Promise<void>((resolve) => this.waiters.push(resolve));
}
private release(): void {
const next = this.waiters.shift();
if (next) next();
else this.active--;
}
}
export interface InterfaceKitConfig {
bulkhead: { slots: number; queueMax: number };
timeoutMs: number;
circuit: InterfaceCircuitConfig;
retry: InterfaceRetryConfig;
}
export interface InterfaceKit {
run<T>(operation: (signal: AbortSignal) => Promise<T>, fallback: () => Promise<T>): Promise<{ value: T; source: FallbackSource }>;
circuit: CircuitBreaker;
}
// One kit per dependency, never global: each service has its own limits.
export function kitCreate(config: InterfaceKitConfig): InterfaceKit {
const bulkhead = new Bulkhead(config.bulkhead.slots, config.bulkhead.queueMax);
const circuit = new CircuitBreaker(config.circuit);
const run = <T>(operation: (signal: AbortSignal) => Promise<T>, fallback: () => Promise<T>) =>
bulkhead.execute(() =>
fallbackWith(() => timeoutWith((signal) => circuit.execute(() => retryWith(() => operation(signal), config.retry, signal)), config.timeoutMs), fallback),
);
return { run, circuit };
}
Nível
avançado
10/13
Domínio financeiro
Padrões do catálogo que implementa
Trilhapasso 6 de 6
Resiliência de ponta a ponta
Parecidos
Por que se relacionam
Combina com
Alternativa a
Teste rápido
Qual destes combina com Resilience Kit?
Peça central do kit. Abrir Circuit Breaker
Seu progresso
0/157 estudados
Fica salvo só neste navegador.