Pular para o conteúdo
  1. Padrões
  2. Resiliência

bulkhead

Isola recursos em compartimentos para que a falha de um não afunde os outros.
Status
Em breve
Categoria
Resiliência
Implementação em Resiliênciapattern/resilience/bulkheadintrodutório4 passos≈ 3 min

Órbita

  1. Código
  2. Arquitetura
  3. Dados
  4. Integração
  5. Resiliência

Quando usar

Isolar pools por dependência ou cliente

RequisiçõesCargaBulkhead PIX8 slots + fila de 16Bulkhead relatórios2 slots + fila de 2Core bancárioHTTPErrorBulkheadFullrejeição imediataPIXrelatório regulatóriofila cheia

Como funciona

  1. 1

    Semáforo com maxConcurrent e fila FIFO de maxQueueDepth por carga

  2. 2

    Slot livre roda; sem slot espera; fila cheia → ErrorBulkheadFull

  3. 3

    Slot liberado no finally vai ao mais antigo da fila

  4. 4

    Lei de Little: 200 PIX/s × 20 ms ≈ 4 slots, dobrado para pico

Nível
introdutório
Infraestrutura
A — código puro
Domínio financeiro
PIXLiquidação
Abrir a implementação completa

README.mdpattern/resilience/bulkhead

thiagoeti/pattern/bulkhead

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.

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.

Como funciona

  1. Semáforo com maxConcurrent e fila FIFO de maxQueueDepth por carga
  2. Slot livre roda; sem slot espera; fila cheia → ErrorBulkheadFull
  3. Slot liberado no finally vai ao mais antigo da fila
  4. Lei de Little: 200 PIX/s × 20 ms ≈ 4 slots, dobrado para pico

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

Executar

bun install
bun run demo

Saída: 20/20 PIX liquidados em cerca de 100 ms; 4/10 relatórios gerados e 6 descartados pelo próprio bulkhead.

Trade-offs

Vantagem Desvantagem
Carga lenta não esgota as outras Capacidade ociosa não é emprestada
Rejeição imediata protege quem entra Dimensionar exige medir vazão e latência
Esc

↑ ↓ navegarEnter abrir239 resultados