Pular para o conteúdo

Fallback

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.

passos
4
arquivos
5
testes
0
tecnologias
4

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

Fluxo
5/5
Cotação USD/BRLProvedorresponde?api: taxa ao vivoe grava no cacheCache mais novoque o TTL?cache: última taxamais spread de 1,5%static: taxa tetoda tesourariasimnãosimnão
5

5 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

  1. 1

    Níveis em ordem; falha ou undefined passa ao próximo

  2. 2

    api chama com timeout e grava taxa e instante

  3. 3

    cache só dentro do TTL, com spread contra o cliente

  4. 4

    static = taxa teto; sem nível, erro explícito

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

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

./

  • .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: 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.

Requisitos
Bun

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

Por que se relacionam

Teste rápido

Qual é o próximo passo depois de Fallback?

Próximo projeto, ResiliênciaGraceful Degradation
Esc

↑ ↓ navegarEnter abrir239 resultados