pattern/resilience/bulkhead
- Bun
- ElysiaJS
- TypeScript
Divide a capacidade de um recurso compartilhado em pools por criticidade: um pool esgotado não afeta os outros. Use quando cargas de importância diferente disputam o mesmo serviço.
pattern/resilience/bulkhead
Cenário
10 relatórios de 800 ms e 20 PIX de 20 ms no core: relatórios excedentes são descartados no próprio pool e os PIX liquidam em ms.
Planta
Fluxo6 passos — reproduza para seguir o fluxo
Como funciona
4passos
Divide a capacidade de um recurso compartilhado em pools por criticidade
Esconde cada passo: lembre antes de tocar para revelar.
Vocabulário compartilhado
Semáforo com maxConcurrent e fila FIFO de maxQueueDepth por carga
Slot livre roda; sem slot espera; fila cheia → ErrorBulkheadFull
Slot liberado no finally vai ao mais antigo da fila
Lei de Little200 PIX/s × 20 ms ≈ 4 slots, dobrado para pico
Trade-offs
O que se ganha, o que se paga
Vantagens
Carga lenta não esgota as outras
Rejeição imediata protege quem entra
Custos
Capacidade ociosa não é emprestada
Dimensionar exige medir vazão e latência
Código
pattern/resilience/bulkhead
5 arquivos./
src/
Executar só Bun
bun install# dependênciasbun run demo# roda o cenárioSaída: 20/20 PIX liquidados em cerca de 100 ms; 4/10 relatórios gerados e 6 descartados pelo próprio bulkhead.
Código
src/demo.ts// Demo: month-end — 10 slow regulatory reports and 20 PIX hit the core at once; one bulkhead per workload keeps PIX flowing.
import { Elysia, t } from "elysia";
const CORE_URL = Bun.env.BULKHEAD_CORE_URL ?? "http://localhost:4211";
const PIX_SETTLE_MS = 20;
const REPORT_GENERATE_MS = 800;
// Sized by Little's law: PIX 200/s × 20 ms ≈ 4 slots, doubled for peaks; reports are rare and can wait.
const PIX_SLOTS = 8;
const PIX_QUEUE_MAX = 16;
const REPORT_SLOTS = 2;
const REPORT_QUEUE_MAX = 2;
class ErrorBulkheadFull extends Error {
override name = "ErrorBulkheadFull";
}
// A pool of slots per workload: at most maxConcurrent run, up to maxQueueDepth wait in FIFO order, the rest is shed at
// once — an unbounded queue would undo the isolation.
class BulkheadSemaphore {
private inUse = 0;
private readonly waiting: (() => void)[] = [];
constructor(
readonly name: string,
private readonly maxConcurrent: number,
private readonly maxQueueDepth: number,
) {}
async execute<T>(operation: () => Promise<T>): Promise<T> {
if (this.inUse < this.maxConcurrent) this.inUse++;
else if (this.waiting.length >= this.maxQueueDepth) throw new ErrorBulkheadFull(`bulkhead ${this.name} is full`);
// The slot is handed over by the releaser: inUse stays counted for the waiter that receives it.
else await new Promise<void>((resolve) => this.waiting.push(resolve));
try {
return await operation();
} finally {
// Released in finally: an operation that throws never keeps its slot.
const next = this.waiting.shift();
if (next) next();
else this.inUse--;
}
}
}
// The core banking API both workloads depend on: a PIX settles in 20 ms, a regulatory report takes 800 ms.
const core = new Elysia()
.post("/pix", async ({ body }) => (await Bun.sleep(PIX_SETTLE_MS), { pixId: body.pixId, status: "settled" }), { body: t.Object({ pixId: t.String() }) })
.post("/reports", async ({ body }) => (await Bun.sleep(REPORT_GENERATE_MS), { reportId: body.reportId, status: "generated" }), { body: t.Object({ reportId: t.String() }) })
.listen(new URL(CORE_URL).port);
const corePost = (path: string, body: object) => fetch(`${CORE_URL}${path}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }).then((response) => response.json());
const pools = { pix: new BulkheadSemaphore("pix", PIX_SLOTS, PIX_QUEUE_MAX), reports: new BulkheadSemaphore("reports", REPORT_SLOTS, REPORT_QUEUE_MAX) };
const reports = Promise.allSettled(Array.from({ length: 10 }, (_, index) => pools.reports.execute(() => corePost("/reports", { reportId: `REP-${index}` }))));
const started = performance.now();
const pixes = await Promise.allSettled(Array.from({ length: 20 }, (_, index) => pools.pix.execute(() => corePost("/pix", { pixId: `PIX-${index}` }))));
console.log(` [PIX] ${pixes.filter((result) => result.status === "fulfilled").length}/20 settled in ${Math.round(performance.now() - started)} ms`);
const reportResults = await reports;
console.log(` [REPORT] ${reportResults.filter((result) => result.status === "fulfilled").length}/10 generated, ${reportResults.filter((result) => result.status === "rejected").length} shed by their own bulkhead`);
await core.stop(true);
Nível
introdutório
1/13
Domínio financeiro
Padrões do catálogo que implementa
Variáveis de ambiente
Trilhapasso 5 de 6
Resiliência de ponta a ponta
Relações
Onde ele se encaixa
Por que se relacionam
Próximo passo
Teste rápido
Qual é o próximo passo depois de Bulkhead?
Fila absorve o pico. Abrir Queue-Based Load Leveling
Seu progresso
0/157 estudados
Fica salvo só neste navegador.