Pular para o conteúdo

Graceful Degradation

Dependências classificadas como core ou opcional, chamadas em paralelo com timeout próprio; a resposta sai com o que respondeu e um tier de redução. Use em telas e APIs que agregam fontes.

passos
4
arquivos
5
testes
0
tecnologias
4

Cenário

Painel com saldo, nome e ofertas; ofertas fora, sai sem elas e a transferência segue disponível.

Planta

Fluxo
10/10
Painel da contaPromise.allSettledContas: saldoCadastro: nomeOfertasFalhasFULLDEGRADED: sem a seçãoMINIMAL: só leituracore, 800 msopcional, 300 msopcional, 300 msnenhumasó opcionalcore
10

10 passos — reproduza para seguir o fluxo

Como funciona

4passos

Dependências classificadas como core ou opcional, chamadas em paralelo com timeout próprio

Esconde cada passo: lembre antes de tocar para revelar.

Vocabulário compartilhado

AbortSignal.timeout+2
Promise.allSettled+1
  1. 1

    SERVICES define core, opcional e timeout

  2. 2

    Promise.allSettled com AbortSignal.timeout individual

  3. 3

    Falha vira warning e seção ausente, nunca valor inventado

  4. 4

    FULL, DEGRADED (opcional fora) ou MINIMAL (core fora, transferência desligada)

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

Vantagens

  • Opcional fora não derruba a tela

  • Latência limitada por serviço

Custos

  • UI trata cada ausência

  • Lista core × opcional a manter

Código

pattern/resilience/graceful-degradation

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: balanceCents 843055 e nome Maria Silva, sem ofertas; tier DEGRADED, capabilities com transfer e warning offers_unavailable.

Requisitos
Bun

Código

src/demo.ts

// Demo: the account dashboard with the offers service down — the screen still comes out, without offers, tier DEGRADED.
import { Elysia } from "elysia";

type ServiceName = "accounts" | "profile" | "offers";
const UPSTREAM_URL = Bun.env.GRACEFUL_DEGRADATION_UPSTREAM_URL ?? "http://localhost:4213";

// The documented split: the balance is why the customer opens the app; a greeting and offers are nice to have.
const SERVICES: Record<ServiceName, { core: boolean; timeoutMs: number; path: (accountId: string) => string }> = {
  accounts: { core: true, timeoutMs: 800, path: (accountId) => `/accounts/${accountId}/balance` },
  profile: { core: false, timeoutMs: 300, path: (accountId) => `/profiles/${accountId}` },
  offers: { core: false, timeoutMs: 300, path: (accountId) => `/offers/${accountId}` },
};

// The upstream services; offers answers 503 in this run.
const upstreams = new Elysia()
  .get("/accounts/:id/balance", () => ({ balanceCents: 843_055 }))
  .get("/profiles/:id", () => ({ name: "Maria Silva" }))
  .get("/offers/:id", ({ status }) => status(503, { error: "offers unavailable" }))
  .listen(new URL(UPSTREAM_URL).port);

async function serviceFetch(service: ServiceName, accountId: string): Promise<Record<string, unknown>> {
  const response = await fetch(`${UPSTREAM_URL}${SERVICES[service].path(accountId)}`, { signal: AbortSignal.timeout(SERVICES[service].timeoutMs) });
  if (!response.ok) throw new Error(`${service} answered ${response.status}`);
  return (await response.json()) as Record<string, unknown>;
}

// Every service at once with its own timeout; allSettled keeps whatever answered, and each failure becomes a warning
// and a missing section — never a failed response, never an invented value.
async function dashboardBuild(accountId: string) {
  const names = Object.keys(SERVICES) as ServiceName[];
  const settled = await Promise.allSettled(names.map((service) => serviceFetch(service, accountId)));
  const failed = names.filter((_, index) => settled[index]?.status === "rejected");
  const tier = failed.some((service) => SERVICES[service].core) ? "MINIMAL" : failed.length ? "DEGRADED" : "FULL";
  const sections = Object.assign({}, ...settled.map((result) => (result.status === "fulfilled" ? result.value : {})));
  // Without the core account service the balance cannot be checked, so money-moving operations are switched off.
  return { ...sections, tier, capabilities: tier === "MINIMAL" ? ["read"] : ["transfer", "statement", "read"], warnings: failed.map((service) => `${service}_unavailable`) };
}

console.log(`  [DASHBOARD] ${JSON.stringify(await dashboardBuild("12345"))}`);
await upstreams.stop(true);

Nível

introdutório

1/13

Linhas de TypeScript
34
Tipo
A — código puro

Domínio financeiro

  • Conta corrente
  • Saldo

Padrões do catálogo que implementa

  • Graceful Degradation

Variáveis de ambiente

GRACEFUL_DEGRADATION_UPSTREAM_URL
http://localhost:4213

Por que se relacionam

Teste rápido

Qual é o próximo passo depois de Graceful Degradation?

Próximo projeto, ResiliênciaRate Limiting
Esc

↑ ↓ navegarEnter abrir239 resultados