📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What is the Bulkhead pattern? Explain how you isolate dependencies in a .NET 10 service with concurrency limiters, separate named HttpClients and pipelines, connection limits, and separate queues or consumers, how a bulkhead differs from rate limiting, and how you size the limits.

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.

Senior Theory Advanced bulkhead concurrency design-patterns polly rate-limiting resilience

🎯 Key points

  • Bulkhead (ship compartments): partition shared resources so a failing or slow dependency can only exhaust its own share
  • In .NET the shared resources are thread-pool threads, sockets/connections, DB connection pool slots, memory and request slots, not dedicated threads
  • Polly v8 has no BulkheadPolicy (that was v7); use the rate limiter strategy on System.Threading.RateLimiting: AddConcurrencyLimiter(permitLimit, queueLimit), or the standard handler's RateLimiter (default 1,000 permits, queue 0); excess calls fail fast with RateLimiterRejectedException
  • Separate named/typed HttpClients per dependency, each with its own pipeline and SocketsHttpHandler.MaxConnectionsPerServer, so one host can't take every connection
  • Inbound bulkhead: ASP.NET Core AddRateLimiter with a concurrency limiter policy per endpoint group (e.g. reports limited to 8) returning 503/429 when full
  • Messaging bulkhead: separate queues/subscriptions and consumers with their own MaxConcurrentCalls, so a slow message type doesn't starve others
  • Bulkhead limits concurrent in-flight work (isolation); rate limiting limits requests per time window (throughput, fairness, quotas)
  • Size with Little's Law (200 rps x 0.1 s = 20 in flight, allow ~40), keep queues short, pair with per-attempt timeouts so permits are released, and track in-flight calls, rejection rate and DB pool usage per bulkhead to re-size

⏱ 30-second answer

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.

  • Outbound: a concurrency limiter per dependency. Use Polly's AddConcurrencyLimiter, or the standard handler's limiter (1,000 permits, queue 0 by default). Give each dependency a separate named HttpClient with MaxConnectionsPerServer.
  • Inbound: ASP.NET Core AddRateLimiter concurrency policies per endpoint group.
  • Messaging: separate queues and consumers with their own 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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 of AddStandardResilienceHandler, 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 typed HttpClient, its own pipeline and its own MaxConnectionsPerServer, 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 own MaxConcurrentCalls. When a compartment is full, calls are rejected immediately with RateLimiterRejectedException or 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."


Where bulkheads go in a .NET service

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 vs rate limiting

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

Production example

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.

🔍 What the interviewer is checking

Checks whether the candidate understands failure isolation in async .NET, can implement bulkheads at several layers, and can size them.

Green flags

  • Names the actual shared resources (sockets, DB pool, memory, request slots).
  • Uses per-dependency concurrency limiters and separate clients.
  • Distinguishes bulkheads from rate limiting clearly.
  • Sizes limits with Little's Law and keeps queues short.
  • Mentions inbound and messaging bulkheads.

Red flags

  • Thinks bulkheads mean dedicated thread pools in async code.
  • Treats a requests-per-second limit as isolation.
  • No idea what happens to rejected work.
  • Holds DB transactions across external calls.

📚 Learn in depth

1. The idea

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

2. What's actually shared in async .NET

  • Thread pool: async I/O doesn't hold threads while waiting, but sync-over-async (.Result) does, causing starvation.
  • Sockets/connections: SocketsHttpHandler pools connections per host; MaxConnectionsPerServer defaults to unlimited.
  • DB connection pool: SqlClient's Max Pool Size defaults to 100. Holding a connection (or transaction) while awaiting an external call ties it up.
  • Memory: every pending request holds buffers and state.
  • Server capacity: Kestrel and the ingress have their own limits.

A bulkhead should protect whichever of these the dependency can exhaust.

3. Outbound: concurrency limiters

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.

4. Separate clients

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.

5. Inbound bulkheads

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.

6. Messaging bulkheads

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.

7. Sizing with Little's Law

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.

8. Rejection handling

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.

Try it yourself

  1. Point a typed client at a stub with a 10-second delay and send 500 concurrent requests; watch dotnet-counters (System.Net.Http connections, ThreadPool queue length) with and without a concurrency limit of 20.
  2. Hold a DbContext transaction while awaiting the slow stub and watch SqlClient pool exhaustion.
  3. Add an inbound concurrency policy to a slow endpoint and verify a fast endpoint keeps its latency under load (use bombardier or k6).
  4. Compute limits for your top three dependencies with Little's Law from Application Insights rate and p95.
  5. Compare a concurrency limiter and a fixed-window rate limiter against a dependency whose latency jumps from 50 ms to 5 s.

💻 Code

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

⚠ Common mistakes

  • Mistake: One shared 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.
  • Mistake: Leaving the standard handler's limiter at 1,000 permits. Why it is wrong: It's far above most dependencies' healthy concurrency, so it doesn't isolate anything in practice. Instead: Size it per dependency with Little's Law.
  • Mistake: Long queues on concurrency limiters. Why it is wrong: Work waits instead of failing fast, so latency grows and timeouts hit anyway. Instead: Small or zero queues and a clear rejection path.
  • Mistake: Confusing rate limiting with bulkheads. Why it is wrong: A requests-per-second limit doesn't tighten when the dependency slows, so in-flight work still piles up. Instead: Use a concurrency limiter for isolation; rate limits for quotas.
  • Mistake: Holding a database connection or transaction while awaiting an external call. Why it is wrong: The DB pool (100 by default) becomes the shared resource that the slow dependency exhausts. Instead: Do external calls outside transactions, or use the outbox.
  • Mistake: No timeouts inside the bulkhead. Why it is wrong: Permits are held for the full hang, so the compartment stays full. Instead: Pair each bulkhead with a per-attempt timeout.
  • Mistake: Logging rejections as errors and paging on them. Why it is wrong: Rejection is the bulkhead working; alert noise hides real failures. Instead: Log at Information, chart the rejection rate, alert on sustained high rates.
  • Mistake: One queue for all message types. Why it is wrong: A slow or poison message type delays everything behind it. Instead: Separate queues/subscriptions and consumers by type or priority.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate says calls pile up when nothing limits in-flight work Why: Checks putting limits on unbounded concurrency across a system
    How to answer

    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.

  2. When: Candidate mentions rejecting or queueing when a compartment is full Why: Checks backpressure as the system-wide complement to bulkheads
    How to answer

    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.

  3. When: Candidate mentions a bounded queue with a fixed number of workers Why: Checks bounded Channels as an in-process bulkhead
    How to answer

    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.

  4. When: Candidate describes a slow dependency taking down unrelated endpoints Why: Checks applying bulkheads, timeouts and breakers in a real cascading outage
    How to answer

    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:

    • Timeouts: 2 s per attempt, 5 s total.
    • One jittered retry, outside a circuit breaker tuned to the traffic.
    • A bulkhead: a concurrency limit on the shipping client.
    • No external calls inside DB transactions.
    • Liveness checks that don't include the third party.

    The trade-off is a slightly degraded feature against a whole service going down.

🛠 Real-world problems: how you handle them

A slow PDF provider exhausted the SQL connection pool and took checkout down
Situation
E-commerce API at [company] on Azure App Service, [6] instances, about [300] requests a second. The order-confirmation endpoint opened a transaction, saved the order, then called a third-party PDF service to render the invoice before committing.
Signals
During a PDF provider slowdown (p95 from [800 ms] to [25 s]), checkout and unrelated endpoints failed with `InvalidOperationException: Timeout expired... prior to obtaining a connection from the pool`; Application Insights showed SQL dependency failures across all endpoints and a spike in in-flight PDF calls.
Investigation
`dotnet-counters` showed the SqlClient active connection count pinned at 100 per instance. A `dotnet-dump` analysis of async state machines showed hundreds of requests awaiting the PDF client inside an open transaction. Application Insights confirmed PDF calls with no concurrency limit and the default 100-second `HttpClient` timeout.
Resolution
Immediate: a feature flag made invoice PDFs asynchronous (emailed later), freeing connections within minutes. Real fix: moved PDF rendering out of the transaction to a queue consumer fed by the outbox; added a concurrency limiter (10 permits, queue 5) and 20 s timeout on the PDF client; separate subscription and consumer for PDF jobs with `MaxConcurrentCalls = 4`.
Prevention
Architecture rule: no external calls inside DB transactions (code review checklist and a Roslyn analyser for calls on typed clients inside transaction scopes); per-dependency bulkhead sizes documented with Little's Law; dashboards for SQL pool usage and in-flight calls per client; chaos test that slows the PDF stub to 30 s and asserts checkout p95 under [1 s].

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.

↩ Usually asked after

More in Enterprise Patterns

Last updated 18 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me