pattern/resilience/fallback
- AbortSignal
- Bun
- ElysiaJS
- TypeScript
Com a fonte primária fora, responde com a melhor alternativa (do mais fresco ao mais conservador) e informa o nível usado; termina em erro explícito. Use em leitura degradável, nunca em escrita financeira.
pattern/resilience/fallback
Cenário
Cotação do dólar com o provedor fora: última taxa + 1,5% por até 5 min, depois a taxa teto da tesouraria; o app avisa que é indicativa.
Planta
Fluxo5 passos — reproduza para seguir o fluxo
Como funciona
4passos
Com a fonte primária fora, responde com a melhor alternativa (do mais fresco ao mais conservador) e informa o nível usado
Esconde cada passo: lembre antes de tocar para revelar.
Vocabulário compartilhado
Níveis em ordem; falha ou undefined passa ao próximo
api chama com timeout e grava taxa e instante
cache só dentro do TTL, com spread contra o cliente
static = taxa teto; sem nível, erro explícito
Trade-offs
O que se ganha, o que se paga
Vantagens
Resposta útil com a fonte fora
Cada nível mais conservador
Custos
Dado degradado sem aviso induz erro
Spread e teto pioram o preço
Código
pattern/resilience/fallback
5 arquivos./
src/
Executar só Bun
bun install# dependênciasbun run demo# roda o cenárioSaída: provedor no ar → 5.4213 de api; fora há 2 min → 5.5026 de cache (spread de 1,5%); fora há 6 min → 6 de static.
Código
src/demo.ts// Demo: the dollar quote while the FX provider goes down — live, then the cached rate with a spread, then the treasury ceiling.
import { Elysia } from "elysia";
const PROVIDER_URL = Bun.env.FALLBACK_PROVIDER_URL ?? "http://localhost:4212";
const PROVIDER_TIMEOUT_MS = 500;
const CACHE_TTL_MS = 5 * 60_000;
const CACHE_SPREAD_BPS = 150;
const CEILING_USD_BRL = 6.0;
type Quote = { sellRate: number; source: string };
// The market-data provider, its health switched at runtime so the chain meets a real HTTP outage.
let providerIsHealthy = true;
const provider = new Elysia().get("/rates/USD-BRL", ({ status }) => (providerIsHealthy ? { sellRate: 5.4213 } : status(503, { error: "provider unavailable" }))).listen(new URL(PROVIDER_URL).port);
let clock = Date.now();
let lastLive: { sellRate: number; at: number } | undefined;
// Levels from the freshest source to the most conservative; undefined passes to the next, the last is an explicit error.
const LEVELS: { source: string; run: () => Promise<number | undefined> }[] = [
{
source: "api",
run: async () => {
const response = await fetch(`${PROVIDER_URL}/rates/USD-BRL`, { signal: AbortSignal.timeout(PROVIDER_TIMEOUT_MS) });
if (!response.ok) return undefined;
const { sellRate } = (await response.json()) as { sellRate: number };
lastLive = { sellRate, at: clock };
return sellRate;
},
},
// Older than the TTL is worse than nothing; a stale rate at face value can sell below market, so the spread moves it against the customer.
{ source: "cache", run: async () => (lastLive && clock - lastLive.at <= CACHE_TTL_MS ? Math.round(lastLive.sellRate * (10_000 + CACHE_SPREAD_BPS)) / 10_000 : undefined) },
{ source: "static", run: async () => CEILING_USD_BRL },
];
async function quoteUsdBrl(): Promise<Quote> {
for (const level of LEVELS) {
const sellRate = await level.run().catch(() => undefined);
// The app reads the source and warns the customer that the quote is indicative.
if (sellRate !== undefined) return { sellRate, source: level.source };
}
throw new Error("quote USD/BRL: no source available");
}
console.log(` [QUOTE] provider up → ${JSON.stringify(await quoteUsdBrl())}`);
providerIsHealthy = false;
clock += 2 * 60_000;
console.log(` [QUOTE] provider down, 2 min → ${JSON.stringify(await quoteUsdBrl())}`);
clock += 4 * 60_000;
console.log(` [QUOTE] provider down, 6 min → ${JSON.stringify(await quoteUsdBrl())}`);
await provider.stop(true);
Nível
introdutório
1/13
Domínio financeiro
Padrões do catálogo que implementa
Variáveis de ambiente
Trilhapasso 4 de 6
Resiliência de ponta a ponta
Parecidos
Relações
Onde ele se encaixa
Por que se relacionam
Teste rápido
Qual é o próximo passo depois de Fallback?
Desliga o acessório, preserva o núcleo. Abrir Graceful Degradation
Seu progresso
0/157 estudados
Fica salvo só neste navegador.