pattern/resilience/graceful-degradation
- AbortSignal
- Bun
- ElysiaJS
- TypeScript
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.
pattern/resilience/graceful-degradation
Cenário
Painel com saldo, nome e ofertas; ofertas fora, sai sem elas e a transferência segue disponível.
Planta
Fluxo10 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
SERVICES define core, opcional e timeout
Promise.allSettled com AbortSignal.timeout individual
Falha vira warning e seção ausente, nunca valor inventado
FULL, DEGRADED (opcional fora) ou MINIMAL (core fora, transferência desligada)
Trade-offs
O que se ganha, o que se paga
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./
src/
Executar só Bun
bun install# dependênciasbun run demo# roda o cenárioSaída: balanceCents 843055 e nome Maria Silva, sem ofertas; tier DEGRADED, capabilities com transfer e warning offers_unavailable.
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
Domínio financeiro
Padrões do catálogo que implementa
Variáveis de ambiente
Relações
Onde ele se encaixa
Por que se relacionam
Próximo passo
Teste rápido
Qual é o próximo passo depois de Graceful Degradation?
Prova tudo isso sob falha real. Abrir Chaos Engineering
Seu progresso
0/157 estudados
Fica salvo só neste navegador.