Pular para o conteúdo

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.

passos
4
arquivos
5
testes
0
tecnologias
3

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

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

6 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

  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 Little200 PIX/s × 20 ms ≈ 4 slots, dobrado para pico

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

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

./

  • .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: 20/20 PIX liquidados em cerca de 100 ms; 4/10 relatórios gerados e 6 descartados pelo próprio bulkhead.

Requisitos
Bun

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

Por que se relacionam

Teste rápido

Qual é o próximo passo depois de Bulkhead?

Próximo projeto, ResiliênciaChaos Engineering
Esc

↑ ↓ navegarEnter abrir239 resultados