Sub topic 8
Bulkheads: containing failure to one part of the system
This chapter assumes you have read the chapters on timeouts, circuit breakers, and fallbacks. You should also be comfortable with threads or a worker pool in your language. The examples use Python.
The problem: one slow dependency uses up shared capacity
A timeout limits how long one call waits. It does not limit how many calls wait at the same time. Suppose a service has 20 worker threads, and every request calls a recommendations service. If that service slows to 0.5 seconds per call, each thread is tied up for that long. Requests keep arriving, so more and more threads end up waiting on recommendations. Soon all 20 threads are busy, and checkout requests, which never needed recommendations, cannot get a thread.
The optional dependency has taken down a critical feature. The cause is shared capacity: threads, connections, or memory that all features draw from.
The bulkhead idea
A ship's hull is divided into watertight compartments called bulkheads. A leak floods one compartment, and the ship stays afloat. In software, a bulkhead is a hard limit on the resources one dependency or feature can use. When that limit is reached, new calls to that dependency are rejected immediately. The rest of the system keeps its own resources.
If recommendations hangs, at most 5 slots are stuck. Checkout still has its 15.
Common forms of bulkhead
| Form | What is limited | Typical use |
|---|---|---|
| Semaphore | Concurrent calls to one dependency | Lightweight, same thread pool |
| Separate thread pool | Threads per dependency | Stronger isolation, more overhead |
| Connection pool per dependency | Open connections | Databases and HTTP clients |
| Separate process or deployment | Everything | Isolating a whole feature |
Isolation can also be larger than a pool. Running a batch-export feature in a separate deployment from the user-facing API is a bulkhead too. A traffic spike in exports then cannot starve interactive requests.
A semaphore bulkhead in Python
A semaphore is a counter that allows only a fixed number of holders at once. This version rejects a call at once if no slot is free.
import threading
import time
class BulkheadFullError(Exception):
"""Raised when a dependency has no free slots."""
class Bulkhead:
def __init__(self, name, max_concurrent, wait=0.0):
self.name = name
self.wait = wait
self._slots = threading.BoundedSemaphore(max_concurrent)
def call(self, fn, *args, **kwargs):
if not self._slots.acquire(timeout=self.wait):
raise BulkheadFullError(self.name)
try:
return fn(*args, **kwargs)
finally:
self._slots.release()
recommendations = Bulkhead("recommendations", max_concurrent=2)
def slow_fetch():
time.sleep(0.3)
return ["book", "lamp"]
def get_items():
try:
return recommendations.call(slow_fetch)
except BulkheadFullError:
return [] # fallback: empty default
results = []
threads = [
threading.Thread(target=lambda: results.append(get_items()))
for _ in range(4)
]
for t in threads:
t.start()
for t in threads:
t.join()
print(results)Two of the four calls get a slot and return items. The other two find the bulkhead full and return [] straight away. Run it and you will see two full lists and two empty ones. The order varies.
The finally block matters. If the slot is not released when the call raises an exception, the bulkhead slowly leaks capacity and eventually rejects everything.
Choosing the size and wait
- Size from measurement. A rough starting point is peak calls per second multiplied by normal latency in seconds. At 50 calls per second and 0.1 seconds latency, about 5 calls are in flight. Add headroom, but not so much that the pool can swallow most of your capacity.
- Keep the wait short. A
waitof 0 rejects immediately. A long wait recreates the original problem, because callers queue up behind a slow dependency. - Size by criticality. Give critical dependencies guaranteed capacity. Cap optional ones tightly.
Common errors
- Unbounded queues. A pool with a small limit but an unlimited queue in front of it still lets work pile up. Bound the queue or reject when full.
- Sharing one pool "just for convenience." One HTTP client with one connection pool for every dependency brings the shared-capacity problem back.
- No fallback for rejections. A rejection is a new kind of failure. Handle it like a timeout: return cached data or a default.
- Retrying rejections. Retrying a
BulkheadFullErroradds load to a dependency that is already saturated. Leave it out of the exceptions your retry loop catches. - Treating rejections as invisible. Count them. A rising rejection rate is an early sign that a dependency is slow, and the next chapters cover how to expose it.
Exercise
Exercise
A service has 30 worker threads. Search calls take 50 ms normally and arrive at about 100 per second. A "related articles" call takes 100 ms and arrives at about 100 per second. Related articles becomes very slow and starts hanging. Using the rule of thumb of calls per second times latency, roughly how many slots would you give each, and what should happen to related-articles calls once its slots are full?
Show answer
Search needs about 100 × 0.05 = 5 concurrent slots, so give it perhaps 10 for headroom. Related articles normally needs about 100 × 0.1 = 10 slots. Because it is optional, cap it near that (for example 10) so it can never take more than a third of the 30 threads. Once its slots are full, further calls should be rejected immediately with a short or zero wait and answered with a fallback such as an empty list or cached articles, and the rejection should be counted in a metric.