Bulkhead pattern: isolating failures so one slow dependency can't consume shared resources (threads, sockets, DB connections, memory), outbound bulkheads with Polly v8 concurrency limiters (Polly.RateLimiting, RateLimiterRejectedException) and the standard resilience handler's limiter (1,000 permits, queue 0), separate named HttpClients and MaxConnectionsPerServer, inbound bulkheads with ASP.NET Core AddRateLimiter concurrency policies, separate queues/consumers and MaxConcurrentCalls, bulkhead vs rate limiting, sizing with Little's Law, and rejection handling.
A bulkhead partitions shared resources so one failing dependency can only exhaust its own share, like the watertight compartments in a ship. In .NET the shared resources are thread-pool threads, sockets, database connection-pool slots, memory and request slots.
AddConcurrencyLimiter, or the standard handler's limiter (1,000 permits, queue 0 by default). Give each dependency a separate named HttpClient with MaxConnectionsPerServer.AddRateLimiter concurrency policies per endpoint group.MaxConcurrentCalls.A bulkhead limits concurrent work. Rate limiting limits requests per time window. Size limits with Little's Law (concurrency = rate x latency) plus headroom, and pair them with timeouts. The trade-off is containment against rejecting work when a compartment is full.
"The name comes from ships: the hull is split into watertight compartments, so one breach floods one compartment, not the ship. In a service, the 'water' is a slow dependency, and the compartments are whatever resources requests share. In async .NET it's rarely threads themselves. It's outstanding requests holding memory, sockets to a host, database connection-pool slots held while waiting, and Kestrel request capacity. If a shipping-rates API goes from 200 ms to 30 seconds, and nothing limits how many calls to it can be in flight, those calls pile up until they've used everything, and endpoints that never call shipping start failing too.
So I put a limit around each dependency. Outbound, that's a concurrency limiter in the resilience pipeline: Polly's
AddConcurrencyLimiter, or the rate limiter at the front ofAddStandardResilienceHandler, which is actually a concurrency limiter with 1,000 permits and no queue by default. That default is too generous for most dependencies, so I size it. Each dependency gets its own typedHttpClient, its own pipeline and its ownMaxConnectionsPerServer, so they don't share fate. Inbound, ASP.NET Core's rate-limiting middleware has a concurrency limiter I attach to expensive endpoint groups, like reports, so a burst of report requests can't starve checkout. For messaging, I give slow message types their own subscription and consumer with their ownMaxConcurrentCalls. When a compartment is full, calls are rejected immediately withRateLimiterRejectedExceptionor a 503, which is the point: failing fast in one compartment beats failing slowly everywhere. For example, at [company] [a slow PDF-rendering dependency used up all [n] database connections because callers held them while waiting]. I [added a concurrency limit of [n] on the PDF client and moved the call outside the transaction], and [checkout was unaffected in the next PDF outage].People confuse this with rate limiting. A rate limiter says 'no more than 100 requests per second': it's about throughput, fairness and quotas. A bulkhead says 'no more than 40 in flight at once': it's about isolation, and it automatically tightens when the dependency slows down, because each call holds its permit longer. For sizing I use Little's Law: at 200 requests a second and 100 ms latency, about 20 are in flight; I'd allow around 40. A bulkhead turns 'one dependency is slow' into 'one feature is degraded', but only if every shared resource is in a compartment."
| Resource at risk | Bulkhead |
|---|---|
| Outbound calls to one dependency | Concurrency limiter in its resilience pipeline |
| Sockets to one host | Separate typed HttpClient + MaxConnectionsPerServer |
| Inbound request capacity | ASP.NET Core AddConcurrencyLimiter policy per endpoint group |
| DB connection pool | Don't hold connections across external calls; separate pools/connection strings for heavy jobs |
| Message processing | Separate queue/subscription + consumer MaxConcurrentCalls |
| CPU-heavy work | Bounded Channel<T> with a fixed number of workers |
| Whole workloads | Separate deployments/node pools (cell-style isolation) |
| Bulkhead (concurrency limit) | Rate limit | |
|---|---|---|
| Limits | In-flight work at once | Requests per time window |
| Reacts to slowness | Yes: slower calls hold permits longer | No |
| Main purpose | Isolation, protect shared resources | Throughput, quotas, fairness |
| .NET API | ConcurrencyLimiter, Polly AddConcurrencyLimiter |
FixedWindowRateLimiter, SlidingWindowRateLimiter, TokenBucketRateLimiter |
After adding per-dependency concurrency limits (pricing 60, PDF rendering 10, address validation 20) and an inbound limit of 8 concurrent report requests, a 25-minute PDF provider outage rejected about 4,000 PDF requests with a friendly "try again shortly", while checkout p95 stayed at 450 ms. In the previous outage, checkout had failed for 18 minutes.
Checks whether the candidate understands failure isolation in async .NET, can implement bulkheads at several layers, and can size them.
Green flags
Red flags
Nygard's Release It! names Bulkheads alongside Circuit Breaker and Timeouts as stability patterns. The principle is failure isolation: partition resources so a fault can't spread.
WITHOUT WITH
Requests --> [ shared pool of N ] Requests --> [ pricing: 60 ] --> Pricing API
| | | --> [ pdf: 10 ] --> PDF API (slow!) -> rejects fast
Pricing PDF(slow) Address --> [ address: 20] --> Address API
PDF calls pile up, take all N, PDF can only use its 10; others unaffected
everything waits
.Result) does, causing starvation.SocketsHttpHandler pools connections per host; MaxConnectionsPerServer defaults to unlimited.Max Pool Size defaults to 100. Holding a connection (or transaction) while awaiting an external call ties it up.A bulkhead should protect whichever of these the dependency can exhaust.
Polly v8 has no dedicated bulkhead strategy; v7's BulkheadPolicy is replaced by the rate limiter strategy backed by System.Threading.RateLimiting. AddConcurrencyLimiter(permitLimit, queueLimit) (Polly.RateLimiting) lets permitLimit executions run, queues up to queueLimit, and rejects the rest with RateLimiterRejectedException. In AddStandardResilienceHandler, the outermost strategy is a concurrency limiter configured through options.RateLimiter.DefaultRateLimiterOptions (default PermitLimit 1,000, QueueLimit 0). Because it's outermost, rejected calls don't consume retries or breaker samples.
One typed client per dependency gives each its own handler chain, pipeline, breaker and connection pool. Calling three services through one generic HttpClient merges their fates.
ASP.NET Core's rate-limiting middleware (AddRateLimiter, UseRateLimiter, RequireRateLimiting) supports a concurrency limiter policy. Attach tight limits to expensive endpoints so they can't use all of the server's capacity. Set RejectionStatusCode (503 for overload, 429 for quotas) and optionally Retry-After.
Separate queues or subscriptions per message type or priority, each with its own consumer and MaxConcurrentCalls. A slow GenerateInvoicePdf consumer then can't delay PaymentReceived processing. Bounded Channel<T> with N workers does the same in process.
L = λ × W: average in-flight requests = arrival rate × average latency. At 200 requests/s and 100 ms, L = 20. Set the limit with headroom (about 2x, so 40), measure p99 latency, and revisit. During an outage latency rises; the limit caps in-flight calls, so at 30 s latency only 40 calls are waiting rather than 6,000. Keep queues short: a long queue just converts rejection into latency.
Rejections are expected, so make them cheap and clear: return a fallback, a 503 with Retry-After, or enqueue for later. Log at Information, not Error, and chart the rejection rate per bulkhead.
dotnet-counters (System.Net.Http connections, ThreadPool queue length) with and without a concurrency limit of 20.DbContext transaction while awaiting the slow stub and watch SqlClient pool exhaustion.bombardier or k6).Outbound bulkheads per dependency, an inbound bulkhead for an expensive endpoint, and connection limits.
using System.Threading.RateLimiting;
using Microsoft.AspNetCore.RateLimiting;
using Microsoft.Extensions.Http.Resilience;
using Polly;
var builder = WebApplication.CreateBuilder(args);
// Outbound bulkhead 1: standard handler, with its concurrency limiter sized for this dependency
builder.Services.AddHttpClient<PricingClient>(c => c.BaseAddress = new Uri("https://pricing.internal"))
.ConfigurePrimaryHttpMessageHandler(() => new SocketsHttpHandler
{
MaxConnectionsPerServer = 60, // this host can't take every socket
PooledConnectionLifetime = TimeSpan.FromMinutes(2)
})
.AddStandardResilienceHandler(o =>
{
o.RateLimiter.DefaultRateLimiterOptions.PermitLimit = 60; // ~2x normal in-flight (Little's Law)
o.RateLimiter.DefaultRateLimiterOptions.QueueLimit = 0; // reject immediately when full
o.AttemptTimeout.Timeout = TimeSpan.FromSeconds(2); // permits are released quickly
});
// Outbound bulkhead 2: a slow, non-critical dependency gets a small compartment
builder.Services.AddHttpClient<PdfRenderClient>(c => c.BaseAddress = new Uri("https://pdf.example.com"))
.AddResilienceHandler("pdf", pipeline =>
{
pipeline.AddConcurrencyLimiter(permitLimit: 10, queueLimit: 5); // Polly.RateLimiting
pipeline.AddTimeout(TimeSpan.FromSeconds(20));
});
// Inbound bulkhead: expensive reports can't use all server capacity
builder.Services.AddRateLimiter(o =>
{
o.RejectionStatusCode = StatusCodes.Status503ServiceUnavailable;
o.AddConcurrencyLimiter("reports", c =>
{
c.PermitLimit = 8;
c.QueueLimit = 16;
c.QueueProcessingOrder = QueueProcessingOrder.OldestFirst;
});
o.OnRejected = (ctx, _) =>
{
ctx.HttpContext.Response.Headers.RetryAfter = "10";
return ValueTask.CompletedTask;
};
});
var app = builder.Build();
app.UseRateLimiter();
app.MapGet("/reports/{id:int}", async (int id, PdfRenderClient pdf, CancellationToken ct) =>
Results.File(await pdf.RenderAsync(id, ct), "application/pdf"))
.RequireRateLimiting("reports");
app.MapGet("/prices/{sku}", (string sku, PricingClient pricing, CancellationToken ct) => pricing.GetAsync(sku, ct)); // unaffected by report load
app.Run();
using Polly.RateLimiting;
public sealed class PdfRenderClient(HttpClient http, ILogger<PdfRenderClient> logger)
{
public async Task<byte[]> RenderAsync(int reportId, CancellationToken ct)
{
try
{
return await http.GetByteArrayAsync($"/render/{reportId}", ct);
}
catch (RateLimiterRejectedException)
{
// Expected when the compartment is full: cheap, clear, logged at Information
logger.LogInformation("PDF bulkhead full; rejecting report {ReportId}", reportId);
throw new ServiceBusyException("Report rendering is busy. Please try again shortly.");
}
}
}
public sealed class ServiceBusyException(string message) : Exception(message);
public sealed class PricingClient(HttpClient http)
{
public Task<decimal> GetAsync(string sku, CancellationToken ct) => http.GetFromJsonAsync<decimal>($"/prices/{sku}", ct);
}
HttpClient and pipeline for several dependencies. Why it is wrong: A slow host consumes the shared connections, permits and breaker, so healthy dependencies fail too. Instead: A typed client and pipeline per dependency.Bulkheads are only as good as their coverage: if pricing has a limiter but holds DB connections across the call, the database pool is still the shared compartment. I start by listing what a slow dependency could exhaust (sockets, DB connections, memory, request slots) and put a limit in front of each, sized from real traffic and paired with timeouts so permits come back.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Concurrency limiter per outbound client | Every external dependency | Rejections under load; sizing | Never really wrong |
| Separate typed clients | Multiple dependencies | A little more registration | Single dependency |
| Inbound concurrency policy | Expensive endpoints (reports, exports) | Users see 503s at peak | Cheap endpoints |
| Separate queues/consumers | Mixed message types, priorities | More entities to operate | Uniform, fast messages |
| Separate deployments/cells | Critical vs non-critical workloads, noisy tenants | Infrastructure cost | Small systems |
| Rate limiting | Quotas, fairness, protecting a partner's API | Doesn't react to latency | As the isolation mechanism |
I measure in-flight calls and rejections per bulkhead, DB pool usage, and, the real test, whether unrelated endpoints keep their p95 during a dependency outage (chaos testing in staging).
Unbounded concurrency means starting as much concurrent work as the input demands, with no cap: Task.WhenAll over every item, Task.Run per request, unbounded queues, unlimited outgoing connections. Under load it exhausts something: memory, database connection pools (100 by default in SqlClient), sockets, downstream rate limits or CPU, and latency collapses for everyone. Little's law (concurrency = throughput × latency) shows that when a dependency slows down, in-flight work grows without bound. Put limits at each layer: SemaphoreSlim or Parallel.ForEachAsync for fan-out, bounded channels for queues, ASP.NET Core rate limiting (concurrency or token bucket) for inbound requests, MaxConnectionsPerServer for outbound HTTP, and bulkheads per dependency.
Backpressure is a way for a slow consumer to make producers slow down, instead of letting work pile up until something breaks. The four strategies are block (producer waits), bounded buffer, drop (shed lower-value work) and reject (tell the caller to retry later). In .NET: bounded Channel<T> with WriteAsync (block), BoundedChannelFullMode.DropOldest (drop), TryWrite plus HTTP 429/503 with Retry-After (reject), pull-based IAsyncEnumerable<T>, and broker settings such as prefetch count and max concurrent calls so consumers only take what they can process. Every boundary needs a chosen strategy and metrics for queue depth and age.
System.Threading.Channels provides fast, async-friendly queues for passing data between producers and consumers. Channel.CreateBounded<T>(capacity) gives backpressure: when full, WriteAsync waits (or drops items, depending on BoundedChannelFullMode). Channel.CreateUnbounded<T>() never blocks writers but can grow without limit. Writers call Complete() when done; readers loop with await foreach (var x in reader.ReadAllAsync(ct)) and finish when the channel is completed and empty. Options such as SingleReader and SingleWriter enable faster internal implementations. Channels are the standard building block for in-process background queues and pipelines.
Unrelated requests failing means the slow API exhausted a shared resource: usually database connections held while waiting, sockets, or thread-pool threads (from sync-over-async).
Diagnose: Application Insights dependency durations, then dotnet-counters for the thread pool, SqlClient pool and HTTP connections, then dotnet-dump to see what requests are waiting on. Look for the 100 s HttpClient default timeout multiplied by retries.
Mitigate: a feature flag that switches to a fallback (flat-rate shipping).
Fix:
The trade-off is a slightly degraded feature against a whole service going down.
How to tell it (STAR)
**S:** At [company], a PDF provider slowdown took down checkout and every other endpoint for [18] minutes. **T:** I led the investigation and had to make sure one non-critical dependency could never do that again. **A:** `dotnet-counters` showed the SQL pool pinned at 100, and a dump showed requests waiting on PDF calls inside open transactions. I switched PDFs to async with a feature flag, then moved rendering to a queue consumer via the outbox, added a 10-permit concurrency limiter and timeout on the PDF client, and a chaos test for it. **R:** In the provider's next outage, about [4,000] PDF jobs were delayed but checkout p95 stayed at [450 ms] and no orders were lost.
Last updated 18 Nov 2026.