Bulkhead Pattern
Partition concurrency slots, connection pools and other resources by dependency so one slow service cannot exhaust capacity needed by other calls.
· Last updated: 2026-11-05 · 14 min read
Overview
Suppose an order server talks to both a payment service and a product catalog service through a single shared pool of two concurrent outbound calls. Then the payment service hangs. Two stuck payment requests occupy both slots indefinitely, and the very next catalog request fails with catalog: rejected by shared even though the catalog service itself is completely healthy.
The Bulkhead pattern stops that spillover by walling off resources per dependency, just like watertight bulkheads in a ship's hull keep a single breached compartment from sinking the vessel, so giving payments two dedicated slots and the catalog its own two slots ensures a stalled payment gateway can only exhaust payment capacity while catalog browsing keeps humming.
In the examples below, the partitioned resource is a concurrency slot representing one in-flight call. A semaphore tracks remaining slots, decrementing on entry and releasing on exit, and pairing that semaphore with a bounded queue forms one bulkhead for a target dependency.
What happens when every slot in a bulkhead is busy? Rejecting the call on the spot (fail fast) lets the caller fall back to a cached response or an error banner immediately, whereas placing a small bounded queue in front absorbs brief traffic spikes and rejects only once both the execution slots and the queue are full.
Other designs partition connection pools, thread pools, message queues or service instances instead of slots, and may partition by customer, or tenant, instead of dependency. Either way, one dependency or customer can exhaust only its own allocation.1
Structure
In the diagram above, Program instantiates separate payment and catalog Bulkhead objects, each combining a SemaphoreSlim for execution slots with an admitted counter for running-plus-queued calls so requests exceeding both limits return Rejected immediately.
History
The metaphor comes straight from naval architecture: Microsoft's Azure Architecture Center notes that just as watertight hull compartments keep a single hull breach from sinking a ship, partitioning application elements into isolated pools (sometimes called cell-based architecture) keeps one failing dependency from taking down the rest.2
Michael Nygard brought the pattern into mainstream production engineering in Release It! (Pragmatic Bookshelf, 2007), placing 5.3 Bulkheads right alongside 5.1 Use Timeouts and 5.2 Circuit Breaker under Stability Patterns in both the 2007 first edition and the January 2018 second edition.34
Netflix's Hystrix later popularized per-dependency thread pools and semaphores in JVM microservices.5
In .NET, Polly evolved from Policy.Bulkhead(maxParallelization, maxQueuingActions) in v7 to the AddConcurrencyLimiter(permitLimit, queueLimit) strategy in v8 (Polly.RateLimiting), a thin layer atop System.Threading.RateLimiting.ConcurrencyLimiter.678 Different primitives, same hard cap.
Why use it?
Above all, bulkheads stop a single slow dependency from dragging unrelated features down in a cascading failure. Azure's architecture guidance highlights three payoffs: containing faults inside one pool, keeping the rest of the application running during partial outages, and dedicating capacity to high-priority consumers.9
Failing fast when a partition is full also frees calling threads and sockets from piling up behind a dead upstream, letting the caller decide right away whether to serve a fallback or schedule a retry.
A bulkhead alone, however, will never evict a hung call that is already inside a slot! Without a Timeout pattern to bound how long a call may hold its slot, a limitation Netflix's Hystrix documentation explicitly calls out for semaphore isolation10, stuck requests lock up the partition forever, and stopping traffic to a dependency that is already known to be down is the job of a Circuit Breaker pattern.11
Hard walls also trade away pooling efficiency: a burst of catalog traffic cannot borrow idle payment slots, and slicing a system into too many tiny bulkheads leaves capacity stranded while multiplying the knobs you have to tune and monitor.12
A semaphore inside one process partitions only that process's calls. With several server instances, each has its own limits, and process-wide resources such as CPU and memory remain shared. Isolating those resources requires deploying services into separate virtual machines, containers or processes.11
Slot capacity and queues
Every bulkhead comes down to two numbers: maximum concurrent execution slots and maximum queued waiters. Set the queue length to zero for pure fail-fast behavior, or add a small bounded queue to smooth over micro-bursts, remembering that queued callers still burn memory and latency, and that an unbounded queue in front of a dead dependency defeats the bulkhead entirely.
How do you size a partition in practice? Measure the dependency's baseline concurrency and latency distribution, track occupied slots and rejections per partition in production (Azure likewise recommends per-partition SLA monitoring and prefers platform-level API-gateway or container limits over reinventing them in application code),1113 and remember that Polly v8's rate-limiter strategy defaults to PermitLimit = 1000 with QueueLimit = 0, throwing RateLimiterRejectedException when capacity runs out.14
Finally, keep bulkhead rejection distinct from downstream failure: “this partition is full” (Rejected) is a local admission decision by the caller, whereas “the remote service threw an error” (Failed) comes from across the network, and distinguishing the two in your return type lets callers react appropriately.
Example
How do we test this without sleeping in real time? The example below uses a TaskCompletionSource gate that stays incomplete until SetResult is called, pairing it with Wait(0) (which returns false immediately when no slot is free) across both a shared bulkhead and separate per-dependency bulkheads.15
using System;
using System.Threading;
using System.Threading.Tasks;
var shared = new Bulkhead("shared", 2);
await Scenario("one shared bulkhead", payments: shared, catalog: shared);
await Scenario("separate bulkheads", payments: new Bulkhead("payments", 2), catalog: new Bulkhead("catalog", 2));
static async Task Scenario(string title, Bulkhead payments, Bulkhead catalog)
{
Console.WriteLine($"== {title} ==");
// Stalled payments: calls remain incomplete until their gate opens.
var paymentGate = new TaskCompletionSource<string>(TaskCreationOptions.RunContinuationsAsynchronously);
var pay1 = payments.RunAsync(() => paymentGate.Task);
var pay2 = payments.RunAsync(() => paymentGate.Task);
Console.WriteLine("payment 3: " + await payments.RunAsync(() => paymentGate.Task));
Console.WriteLine("catalog: " + await catalog.RunAsync(() => Task.FromResult("ok")));
paymentGate.SetResult("ok");
Console.WriteLine("payment 1: " + await pay1);
Console.WriteLine("payment 2: " + await pay2);
}
sealed class Bulkhead(string name, int slots)
{
private readonly SemaphoreSlim semaphore = new(slots, slots);
public async Task<string> RunAsync(Func<Task<string>> call)
{
// Reject immediately if no slot is available. Without acquisition, there is nothing to release.
if (!semaphore.Wait(0)) return "rejected by " + name;
try
{
return await call();
}
finally
{
semaphore.Release();
}
}
}== one shared bulkhead ==
payment 3: rejected by shared
catalog: rejected by shared
payment 1: ok
payment 2: ok
== separate bulkheads ==
payment 3: rejected by payments
catalog: ok
payment 1: ok
payment 2: okThe contrast is immediate: the shared partition rejects the healthy catalog call, whereas separate partitions reject only the third payment call.
Extended example
Now give payments two execution slots plus one queue position (2 + 1) and the catalog two execution slots with zero queue (2 + 0), then fire four concurrent payment requests: the first two run, the third waits in the queue, the fourth immediately gets Rejected, and the moment pay-2 throws an exception its finally block releases a slot so pay-3 can advance (because SemaphoreSlim leaves pairing Wait and Release entirely up to you, forgetting to release on failure leaks capacity one slot at a time until the partition rejects every call forever).16
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
var payments = new Bulkhead("payments", maxConcurrent: 2, maxQueue: 1);
var catalog = new Bulkhead("catalog", maxConcurrent: 2, maxQueue: 0);
// Fake payment gateway: each call has a gate the program opens or faults.
var gates = new Dictionary<string, TaskCompletionSource<string>>();
foreach (var id in new[] { "pay-1", "pay-2", "pay-3", "pay-4", "pay-5" })
gates[id] = new TaskCompletionSource<string>(TaskCreationOptions.RunContinuationsAsynchronously);
Task<string> Pay(string id) => gates[id].Task;
var pay1 = payments.RunAsync(() => Pay("pay-1"));
var pay2 = payments.RunAsync(() => Pay("pay-2"));
var pay3 = payments.RunAsync(() => Pay("pay-3")); // No slot: wait in the queue.
var pay4 = payments.RunAsync(() => Pay("pay-4")); // The queue is full too: reject immediately.
Console.WriteLine("after 4 payment calls: " + payments.Describe());
Console.WriteLine("pay-4: " + Describe(await pay4));
Console.WriteLine("catalog-1: " + Describe(await catalog.RunAsync(() => Task.FromResult("item list"))));
gates["pay-2"].SetException(new InvalidOperationException("gateway reset"));
Console.WriteLine("pay-2: " + Describe(await pay2));
gates["pay-3"].SetResult("charged pay-3"); // Run in the slot returned by pay-2.
Console.WriteLine("pay-3: " + Describe(await pay3));
gates["pay-1"].SetResult("charged pay-1");
Console.WriteLine("pay-1: " + Describe(await pay1));
Console.WriteLine("after all calls: " + payments.Describe());
gates["pay-5"].SetResult("charged pay-5");
Console.WriteLine("pay-5: " + Describe(await payments.RunAsync(() => Pay("pay-5"))));
static string Describe(BulkheadResult<string> result) => result switch
{
BulkheadResult<string>.Ok ok => "ok: " + ok.Value,
BulkheadResult<string>.Rejected r => $"rejected: {r.Bulkhead} full (running {r.Running}, queued {r.Queued})",
BulkheadResult<string>.Failed f => "failed: " + f.Error.Message,
_ => "unknown result",
};
abstract record BulkheadResult<T>
{
public sealed record Ok(T Value) : BulkheadResult<T>;
public sealed record Rejected(string Bulkhead, int Running, int Queued) : BulkheadResult<T>;
public sealed record Failed(Exception Error) : BulkheadResult<T>;
}
sealed class Bulkhead(string name, int maxConcurrent, int maxQueue)
{
private readonly SemaphoreSlim slots = new(maxConcurrent, maxConcurrent);
private int admitted; // Running plus queued calls
public int Running => maxConcurrent - slots.CurrentCount;
public int Queued => Volatile.Read(ref admitted) - Running;
public string Describe() => $"{name} running={Running} queued={Queued}";
public async Task<BulkheadResult<T>> RunAsync<T>(Func<Task<T>> call)
{
// If execution slots and queue are full, return rejection without waiting.
if (Interlocked.Increment(ref admitted) > maxConcurrent + maxQueue)
{
Interlocked.Decrement(ref admitted);
return new BulkheadResult<T>.Rejected(name, Running, Queued);
}
var acquired = false;
try
{
// Wait if no slot is available. The finally below restores counters even if waiting throws.
await slots.WaitAsync();
acquired = true;
return new BulkheadResult<T>.Ok(await call());
}
catch (Exception ex)
{
// Dependency boundary: convert exceptions to failure results, retaining their type and stack.
return new BulkheadResult<T>.Failed(ex);
}
finally
{
// Always decrement admitted; release a slot only when actually acquired.
Interlocked.Decrement(ref admitted);
if (acquired) slots.Release();
}
}
}after 4 payment calls: payments running=2 queued=1
pay-4: rejected: payments full (running 2, queued 1)
catalog-1: ok: item list
pay-2: failed: gateway reset
pay-3: ok: charged pay-3
pay-1: ok: charged pay-1
after all calls: payments running=0 queued=0
pay-5: ok: charged pay-5Before copying this extended example into production, tighten its boundaries. Because WaitAsync here has no timeout, pay-3 waits indefinitely until a slot opens; production code should pass a timeout or CancellationToken, store the bool result of WaitAsync(timeout) in acquired, return Rejected when false, and ensure finally always decrements admitted while calling Release() only when acquired is true so cancelled waits never leak counters. You also need execution timeouts for hung calls like pay-1, an explicit FIFO structure if admission order matters (since SemaphoreSlim does not guarantee ordering17), awareness that Running and Queued are approximate snapshots under load, and metrics exported beyond a single process.
TypeScript example
This repeats the first C# scenario in TypeScript. Within one JavaScript execution environment, a number counting available slots limits concurrency. An async function runs synchronously until its first await, so the slot check and decrement happen when run is called. The gate stays incomplete until open resolves its Promise.
type CallResult =
| { ok: true; value: string }
| { ok: false; error: "BULKHEAD_FULL"; bulkhead: string };
// A small semaphore counting free slots; report success immediately without waiting.
class Semaphore {
#available: number;
constructor(slots: number) { this.#available = slots; }
tryAcquire(): boolean {
if (this.#available === 0) return false;
this.#available -= 1;
return true;
}
release(): void { this.#available += 1; }
}
class Bulkhead {
readonly #slots: Semaphore;
constructor(readonly name: string, slots: number) { this.#slots = new Semaphore(slots); }
async run(call: () => Promise<string>): Promise<CallResult> {
// Reject if acquisition fails. Never release a slot that was not acquired.
if (!this.#slots.tryAcquire()) return { ok: false, error: "BULKHEAD_FULL", bulkhead: this.name };
try {
return { ok: true, value: await call() };
} finally {
this.#slots.release();
}
}
}
// A gate pending until explicitly opened, simulating a stalled payment service.
function gate(): { promise: Promise<string>; open: (value: string) => void } {
let open: (value: string) => void = () => {};
const promise = new Promise<string>((resolve) => { open = resolve; });
return { promise, open };
}
function describe(result: CallResult): string {
return result.ok ? result.value : "rejected by " + result.bulkhead;
}
async function scenario(title: string, payments: Bulkhead, catalog: Bulkhead): Promise<void> {
console.log(`== ${title} ==`);
const paymentGate = gate();
const pay1 = payments.run(() => paymentGate.promise);
const pay2 = payments.run(() => paymentGate.promise);
console.log("payment 3: " + describe(await payments.run(() => paymentGate.promise)));
console.log("catalog: " + describe(await catalog.run(() => Promise.resolve("ok"))));
paymentGate.open("ok");
console.log("payment 1: " + describe(await pay1));
console.log("payment 2: " + describe(await pay2));
}
async function main(): Promise<void> {
const shared = new Bulkhead("shared", 2);
await scenario("one shared bulkhead", shared, shared);
await scenario("separate bulkheads", new Bulkhead("payments", 2), new Bulkhead("catalog", 2));
}
void main();== one shared bulkhead ==
payment 3: rejected by shared
catalog: rejected by shared
payment 1: ok
payment 2: ok
== separate bulkheads ==
payment 3: rejected by payments
catalog: ok
payment 1: ok
payment 2: okA call that fails to acquire a slot returns before entering try and has no slot to release. This semaphore has no queue; a slot never returns if its occupying call never finishes.
See also
Footnotes
- Microsoft Learn. Bulkhead pattern. Azure Architecture Center. Solution: separate connection pools per dependency. Problems and considerations: processes, thread pools, semaphores, queues and tenant partitions. ↩
- Microsoft Learn. Bulkhead pattern. Azure Architecture Center. Introduction and Tip. ↩
- Michael T. Nygard. Release It! Design and Deploy Production-Ready Software. Pragmatic Bookshelf, 2007. Publisher's table of contents (P3.0 printing, February 2009), 5.3 Bulkheads, p. 121. ↩
- Michael Nygard. Release It! Second Edition: Design and Deploy Production-Ready Software. Pragmatic Bookshelf, 2018. Publisher's table of contents, Create Stability > Stability Patterns. ↩
- Netflix. How it Works. Hystrix Wiki. ↩
- Polly. Migration guide from v7 to v8. Bulkhead section. ↩
- Polly. Rate limiter resilience strategy. ↩
- Microsoft Learn. ConcurrencyLimiter Class. ↩
- Microsoft Learn. Bulkhead pattern. Azure Architecture Center. Benefits listed under Solution. ↩
- Netflix. How it Works. Hystrix Wiki. Discussion of semaphore isolation. ↩
- Microsoft Learn. Bulkhead pattern. Azure Architecture Center. Problems and considerations. ↩
- Microsoft Learn. Bulkhead pattern. Azure Architecture Center. When to use this pattern. ↩
- Microsoft Learn. Bulkhead pattern. Azure Architecture Center. Built-in platform controls under Problems and considerations. ↩
- Polly. Rate limiter resilience strategy. Defaults table and exception list. ↩
- Microsoft Learn. SemaphoreSlim.Wait Method. Wait(Int32) Remarks. ↩
- Microsoft Learn. SemaphoreSlim Class. Remarks. ↩
- Microsoft Learn. SemaphoreSlim Class. Remarks: no FIFO or LIFO ordering is guaranteed when multiple threads wait. ↩