Give each downstream dependency, and where needed each tenant, its own bounded slice of concurrency. When a slice is full, reject fast or degrade. One failing part should cost you that part's features and nothing else.
A bulkhead splits a service's limited capacity, such as worker threads, connections and in-flight requests, into separate compartments with fixed caps. Each compartment serves one dependency or one tenant. When a downstream hangs, only its own compartment fills up. Everything else keeps its reserved capacity and keeps working. This guide uses one invented incident from start to finish. A restaurant point-of-sale backend stopped taking card payments because a loyalty-points vendor got slow. You will see how per-dependency compartments would have kept checkout running, how to size them, how they interact with timeouts and circuit breakers, and how to explain all of this in a system design interview.
The problem
A situation where the obvious design starts to hurt.
Tillbook runs the checkout backend for about 3,000 restaurants. At Friday dinner peak, POS terminals send roughly 900 checkouts per second to checkout-api, which runs on 10 pods with 200 request workers each. A checkout makes three outbound calls. It charges the card through the Keelpay gateway (p99 140 ms), reads prices from the internal menu-service (p99 20 ms), and accrues points with Crumbly Rewards, a third-party loyalty API (p99 80 ms).
All three calls ran on the same 200 workers per pod. At 19:10 one Friday, Crumbly's p99 jumped from 80 ms to 25 seconds while it held connections open. Each pod gets about 90 checkouts per second. With every loyalty call parking a worker for 25 seconds, the 200 workers were all stuck within about 2.2 seconds. Card charges, which needed only a few dozen concurrent slots and were perfectly healthy at Keelpay, queued behind loyalty calls and timed out at the terminals. For 38 minutes restaurants could not take card payments, because a points system nobody needed in order to pay a bill had soaked up every worker.
The root cause was not the slow vendor. Vendors get slow. The root cause was that a non-critical dependency could consume a shared, finite resource without limit.
The solution
What the pattern proposes.
Give each dependency its own compartment: a counter or semaphore with a fixed number of in-flight slots per pod. A call must take a slot before it runs and releases the slot in a finally block. When no slot is free, the call does not wait. It fails immediately with a BulkheadFull error, and the caller chooses a fallback.
For Tillbook the per-pod caps are payments 40, menu 10 and loyalty 20. They come from Little's law, concurrency = arrival rate x latency, using p99 latency and peak rate per pod with headroom. Payments works out to 90/s x 0.14 s = about 13, so 40 leaves room for gateway slowdowns. Loyalty also gets an 800 ms timeout. When its compartment is full or a call times out, the order still completes and the accrual goes to a points-accrual queue. A separate worker drains that queue later at a rate the vendor can handle.
Replay the Crumbly incident with these limits. At most 20 workers per pod wait on loyalty, each for at most 800 ms. Every other loyalty call is rejected in microseconds and deferred. The remaining 180 workers keep charging cards. Diners lose nothing, and points show up a few minutes late.
You can apply the same idea on the inbound side, per tenant. Cap each restaurant group at 60 in-flight requests per pod. Then a 400-location chain running end-of-day reports cannot starve small restaurants. Stronger isolation means separate pods or node pools per compartment, which also contains memory leaks and CPU exhaustion. An in-process semaphore only contains concurrency.
An everyday analogy
The same idea, outside software.
At a busy airport, crew and staff go through their own security lane with two scanners. When the passenger line backs up to 40 minutes on a holiday morning, pilots and cabin crew still get through in five, so flights are not delayed because the people who fly them are stuck in a queue.
The staff lane does not make the passenger line any faster. It only guarantees that a jam in one line cannot spread to the other. A bulkhead does the same for your service: the slow dependency still has a problem, but the other dependencies keep their own lane.
Structure
The pieces and how they relate.
Participants
- Compartment (bulkhead)
- A named, bounded pool of in-flight slots, usually a semaphore or counter per process, or a dedicated thread or connection pool. It admits a call only if a slot is free and releases the slot when the call settles, whether it succeeded or failed.
- Protected dependency client
- The HTTP or database client for one downstream, such as Keelpay, menu-service or Crumbly. Every call to it goes through its own compartment. Ideally it also has its own connection pool, so the dependencies do not share sockets either.
- Caller (checkout handler)
- Decides what a rejection means for each dependency. A full payments compartment fails the checkout with a retryable 503. A full loyalty compartment is absorbed silently, and the order completes.
- Fallback path
- Handles work the compartment turned away. Here that is the points-accrual queue plus an accrual-worker, which has its own small cap so draining the backlog cannot overload the vendor again.
- Inbound tenant compartment
- An optional second axis. It caps concurrent requests per tenant at the edge of the service, so one large customer's burst uses up only its own share of workers.
- Metrics and alerts
- Exports in-flight count, cap and rejections per compartment. Rejections are the early warning that a dependency is degrading or that a cap is undersized.
Pseudocode
The solution to the scenario, language-neutral.
config compartments:
payments: max_in_flight = 40, on_full = FAIL_REQUEST
menu: max_in_flight = 10, on_full = FAIL_REQUEST
loyalty: max_in_flight = 20, timeout = 800ms, on_full = DEFER
function run(compartment, task):
if compartment.in_flight >= compartment.max_in_flight:
metrics.increment(compartment.name + ".rejected")
raise BulkheadFull(compartment.name)
compartment.in_flight += 1
try:
return task()
finally:
compartment.in_flight -= 1
function checkout(order):
prices = run(menu, () => menuService.price(order.items))
charge = run(payments, () => keelpay.charge(order.card, prices.total))
try:
run(loyalty, () => crumbly.accrue(order.customer, prices.total, timeout = 800ms))
catch BulkheadFull or Timeout:
pointsQueue.publish({ order_id: order.id, customer: order.customer, amount: prices.total })
return receipt(order, charge)
// BulkheadFull from menu or payments propagates as HTTP 503 with Retry-After: 1The code
The same solution in TypeScript, Python and PHP.
// Per-dependency bulkhead: a bounded count of in-flight calls that rejects fast when full.
export class BulkheadFullError extends Error {
constructor(readonly compartment: string) {
super(`bulkhead '${compartment}' is full`);
this.name = "BulkheadFullError";
}
}
export class Bulkhead {
private inFlight = 0;
private rejected = 0;
constructor(readonly name: string, private readonly maxConcurrent: number) {
if (!Number.isInteger(maxConcurrent) || maxConcurrent < 1) {
throw new RangeError("maxConcurrent must be a positive integer");
}
}
async run<T>(task: () => Promise<T>): Promise<T> {
if (this.inFlight >= this.maxConcurrent) {
this.rejected++;
throw new BulkheadFullError(this.name);
}
this.inFlight++;
try {
return await task();
} finally {
this.inFlight--; // always release, even on error or timeout
}
}
stats() {
return { name: this.name, inFlight: this.inFlight, max: this.maxConcurrent, rejected: this.rejected };
}
}
// Demo: loyalty vendor hangs, payments stay healthy.
const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
const payments = new Bulkhead("payments", 40);
const loyalty = new Bulkhead("loyalty", 3);
async function accruePoints(orderId: string): Promise<string> {
try {
// In production, also pass an 800 ms AbortSignal to the vendor call.
await loyalty.run(() => sleep(500)); // vendor is slow
return `${orderId}: points accrued`;
} catch (err) {
if (err instanceof BulkheadFullError) {
return `${orderId}: deferred to accrual queue`;
}
throw err;
}
}
async function chargeCard(orderId: string): Promise<string> {
await payments.run(() => sleep(50));
return `${orderId}: card charged`;
}
async function main(): Promise<void> {
const orders = ["o1", "o2", "o3", "o4", "o5"];
const results = await Promise.all([
...orders.map((id) => accruePoints(id)),
...orders.map((id) => chargeCard(id)),
]);
results.forEach((line) => console.log(line));
console.log(loyalty.stats(), payments.stats());
}
main().catch((err) => {
console.error(err);
process.exit(1);
});# Per-dependency bulkhead: a bounded count of in-flight calls that rejects fast when full.
import asyncio
from typing import Awaitable, Callable, TypeVar
T = TypeVar("T")
class BulkheadFull(Exception):
def __init__(self, compartment: str) -> None:
super().__init__(f"bulkhead '{compartment}' is full")
self.compartment = compartment
class Bulkhead:
def __init__(self, name: str, max_concurrent: int) -> None:
if max_concurrent < 1:
raise ValueError("max_concurrent must be a positive integer")
self.name = name
self.max_concurrent = max_concurrent
self._in_flight = 0
self.rejected = 0
async def run(self, task: Callable[[], Awaitable[T]]) -> T:
# Single event loop: check and increment happen without an await in between.
if self._in_flight >= self.max_concurrent:
self.rejected += 1
raise BulkheadFull(self.name)
self._in_flight += 1
try:
return await task()
finally:
self._in_flight -= 1 # always release, even on error or cancellation
def stats(self) -> dict:
return {
"name": self.name,
"in_flight": self._in_flight,
"max": self.max_concurrent,
"rejected": self.rejected,
}
# Demo: loyalty vendor hangs, payments stay healthy.
payments = Bulkhead("payments", 40)
loyalty = Bulkhead("loyalty", 3)
async def accrue_points(order_id: str) -> str:
try:
# In production, wrap the vendor call in asyncio.timeout(0.8).
await loyalty.run(lambda: asyncio.sleep(0.5)) # vendor is slow
return f"{order_id}: points accrued"
except BulkheadFull:
return f"{order_id}: deferred to accrual queue"
async def charge_card(order_id: str) -> str:
await payments.run(lambda: asyncio.sleep(0.05))
return f"{order_id}: card charged"
async def main() -> None:
orders = ["o1", "o2", "o3", "o4", "o5"]
results = await asyncio.gather(
*(accrue_points(o) for o in orders),
*(charge_card(o) for o in orders),
)
for line in results:
print(line)
print(loyalty.stats(), payments.stats())
if __name__ == "__main__":
asyncio.run(main())<?php
// Per-dependency bulkhead for PHP-FPM: N lock files are N slots shared by all workers.
// flock() locks are released by the OS if a worker dies, so slots cannot leak on crash.
declare(strict_types=1);
final class BulkheadFullException extends RuntimeException
{
}
final class Bulkhead
{
public function __construct(
private string $name,
private int $maxConcurrent,
private string $dir = '/tmp/bulkheads'
) {
if ($maxConcurrent < 1) {
throw new InvalidArgumentException('maxConcurrent must be a positive integer');
}
if (!preg_match('/^[a-z0-9-]+$/', $name)) {
throw new InvalidArgumentException('name must be lowercase letters, digits or dashes');
}
if (!is_dir($dir) && !mkdir($dir, 0700, true) && !is_dir($dir)) {
throw new RuntimeException("cannot create {$dir}");
}
}
/**
* @template T
* @param callable(): T $task
* @return T
*/
public function run(callable $task): mixed
{
$slot = $this->acquire();
if ($slot === null) {
throw new BulkheadFullException("bulkhead '{$this->name}' is full");
}
try {
return $task();
} finally {
flock($slot, LOCK_UN); // always release, even on exception
fclose($slot);
}
}
/** @return resource|null */
private function acquire()
{
for ($i = 0; $i < $this->maxConcurrent; $i++) {
$handle = fopen(sprintf('%s/%s.%d.lock', $this->dir, $this->name, $i), 'c');
if ($handle === false) {
continue;
}
if (flock($handle, LOCK_EX | LOCK_NB)) {
return $handle; // got a free slot without waiting
}
fclose($handle);
}
return null;
}
}
// Demo: both loyalty slots are held (as if two workers were stuck on the vendor),
// so a third accrual is deferred while payments still go through.
$payments = new Bulkhead('payments', 40);
$loyalty = new Bulkhead('loyalty', 2);
$accrual = $loyalty->run(fn () => $loyalty->run(function () use ($loyalty): string {
try {
return $loyalty->run(fn (): string => 'points accrued');
} catch (BulkheadFullException) {
return 'deferred to accrual queue';
}
}));
$charge = $payments->run(fn (): string => 'card charged');
echo "o3: {$accrual}", PHP_EOL; // o3: deferred to accrual queue
echo "o3: {$charge}", PHP_EOL; // o3: card chargedWhen to use it
Situations where it pays off.
One service calls several downstreams with very different criticality or reliability, for example a payment gateway next to a third-party enrichment API.
Without caps, the least reliable dependency decides how much capacity the most important one gets. Compartments let a hang in the optional call cost only the optional feature.
Request handling runs on a fixed pool: thread-per-request servers, PHP-FPM workers, database connection pools, or a bounded HTTP agent.
A fixed pool is exactly the shared resource that slow calls exhaust. If calls to one host can occupy every worker, you need a per-dependency limit.
You serve many tenants from shared infrastructure, and a few tenants are much larger or burstier than the rest.
Per-tenant compartments turn one tenant's batch job or retry storm into slower service for that tenant only, rather than an outage for everyone.
A dependency is known to fail slowly, holding connections open rather than refusing them.
Slow failures are worse than fast ones because they hold resources. A cap bounds how many workers can be held at once, even before a timeout fires.
You are separating batch or background traffic from interactive traffic in the same service.
Reserving slots for interactive requests means a nightly export or a reindex cannot push p99 latency up for live users.
How to implement it
Steps to introduce it in existing code.
List every finite resource a request consumes: request workers, outbound connections per host, database connections, and in-flight calls per dependency. Find which ones are shared across dependencies or tenants.
Classify each dependency by criticality. Decide what a rejection means for it: fail the request, serve a default or cached value, or defer the work to a queue.
Size each compartment with Little's law: peak requests per second per instance x p99 latency in seconds, plus 30 to 50 percent headroom. Check that the critical compartments fit inside the worker pool with room left over.
Wrap every call to a dependency in its compartment. Acquire before the call, and release in a finally block so errors and timeouts never leak a slot.
Pair every compartment with a timeout shorter than the caller's own deadline, and cancel the underlying request when it fires. Otherwise a slot stays held after the caller has given up.
Give each dependency its own connection pool or HTTP agent with maxSockets matching the cap, so the dependencies do not share sockets underneath the semaphore.
Export in-flight count, cap and rejections per compartment. Alert when the rejection rate on a critical compartment goes above about 0.1 percent of calls for 5 minutes.
Load test by injecting 20 second latency into one dependency in staging, and confirm the other compartments keep their normal throughput and p99.
Pros and cons
What you gain and what you pay.
Pros
- A slow or hanging dependency degrades only the features that need it. In the Tillbook replay, card payments kept running while loyalty was down.
- Rejections are fast and explicit. Callers get BulkheadFull in microseconds instead of waiting on a starved worker pool.
- Caps also protect the downstream. A struggling vendor sees at most cap x instances concurrent calls, not your whole traffic.
- Per-compartment metrics show which dependency is in trouble before users notice.
- The mechanism is small, a counter or semaphore with a finally block, and you can add it without changing the architecture.
Cons
- Reserved capacity sits idle. If payments is capped at 40 but uses 13, those 27 slots cannot be lent to a menu spike.
- Caps must be tuned and kept up to date. A cap that was right before a traffic doubling starts rejecting healthy calls.
- Per-instance caps multiply with replica count. Autoscaling from 10 to 30 pods triples the load a fragile vendor can receive.
- In-process compartments do not isolate memory, CPU or crashes. A memory leak in one code path still takes down the whole pod.
- Every compartment needs a defined fallback, which adds product and code decisions for each dependency.
Trade-offs
Decisions you'll have to make, each with its price.
Fail fast with no wait queue versus a small bounded wait queue
You gainFail fast rejects in microseconds and never parks a worker. A queue of 10 with a 50 ms wait limit absorbs short bursts above 40 payments calls when the gateway is healthy.
You payFail fast turns harmless 100 ms spikes into 503s. The queue adds up to 50 ms of latency and hides an undersized cap until the queue also fills.
Static per-pod caps versus adaptive concurrency limits
You gainStatic caps such as payments 40, menu 10 and loyalty 20 are predictable and easy to reason about. Adaptive limits based on observed latency shrink automatically when Crumbly slows down.
You payStatic caps scale with replica count: 30 pods x 20 means Crumbly can receive 600 concurrent calls. Adaptive limits are harder to debug and can swing during noisy latency.
In-process semaphores versus separate deployments per compartment
You gainSemaphores cost nothing extra and ship in a day. Separate pods for loyalty work also isolate memory leaks, CPU and crashes, not just concurrency.
You paySemaphores share the heap, the CPU and the event loop. Separate deployments add pods, network hops and configuration to keep in sync.
Per-dependency compartments only versus adding per-tenant compartments
You gainPer-tenant caps of 60 in-flight requests per pod stop a 400-location chain's end-of-day reports from starving small restaurants.
You payWith 3,000 tenants you cannot reserve slots for each one. You cap per tenant on top of a shared pool, so a few tenants hitting their caps together can still fill the pool.
Tight caps close to measured need versus generous headroom
You gainTight caps keep the worst case small: 20 hung loyalty workers out of 200. Generous caps survive traffic growth without retuning.
You payTight caps reject healthy traffic after a doubling in volume. Generous caps, say loyalty at 120, let a slow vendor hold 60 percent of workers before isolation helps.
How it fails
What goes wrong in production and how to prevent it.
Payments cap is undersized, so healthy checkouts get 503s at normal peak after traffic grows.
What to doSize from peak rate per pod x p99 latency with 30 to 50 percent headroom, and recompute it in each capacity review. Alert when payments rejections exceed 0.1 percent of calls over 5 minutes, and treat that as a capacity signal.
Slot leak: a code path returns or throws without releasing, and the compartment slowly fills up permanently.
What to doRelease only in finally, or use a scoped helper like run(task), never separate acquire and release calls. Graph in-flight per compartment: a value that never drops to zero during quiet hours means a leak.
A timeout fires, but the underlying HTTP request keeps running, so the slot is released while the socket stays busy.
What to doCancel the request itself with AbortSignal, asyncio cancellation or a client-level timeout. Size the per-dependency connection pool to the cap so sockets cannot quietly grow past it.
A hidden shared resource remains: all dependencies share one HTTP agent, DNS resolver or database pool underneath separate semaphores.
What to doGive each dependency its own HTTP agent with maxSockets equal to its cap, and its own DB pool where relevant. Then inject 20 s latency into one dependency in staging and verify the other compartments' p99 does not move.
Autoscaling multiplies caps: going from 10 to 30 pods during a spike sends 600 concurrent calls to a vendor whose contract allows 250.
What to doDerive the per-pod cap from a global budget divided by the current replica count. Alternatively, put a shared limiter in front of the vendor, or route its traffic through the accrual-worker, which has a fixed total cap.
The fallback becomes the new bottleneck: deferred accruals pile up and the worker floods Crumbly as soon as it recovers.
What to doGive accrual-worker its own small cap, for example 10 concurrent calls, with retry backoff. Alert on queue age above 15 minutes rather than queue depth.
In a system design interview
When to bring it up and how to explain it.
Bring it up when your design has one service calling several downstreams of different importance, especially third-party APIs, or when the interviewer asks what happens if one dependency gets slow. It also fits multi-tenant designs where one large customer could starve everyone else.
What you could say
Checkout calls three things: the payment gateway, our menu service and a third-party loyalty API. I don't want those three sharing an unbounded pool of workers. If loyalty slows to 25 seconds and every call can park a worker, a pod with 200 workers getting 90 checkouts a second is fully blocked in about two seconds, and then we can't charge cards even though the gateway is fine. So I'd put a bulkhead around each dependency, which is a cap on concurrent in-flight calls per pod. I size each cap with Little's law: peak rate per pod times p99 latency, plus headroom. That gives roughly 40 for payments, 10 for menu and 20 for loyalty. When a compartment is full I reject immediately rather than queue. For payments that becomes a retryable 503. For loyalty, the order still completes and the accrual goes to a queue that a worker drains later. I'd add an 800 ms timeout on loyalty so slots free up quickly, separate connection pools per dependency, and alerts on rejection rate per compartment. If tenants vary a lot in size, I'd also cap in-flight requests per tenant at the edge.
Likely follow-ups
How is this different from a circuit breaker?
A breaker reacts after it has seen enough failures, and then it stops calling the dependency. A bulkhead works from the first slow call by limiting how much capacity that dependency can hold. In practice I use both: the bulkhead contains the damage while latency climbs, and the breaker trips once errors pass its threshold, so we stop spending even those 20 slots.
How do you pick the cap numbers?
Little's law: concurrency equals arrival rate times latency. For payments, 90 requests per second per pod times 0.14 s p99 is about 13, so I set 40 for headroom against gateway slowdowns. Then I check that the critical caps plus a margin fit within the 200 workers, load test with injected latency, and watch rejection rates after launch.
What happens to the caps when you autoscale?
Per-pod caps multiply. At 30 pods, loyalty's cap of 20 means 600 concurrent calls to the vendor. If the vendor has a hard limit, I compute the per-pod cap from a global budget divided by the replica count, or I move the vendor calls behind a single worker pool with a fixed total cap.
Would you use separate thread pools or semaphores?
In async runtimes like Node or asyncio I use semaphores, because there are no threads to dedicate. On thread-per-request servers a dedicated pool lets the caller give up on a hung call while the pool absorbs it. If one dependency path can leak memory or burn CPU, I'd go further and give it separate pods.
Relations with other guides
Patterns it's often confused or combined with.
- Timeouts and Deadline Propagation
A bulkhead limits how many calls can hang at once, and a timeout limits how long each one hangs. You need both: without a timeout, a full compartment stays full for the vendor's 25 seconds and its throughput collapses.
- Circuit breaker: fail fast when a dependency is down
A circuit breaker stops calling a dependency after it fails repeatedly. A bulkhead limits damage while it is still failing. Use the breaker to skip a dead vendor and the bulkhead to contain a slow one before the breaker trips.
- Rate Limiting: Token Bucket, Sliding Window and Honest 429s
Rate limiting caps requests per unit of time, while a bulkhead caps concurrent requests. A dependency that slows from 80 ms to 25 s stays within any rate limit while using up every worker, which only a concurrency cap catches.
- Queue-Based Load Leveling: Absorbing a Refund Burst
Tillbook's loyalty fallback is load leveling: rejected accruals go to a queue and a capped worker drains them at a pace the vendor can absorb.
- Backpressure: Let Slow Consumers Slow Down Fast Producers
A full compartment that rejects fast is a form of backpressure. It pushes the overload back to the caller instead of buffering it in memory.
- Retry with Backoff: Exponential Delays, Jitter and Retry Budgets
Retries on BulkheadFull must back off with jitter. Immediate retries just hit the same full compartment and add load to it.
Common questions
Short answers to the usual doubts.
Is a bulkhead just a thread pool per dependency?
A dedicated thread pool is one way to build it, and it also lets the caller abandon a hung call. A semaphore or counter around the call is the lighter way, and it is the usual choice in async runtimes like Node or asyncio. Both enforce the same rule: a fixed number of concurrent calls per compartment. Separate pods or node pools are the heaviest form, and they also isolate memory and CPU.
Should a full compartment queue callers or reject them?
For latency-sensitive calls, reject, or allow a tiny queue with a short wait limit such as 10 waiters and 50 ms. A long queue just moves the pile-up from the dependency into your process, and callers time out while they wait.
Do bulkheads replace timeouts?
No. A cap without a timeout keeps the compartment full for as long as the vendor hangs. A timeout without a cap still lets every worker hang at once. Use both.
Now, practise it
Put it to work straight away.
Tests, exercises and problems that use what you've just read.
- Resilience and high concurrencyTake the test