How-To Guide

How to Implement Bulkhead Isolation

Give each dependency its own connection pool, semaphore, and queue so one slow service cannot starve the rest of the ship.

On this page

  1. Introduction
  2. Shared fate is the default
  3. Map compartments by dependency
  4. Bound the compartment
  5. What full means
  6. Instrument every compartment
  7. Test starvation and recovery
  8. Common pitfalls
  9. Conclusion

Introduction

The bulkhead is a shipbuilding idea that software borrowed for a good reason: compartments below the waterline keep one hull breach from sinking the vessel. In a service, the hull is the process and the compartments are its resources, connection pools, threads, memory, and the breach is a dependency that turns slow. One slow dependency on a shared connection pool occupies every connection; requests to healthy dependencies queue behind them and time out; the service is fully down even though ninety percent of its dependencies are fine. The failure cascades through shared resources, and the fix is to not share them: each dependency gets its own bounded pool of connections, its own concurrency semaphore, its own queue, so a slow dependency can exhaust only its own compartment and the rest of the system keeps serving. This tutorial maps dependencies to compartments, sizes them honestly, implements the semaphore pattern in three runtimes, decides what full means, fast rejection or bounded waiting, and instruments the compartments so starvation shows up in graphs before it shows up in tickets.

Shared fate is the default

The failure worth understanding is the default architecture, which shares everything. A single database pool serves every query; a single HTTP client with its default agent serves every API; a single thread pool executes every task. Under a slow dependency, the arithmetic is brutal: a dependency whose latency rises from 50 to 5,000 milliseconds holds each of its requests, and each held request holds a connection or thread for 100 times longer, so a pool sized for 50 concurrent requests now serves half a request per slot, and everything queued behind it waits. The dependency that is slow is unaffected by the queue, it is slow, that is its problem, the damage is done to the healthy dependencies whose requests sit in the same queue. This is why “the database is slow” incidents so often present as “everything is timing out”, and why adding pool capacity during such an incident makes it worse, more requests now reach the slow dependency and hold more resources for longer. The diagnosis is structural: measure per-dependency latency and per-pool queue depth during the incident, and the shared pool shows uniform saturation regardless of which dependency is misbehaving.

Map compartments by dependency

Compartment design starts with the dependency inventory, and each entry gets three attributes. Criticality: does the product work without it, payment authorization is critical, recommendation blending is not, which determines whether a full compartment should fail the request or degrade it. Latency profile: p50 and p99 determine pool sizing, a 10-millisecond dependency and a 2-second dependency need very different concurrency for the same throughput, by Little’s law, concurrency equals rate times latency. Failure correlation: dependencies that share an upstream, a cloud provider, a network path, fail together, and correlated compartments can be merged or at least sized with their correlation in mind. The default assignment is one compartment per dependency host, plus a separate compartment for anything user-facing versus anything background, because background jobs flooding a compartment should never take the interactive path down with them. The anti-pattern to reject is the global default pool inherited by every new dependency, which silently re-creates shared fate the moment a teammate adds a client without noticing there is no pool to notice.

Bound the compartment

The compartment has two knobs, concurrency and queue depth, and both derive from arithmetic rather than defaults. Concurrency, via semaphore or pool size: target throughput times p99 latency, plus headroom, which is Little’s law applied per dependency, so the fast internal dependency gets a small compartment and the slow third-party API gets a larger one sized to its quota. Queue depth: zero for interactive requests, where waiting is nearly as bad as failing and the caller’s timeout budget is better spent on the attempt, and small-but-nonzero for background work, where a bounded queue absorbs bursts and applies backpressure to producers.

export class Bulkhead {
 private active = 0;
 private readonly queue: Array<() => void> = [];

 constructor(readonly name: string,
       private readonly maxConcurrent: number,
       private readonly maxQueue: number) {}

 async run<T>(task: () => Promise<T>): Promise<T> {
  await this.acquire();
  try {
   return await task();
  } finally {
   this.release();
  }
 }

 private acquire(): Promise<void> {
  if (this.active < this.maxConcurrent) {
   this.active++;
   return Promise.resolve();
  }
  if (this.queue.length >= this.maxQueue) {
   return Promise.reject(new BulkheadFullError(this.name));
  }
  return new Promise<void>(resolve => this.queue.push(resolve));
 }

 private release() {
  const next = this.queue.shift();
  if (next) { next(); return; }
  this.active--;
 }
}

Go’s x/sync/semaphore, Python’s asyncio bounded semaphores, and Tokio’s semaphore provide the same primitive natively; the hand-rolled version above exists to make the two knobs and the rejection path explicit.

What full means

A full compartment has two honest behaviors and one dishonest one. Fast rejection: the request fails immediately with a distinct error, bulkhead-full for dependency X, which the caller can handle by degrading, serving cached data, skipping the optional enrichment, or surfacing a partial result. Bounded waiting: the request enters the compartment queue with its own timeout, appropriate for background work and for dependencies whose slowness is bursty rather than persistent. The dishonest behavior is unbounded waiting, the default of a naive pool, where the request sits in a queue with no deadline, holding the caller’s connection while the compartment drains at the pace of the slowest dependency. The error type matters as much as the behavior: bulkhead-full must be distinguishable from dependency-unavailable and from timeout, because the three call for different responses, and conflating them means the caller’s retry logic retries into a full compartment, which is exactly the wrong move. Export the compartment state with the error, queue depth and expected wait, so the caller’s backoff can be informed rather than guessed.

Instrument every compartment

Bulkheads are invisible until they fire, and the metrics that make them visible are per compartment, not aggregate: active concurrency versus capacity, which is saturation; queue depth over time, which shows burstiness versus sustained overload; rejection or timeout rate, which is the compartment protecting the process; and wait time in queue for the bounded-waiting shape. Graphed per dependency, these four answer the diagnostic question from the shared-fate section instantly: during an incident, the healthy compartments show flat low saturation while the slow dependency’s compartment pins at capacity with a rising rejection rate, and the contrast is the diagnosis. Alert on sustained saturation rather than momentary bursts, and alert on rejection rate crossing a threshold, because rejections mean the compartment is doing its job but also that users are feeling it, which is the signal to resize or to fix the dependency. The instrumentation also pays for capacity planning: saturation trends show which compartments are growing toward their bounds before the rejections start.

Test starvation and recovery

The bulkhead’s contract is specific and testable: a slow dependency degrades only its own compartment. The starvation test: with compartment A’s dependency hung, saturate A with concurrent calls, and assert calls to compartment B’s healthy dependency complete at full speed throughout, which is the entire property. The rejection test: exceed A’s concurrency plus queue and assert the excess calls fail fast with the bulkhead-full error, not with a generic timeout, and that the error carries the compartment name. The recovery test: unhang the dependency and assert the compartment drains, the queue empties, and rejections stop, within a bounded interval, because a compartment that never recovers its slots, a leaked semaphore permit, converts the protection into a permanent capacity cut, which is worse than the disease. The sizing test: assert that the derived sizes hold under generated load, throughput at p99 latency within the compartment bound. These tests are the difference between a bulkhead that exists in configuration and one that exists in fact, and the leak test especially belongs in CI, run repeatedly, because permit leaks are the classic way this pattern rots.

sem := semaphore.NewWeighted(8)
ctx, cancel := context.WithTimeout(ctx, 50*time.Millisecond)
if err := sem.Acquire(ctx, 1); err != nil {
 return BulkheadFullError{name: "payments"}
}
defer sem.Release(1)

Common pitfalls

  • One pool to rule them all. Shared fate by default; the slow dependency owns every connection and the outage is total.
  • **Global defaults for new clients. ** Every dependency added without an explicit compartment silently re-creates the shared pool.
  • **Unbounded queues. ** The dishonest behavior: callers wait without deadline at the pace of the slowest dependency.
  • **Generic timeout instead of bulkhead-full. ** Callers retry into the full compartment; the distinct error is what enables degradation.
  • **Leaked permits. ** A compartment that never releases slots becomes a permanent capacity cut; test for leaks in CI.
  • **Background and interactive sharing a compartment. ** A nightly job flooding the pool takes the user-facing path down with it.

Conclusion

Bulkhead isolation converts total outages into partial ones by refusing to share resources across dependencies. Map each dependency to its own compartment sized by Little’s law from its latency profile, separate interactive from background traffic, and give each compartment two explicit knobs, concurrency and queue depth, rather than inheriting global defaults. When the compartment is full, fail fast with a distinct, named error carrying queue state, so callers degrade instead of retrying into the wall, and instrument saturation, depth, and rejections per compartment so the diagnostic contrast, one pinned graph among flat ones, is visible during the incident. Test the property itself, healthy compartments at full speed while a sibling hangs, plus rejection semantics and leak-free recovery. The pattern is cheap, the arithmetic is honest, and the failure mode it removes, one slow dependency taking everything down, is among the most common and most preventable in production.

Sources: Azure architecture: bulkhead pattern, Go: semaphore package, Tokio: Semaphore.

FAQ

How is this different from rate limiting?
Rate limiting caps the total requests a caller may send. Bulkheading caps the concurrent resources each dependency may consume inside your process. The first protects the server from the client; the second protects your other dependencies from each other.
Why not one big pool for everything?
A shared pool is a shared fate: one slow dependency holds all the connections and every other dependency queues behind it. Isolation per dependency converts a total outage into a partial one, which is the entire value proposition.
Should compartments share threads or event loops?
Event-loop runtimes like Node share one loop, so CPU-heavy work needs worker pools or process-level separation as the compartment. Thread-per-request runtimes need bounded pools per dependency. The principle is the same; the mechanism differs.

Related Examples