Sub topic 8
Bulkheads: containing failure to one part of the system
This chapter assumes you have read the earlier chapters on dependency failures, timeouts, and circuit breakers. You should be comfortable with threads or async tasks, HTTP calls, and exceptions in Python. The code uses only the standard library.
The problem: one slow dependency uses up shared resources
A timeout limits how long one call waits. It does not limit how many calls are waiting at once. Suppose a service has a pool of 20 worker threads that handle every request. One optional dependency, the recommendations service, becomes slow. Each call to it now holds a thread for the full timeout, say 500 ms. If requests arrive faster than threads are freed, all 20 threads end up stuck waiting on recommendations. Requests that never touch recommendations, such as checkout, now queue behind them and fail.
The dependency was optional, but it took down a critical feature. The cause is a shared resource that has no boundaries. This is called resource exhaustion. A bulkhead is the fix.
A bulkhead is a limit on how much of a shared resource one part of the system can use. The name comes from ship design. Watertight compartments keep a hull breach in one section from sinking the whole ship. In software, you divide threads, connections, or memory into separate compartments so that a failure in one cannot drain the others.
Where to put the walls
You can build a bulkhead around any resource that a failure could exhaust. Common choices:
| Resource | Bulkhead form | What it protects against |
|---|---|---|
| Threads or async tasks | Separate thread pool or semaphore per dependency | Slow calls tying up all workers |
| Connections | Separate connection pool per dependency or per database | One heavy query type taking every connection |
| Memory and CPU | Separate processes or containers with resource limits | A leak or runaway computation in one component |
| Queues | Separate queue per workload or priority | A backlog of low-value jobs delaying important ones |
| Deployments | Separate service instances per feature or customer group | A bad deploy or bad request pattern affecting everyone |
The last row is the coarsest form. Splitting a system into cells, where each cell serves a subset of customers, limits the blast radius (the number of users affected) of any single failure to that subset. Most services start with the first two rows, because they are cheap and local.
A semaphore bulkhead
The simplest bulkhead limits concurrent calls with a semaphore. A semaphore is a counter that allows at most N holders at a time. If all permits are taken, the next caller either waits or is rejected. For a bulkhead, rejecting is almost always better. A caller that waits for a permit is still consuming a resource.
import threading
class BulkheadFull(Exception):
"""Raised when no permit is available for a call."""
class Bulkhead:
def __init__(self, name, max_concurrent):
self.name = name
self.max_concurrent = max_concurrent
self._semaphore = threading.BoundedSemaphore(max_concurrent)
self._lock = threading.Lock()
self.rejected = 0
def call(self, fn, fallback):
if not self._semaphore.acquire(blocking=False):
with self._lock:
self.rejected += 1
return fallback()
try:
return fn()
finally:
self._semaphore.release()
recommendations_bulkhead = Bulkhead("recommendations", max_concurrent=5)Three details matter here.
acquire(blocking=False)returns immediately. If five calls to recommendations are already in flight, the sixth gets the fallback at once, without waiting.- The
finallyblock releases the permit even whenfnraises. A leaked permit permanently shrinks the compartment, and the failure is hard to notice. BoundedSemaphoreraises an error if you release more times than you acquired. That catches double-release bugs that a plainSemaphorewould hide.
Using it with the cache-and-default fallback from the earlier chapter looks like this:
import time
import threading
_cache = {}
class Bulkhead:
def __init__(self, name, max_concurrent):
self.name = name
self._semaphore = threading.BoundedSemaphore(max_concurrent)
def call(self, fn, fallback):
if not self._semaphore.acquire(blocking=False):
return fallback()
try:
return fn()
finally:
self._semaphore.release()
recommendations_bulkhead = Bulkhead("recommendations", max_concurrent=5)
def get_recommendations(user_id, fetch, timeout=0.5):
def fallback():
if user_id in _cache:
items, _ = _cache[user_id]
return {"items": items, "degraded": True, "source": "cache"}
return {"items": [], "degraded": True, "source": "default"}
def real_call():
try:
items = fetch(user_id, timeout=timeout)
except (TimeoutError, ConnectionError):
return fallback()
_cache[user_id] = (items, time.monotonic())
return {"items": items, "degraded": False}
return recommendations_bulkhead.call(real_call, fallback)Now at most five threads can be inside the recommendations call at any moment. Even if every one of them waits the full 500 ms, the remaining workers stay available for checkout.
Sizing a compartment
A bulkhead that is too small rejects healthy traffic. One that is too large does not protect anything. Use Little's Law as a starting point: the average number of calls in flight equals the arrival rate multiplied by the average latency.
For example, if recommendations normally receives 40 requests per second and responds in 50 ms, the average concurrency is 40 × 0.05 = 2 calls in flight. A limit of 5 gives some headroom for bursts. During an incident, latency rises to 500 ms, which would need 20 concurrent calls to serve the same traffic. The bulkhead refuses to grow, so 15 of those 20 slots' worth of demand is rejected and receives the fallback. This is the intended behavior: you trade some optional functionality to keep the rest of the service alive.
Steps for choosing a limit:
- Measure the normal arrival rate and the 99th percentile latency (p99) of the dependency.
- Multiply them to estimate the concurrency needed at peak, then add 50 to 100 percent headroom.
- Check that the sum of all compartments is below the total capacity of the shared resource, with room left for the critical path.
- Revisit the numbers after load tests and after major traffic changes.
Thread pool bulkheads and semaphore bulkheads
There are two common implementations, and they differ in an important way.
A semaphore bulkhead runs the call on the caller's own thread and only counts it. It is cheap and has no hand-off cost. It cannot stop a call that hangs, so it relies on a working timeout inside fn. If the timeout is missing, a permit is held for as long as the call hangs.
A thread pool bulkhead runs each call on a dedicated pool of threads. The caller submits work and waits for the result with its own timeout. If the dependency hangs, the caller can give up and move on, because the stuck work sits on a thread belonging to the dependency's pool. The cost is thread hand-off overhead and more complexity, such as propagating context and handling cancellation.
from concurrent.futures import ThreadPoolExecutor, TimeoutError as FutureTimeout
import queue
recommendations_pool = ThreadPoolExecutor(
max_workers=5, thread_name_prefix="recs"
)
def call_in_pool(pool, fn, timeout, fallback):
try:
future = pool.submit(fn)
except RuntimeError:
return fallback()
try:
return future.result(timeout=timeout)
except FutureTimeout:
future.cancel()
return fallback()This version has a gap. ThreadPoolExecutor uses an unbounded internal queue, so submit never rejects. Under overload, work piles up in the queue and every call waits longer. The pool limits running calls, but the queue becomes a hidden shared resource. If you use a thread pool as a bulkhead, bound the queue too. Combine the pool with a semaphore sized to workers plus a small allowed backlog, and reject when it is full.
Gotchas and failure modes
- Bulkheads that share a hidden resource. Two separate thread pools can still share one database connection pool, one DNS resolver, or one CPU core. If the real bottleneck is shared, the walls do not hold. Trace each compartment down to the lowest-level resource it uses.
- Limits that sum to more than capacity. If you give five dependencies 20 permits each against a 50-worker pool, they can still starve the critical path together. Reserve capacity for critical work first, then divide the rest.
- Rejecting without a fallback. A rejection is a failure that you chose. It needs the same fallback as a timeout, and it needs to be counted. A bulkhead that raises an unhandled exception just moves the outage to a different line.
- Static limits in a changing system. A fixed limit chosen last quarter may be wrong now. Watch rejection rates. Frequent rejections while the dependency is healthy mean the limit is too low.
- Per-process limits in a fleet. A limit of 5 per instance across 100 instances allows 500 concurrent calls to the dependency. A bulkhead protects the caller. To protect the dependency itself, you also need limits at its side or a shared rate limiter.
Bulkheads and the other patterns
Each pattern in this tutorial answers a different question.
| Pattern | Question it answers |
|---|---|
| Timeout | How long will one call wait? |
| Retry | Should a failed call be attempted again? |
| Circuit breaker | Should we keep calling a dependency that is failing? |
| Bulkhead | How much of our capacity can this dependency use? |
| Fallback | What do we return when the call does not happen or fails? |
A circuit breaker reacts to failures it has observed. A bulkhead works before any failure is detected, and it bounds the damage of slowness, which a breaker based only on errors may not notice quickly. They work well together. The bulkhead caps concurrent waiting, the timeout caps each wait, and the breaker stops the calls altogether once the pattern of failures is clear. All three route to the same fallback.
A useful order of wrapping, from outside to inside, is: bulkhead, circuit breaker, retry, timeout. The bulkhead check is cheapest and should reject first. Retries should sit inside the bulkhead so that retry attempts are counted against the same permit and do not multiply concurrency.
Making the walls visible
Expose at least these numbers per compartment:
- Current concurrent calls and the configured maximum.
- Count of rejected calls, as a rate.
- Count of fallbacks served, split by source (cache, default).
- Latency of calls that were admitted.
A rising rejection rate with a healthy dependency means your limit is wrong. A rising rejection rate with rising latency means the dependency is failing and the bulkhead is doing its job. Alert on the first as a configuration problem and on the second as an incident, and make sure the responses carry the degraded flag shown earlier.
Exercise
A service has 30 worker threads. Payments (critical) needs about 10 concurrent calls at peak. Search (optional) averages 100 requests per second at 80 ms latency. Using Little's Law, how many concurrent search calls are normal, and what bulkhead limit would you choose for search so that payments is protected? Explain why a thread pool with an unbounded queue would weaken your design.
Show answer
Normal search concurrency is 100 × 0.08 = 8 calls. With 50 to 100 percent headroom, a limit of 12 to 16 is reasonable. Choose a value such as 12 or 14, so payments (10) plus search (at most 14) stays under 30 and leaves spare workers for other work. An unbounded queue lets extra search requests wait behind the running ones. They hold memory and add latency, and they eventually time out anyway, so the compartment limits running calls but not waiting calls. Bound the queue and reject the overflow with the fallback.
Exercise
Your recommendations bulkhead rejects 30 percent of calls, but the recommendations service reports normal latency and no errors. What is the most likely cause, and what do you change?
Show answer
The limit is too low for current traffic, so healthy calls are being rejected. Measure the present arrival rate and p99 latency, recompute the concurrency with Little's Law, add headroom, and raise the limit. Also check that the total of all compartments still leaves capacity for critical work.