The Bulkhead Pattern in .NET

aspnetcoredotnetpollyresilience
The Bulkhead Pattern in .NET

A payment provider's API slows down from 200 ms to 30 seconds. Your service keeps accepting requests, and each one parks on a call to the slow provider.

In-flight requests pile up, and each one holds whatever it acquired before the call, such as a database connection or a slot in a shared connection pool. An await on the slow call doesn't hold a thread, but any blocking code in the path (.Result, .Wait()) pins a thread-pool thread per request, and the pool adds threads too slowly to keep up. Soon requests that never touch the payment provider are timing out too, waiting for connections or threads the stuck requests are holding.

The provider only degraded, but your whole application went down.

That's the failure mode the bulkhead pattern exists to prevent.

Ships, Bulkheads, and Blast Radius

A ship's hull is divided by bulkheads into watertight compartments. A breach floods one compartment, not the vessel.

Applied to software: partition your finite resources (concurrent requests, connections, memory) into pools, one per dependency or workload. The slow payment provider gets a pool of, say, 20 concurrent calls. When it degrades, at most 20 requests are stuck waiting on it. Call number 21 is rejected immediately, and the other 980 requests your server can handle keep flowing to the code paths that still work.

Incoming requests split into separate per-dependency permit pools; the payments pool is full because the payment API degraded, while the shipping and catalog pools stay healthy and keep serving traffic

A bulkhead protects you from slowness, not just errors. A circuit breaker needs failures to trip. A dependency that answers every call successfully in 30 seconds never trips a naive breaker, but it will still exhaust your capacity. The bulkhead caps the damage from the very first slow call.

The Simplest Bulkhead: SemaphoreSlim

A bulkhead is a counted gate. SemaphoreSlim is exactly that:

public class PaymentGateway(HttpClient httpClient)
{
    // Max 20 concurrent calls to the payment provider.
    private static readonly SemaphoreSlim Bulkhead = new(20, 20);

    public async Task<PaymentResult> ChargeAsync(
        PaymentRequest request,
        CancellationToken ct)
    {
        // Wait up to 500 ms for a slot, then fail fast.
        if (!await Bulkhead.WaitAsync(TimeSpan.FromMilliseconds(500), ct))
        {
            throw new BulkheadRejectedException(
                "Payment gateway at capacity.");
        }

        try
        {
            var response = await httpClient.PostAsJsonAsync(
                "/v1/charges", request, ct);

            response.EnsureSuccessStatusCode();

            return (await response.Content
                .ReadFromJsonAsync<PaymentResult>(ct))!;
        }
        finally
        {
            Bulkhead.Release();
        }
    }
}

public class BulkheadRejectedException(string message) : Exception(message);

public record PaymentRequest(string OrderId, decimal Amount, string Currency);

public record PaymentResult(string ChargeId, string Status);

Register it as a typed client with builder.Services.AddHttpClient<PaymentGateway>(...); the semaphore is static, so every PaymentGateway instance shares the same 20 slots.

Those few lines encode two decisions:

  • The capacity (20). Start from the dependency's real limits and your worst-case math: 20 concurrent calls at a 30-second worst-case latency means at most 20 requests stuck waiting on this dependency, ever.
  • The wait budget (500 ms). Zero means reject instantly at capacity. A short wait absorbs bursts. A long wait recreates the original problem, just with a queue in front of it.

This works, but you're hand-rolling rejection, timeouts, and metrics. Polly v8 gives you the same semantics with those parts included.

Bulkheads in Polly v8

In Polly v7 there was a dedicated bulkhead policy. In Polly v8, it became the concurrency limiter, built on System.Threading.RateLimiting:

dotnet add package Polly.RateLimiting
using Polly;
using Polly.RateLimiting;

ResiliencePipeline pipeline = new ResiliencePipelineBuilder()
    // 20 concurrent executions, up to 10 waiting in queue.
    .AddConcurrencyLimiter(permitLimit: 20, queueLimit: 10)
    .Build();

var result = await pipeline.ExecuteAsync(
    async ct => await paymentClient.ChargeAsync(request, ct),
    cancellationToken);

When all 20 permits are taken and the queue of 10 is full, the pipeline throws RateLimiterRejectedException immediately. Map that exception to a 503 with a Retry-After header, and the caller gets an immediate "at capacity" response instead of a 30-second timeout.

Next, wire a limiter into each dependency's HttpClient:

dotnet add package Microsoft.Extensions.Http.Resilience
builder.Services.AddHttpClient("payments", client =>
{
    client.BaseAddress = new Uri("https://api.payment-provider.com");
})
.AddResilienceHandler("payments-bulkhead", pipeline =>
{
    pipeline.AddConcurrencyLimiter(permitLimit: 20, queueLimit: 10);
    pipeline.AddTimeout(TimeSpan.FromSeconds(5));
});

builder.Services.AddHttpClient("shipping", client =>
{
    client.BaseAddress = new Uri("https://api.shipping-provider.com");
})
.AddResilienceHandler("shipping-bulkhead", pipeline =>
{
    pipeline.AddConcurrencyLimiter(permitLimit: 50, queueLimit: 20);
    pipeline.AddTimeout(TimeSpan.FromSeconds(2));
});

Each named client is a compartment with its own limit. A slow payment provider cannot consume shipping's capacity, and vice versa. Note the timeout inside each pipeline: bulkheads and timeouts compound, because the timeout bounds how long each of the 20 permits can be held.

Rate Limiter vs Semaphore: Pick the Right Axis

People often reach for a rate limiter here, and it's the wrong tool for this job. The two limit different axes:

  • A rate limiter (fixed window, sliding window, token bucket) caps how many operations start per unit of time. It answers "am I sending too fast?". Use it for the outbound path when a vendor gives you a requests-per-second quota; that's client-side rate limiting.
  • A concurrency limiter / semaphore caps how many operations are in flight right now. It answers "how much of my capacity can this dependency tie up?". That's the bulkhead.

The difference shows up during slowdowns. At 100 requests per second and 200 ms latency, you average 20 in-flight calls. Latency degrades to 10 seconds and the rate hasn't changed at all, but in-flight jumps toward 1,000. A rate limiter waves all of it through. Only the concurrency limiter notices, because slowness raises the number of calls in flight while the arrival rate stays flat.

Use rate limiters for vendor quotas and bulkheads for slow dependencies. Busy systems often need both in the same pipeline.

How Do You Size and Monitor a Bulkhead?

A bulkhead that's never rejected anything is unverified, and one that rejects constantly is a bottleneck. Size it with Little's Law: in-flight = arrival rate x latency. Take the dependency's normal latency, your peak call rate, multiply, then add 50 to 100 percent headroom. For 50 calls per second at 200 ms, that's 10 in-flight on average, so a limit of 20 is comfortable and a limit of 200 is too loose to act as a bulkhead.

Then watch it in production with two numbers: rejection count and permit utilization. Pipelines built through DI (AddResilienceHandler or AddResiliencePipeline) report each rejection as an OnRateLimiterRejected event in the resilience.polly.strategy.events metric, while a pipeline from a plain ResiliencePipelineBuilder needs ConfigureTelemetry first.

Polly has no utilization metric, so create the ConcurrencyLimiter yourself, pass it to AddRateLimiter, and publish its GetStatistics() values (CurrentAvailablePermits, CurrentQueuedCount) as a gauge. Utilization pinned at 100 percent with rising rejections is your early warning that a dependency degraded. It's the same philosophy as building resilient cloud applications: make failure modes explicit and observable instead of discovering them during the outage.

One caveat: bulkheads add rejection as a new failure mode. Every caller must handle RateLimiterRejectedException deliberately, whether that's a 503, a fallback response, or shedding non-critical work first.

Summary

A bulkhead caps each dependency at its allotted share of your concurrency, no matter how slow it gets.

  • Use SemaphoreSlim when you want the mechanism with zero dependencies; use Polly v8's AddConcurrencyLimiter for rejection, queueing, and telemetry included.
  • Give each downstream dependency its own named HttpClient with its own concurrency limit.
  • Bulkheads limit in-flight work; rate limiters limit arrival rate. Slowness shows up as in-flight growth, so the bulkhead is the limit that catches it.
  • Size from arrival rate x latency with headroom, alert on rejections, and pair the bulkhead with a timeout so permits can't be held forever.

Frequently Asked Questions

What is the bulkhead pattern?

The bulkhead pattern partitions an application's resources (concurrent requests, connections, threads) into isolated pools, one per dependency or workload. When one dependency slows down or fails, it can only exhaust its own pool, so the rest of the application keeps working.

How do I implement a bulkhead in .NET?

The simplest bulkhead is a SemaphoreSlim capping concurrent calls to a dependency. In Polly v8, the equivalent is the concurrency limiter strategy added with AddConcurrencyLimiter from the Polly.RateLimiting package, which also supports a bounded queue and reports rejections through pipeline telemetry.

What is the difference between a bulkhead and a rate limiter?

A bulkhead limits how many operations are in flight at the same time, regardless of how fast they arrive. A rate limiter caps how many operations start per time window, regardless of how long they run. Slow-dependency protection needs concurrency limiting, because slowness increases in-flight count, not arrival rate.

Is a bulkhead the same as a circuit breaker?

No. A circuit breaker reacts to failures by stopping calls after the fact. A bulkhead limits resource consumption up front, even when every call still succeeds slowly. They complement each other: the bulkhead contains the damage while the breaker decides when to stop calling.

  • Polly v8 replaced policies with resilience pipelines: a rewritten core with allocation-free execution, built-in telemetry, and one composition model instead of PolicyWrap. Here is how the new API maps to the old one, how to register pipelines with DI, and why the order you add strategies changes what your pipeline does.

  • Retry and circuit breaker assume opposite things about a failure. Retries assume it is transient and try again; breakers assume it is systemic and stop calling the dependency. When you use both, the order decides which one sees a failure first. Here is the Polly v8 pipeline that composes them, with the breaker inside the retry.

  • You have retries, circuit breakers, and timeouts configured. Have you ever seen them fire? Simmy injects faults, latency, and bad responses into your Polly pipelines so you can prove your resilience policies work before a real outage tests them. Fault injection often turns up a policy that was a misconfigured no-op.

Browse all Resilience guides →
Loading comments...

Go deeper

Whenever you're ready, there are 5 ways I can help you:

  1. Learn to deploy and run your apps on a VPS with Dokploy and Tailscale. Keep administration private, automate releases, and practice restoring backups, with source code and a runbook you can reuse.

  2. Join 5,000+ students in this comprehensive course that will teach you the system I use to ship production-ready applications using Clean Architecture. Learn how to apply the best practices of modern software architecture.

  3. Join 2,800+ engineers in this in-depth course that will transform the way you build modern systems. You will learn the best practices for applying the Modular Monolith architecture in a real-world scenario.

  4. Join 1,900+ students in this course that will teach you how to build production-ready REST APIs using the latest ASP.NET Core features and best practices. It includes a fully functional UI application that we'll integrate with the REST API.

  5. Join a community of 5,000+ engineers and software architects. You will also unlock access to the source code I use in my YouTube videos, early access to future videos, and exclusive discounts for my courses.

The .NET Weekly

One practical .NET tip, every Saturday.

Join 66,000+ engineers who read it. Free, and you can unsubscribe any time.