Bulkheads

A from-scratch guide to resource isolation: why a dependency that never returns an error can still take down your whole service, how to partition goroutines, connections, and memory so a failure stays in one compartment, and how to pick the numbers without guessing.

Read top to bottom. It goes beginner → advanced, and generic → concrete. Part I builds the model with no code. Part II builds semaphore, worker-pool, and adaptive bulkheads in Go, and covers the pieces people forget — queueing, fairness, and where the bulkhead sits relative to a circuit breaker.

Companion doc: Circuit Breakers. The two patterns are complements, not alternatives, and section 3 of this doc explains exactly why.


Part I — The generic model


1. The problem: slow is worse than down

Service A serves three endpoints. Two of them are self-contained; the third calls dependency B.

   /health    ──┐
   /orders    ──┼──►  ┌───┐
   /reports   ──┘     │ A │ ──► ┌───┐
                      └───┘     │ B │   (only /reports needs B)
                                └───┘

B starts taking 30 seconds per call. It does not error — it returns 200 OK, eventually.

Now trace what happens inside A. /reports gets 50 rps. By Little's Law, in-flight calls settle at L = λ × W = 50 × 30 = 1500. Each in-flight call holds:

  • a goroutine (~8 KB stack minimum, often much more once it has buffers)
  • an HTTP connection out of a pool that maxes at, say, 100
  • a slot in whatever caps A's inbound concurrency
  • whatever request-scoped memory it allocated before making the call

The connection pool exhausts first, at 100. Calls 101 through 1500 now block waiting for a connection — and here is the crucial part: that wait happens inside A, holding a goroutine, for a request to a dependency A may not even need. If the pool is shared across all outbound HTTP, /orders calls to dependency C are now queued behind /reports calls to a dead B.

Within a minute:

  • Goroutine count: 20 → 1500+.
  • Memory: climbing, because each in-flight request holds its parsed body.
  • /health starts timing out — the health checker marks A unhealthy — the load balancer removes A — the remaining replicas get more traffic — they fall over the same way.

One slow dependency, used by one endpoint, took down the entire service.

Notice what did not help here:

  • Timeouts help, but only bound the damage: with a 30 s timeout you still hold 1500 goroutines. Lowering it to 2 s gets you to 100 — better, but it's a blunt instrument and you may need 30 s for legitimate slow requests.

  • Retries actively hurt (they multiply the in-flight count).

  • A circuit breaker doesn't fire at all. Every call returns 200. There are no errors to count. This is the single most important thing to understand about bulkheads: they cover the case a breaker structurally cannot see.

What's missing is a hard cap on how much of A the B dependency is allowed to occupy. That cap is the bulkhead.


2. The idea: compartments in a ship

A ship's hull is divided by transverse walls — bulkheads — into watertight compartments. Puncture the hull and one compartment floods. The ship rides lower and slower; it does not sink.

   ┌──────┬──────┬──────┬──────┐
   │      │▓▓▓▓▓▓│      │      │   one compartment flooded,
   │      │▓▓▓▓▓▓│      │      │   the ship still floats
   └──────┴──────┴──────┴──────┘

In software:

Partition a finite resource into fixed compartments, one per failure domain, so that exhausting one compartment cannot exhaust the others.

Applied to section 1: give /reports a budget of 20 concurrent calls to B. When B gets slow, 20 goroutines are stuck. Call 21 is rejected immediately — it doesn't wait, it doesn't allocate, it doesn't take a connection. /orders and /health never notice, because their compartment was never touched.

The gains, stated precisely:

Property Without bulkhead With bulkhead
Goroutines held by a slow B unbounded (λ × W) ≤ 20, always
Blast radius whole process one endpoint
/reports availability 0% (times out) ~40% (20 slots × throughput)
/orders availability 0% (collateral) 100%
Failure onset gradual, then cliff immediate, bounded, visible

That last row is underrated. Without a bulkhead the failure is quiet until it's catastrophic. With one, bulkhead_rejected_total starts incrementing the moment saturation begins, which is a metric you can alert on minutes before anything user-visible happens.

The tradeoff is explicit and deliberate: you are choosing to reject some requests to /reports in order to guarantee /orders keeps working. If every request were equally important and resources were infinite, you wouldn't need this. They aren't, so you do.


3. Bulkhead vs. circuit breaker vs. rate limiter

These three get conflated constantly. They control different variables.

Bulkhead Circuit breaker Rate limiter
Controls Concurrency (how many at once) Whether to call at all Arrival rate (how many per second)
Triggered by Saturation of a slot pool Observed failures Time-based budget
Catches slow-but-OK dependency Yes No Partially
Catches erroring dependency Partially (only if slow too) Yes No
State Counter of in-flight Failure history + state machine Token bucket / time
Protects Your resources Their resources (and yours) Their resources
Reject reason "I'm full" "You're broken" "Too fast"

The distinction that matters most:

A circuit breaker asks "is the dependency healthy?" A bulkhead asks "how much of me is this dependency currently holding?"

The breaker needs evidence of failure. If the dependency returns 200s at 30 s latency, there is no evidence, and the breaker stays closed forever while your service dies. The bulkhead needs no evidence at all — it counts slots, and slots run out whether the calls are failing or merely slow.

Conversely, a bulkhead alone is insufficient. Consider a dependency that fails fast: connection refused in 1 ms. Concurrency never rises (calls complete instantly), so the bulkhead never engages — meanwhile you're hammering a dead service with your full request rate, and every one of your users gets an error after burning a retry budget. That's the breaker's job.

Use both. They compose cleanly (section 16):

   bulkhead  →  caps resource consumption      (defends against slow)
   breaker   →  stops calling a broken thing   (defends against failing)
   rate limit→  caps load you generate         (defends the dependency)

There is a partial overlap worth knowing: some breaker implementations (resilience4j) add a "slow call rate" trip condition — open when >50% of calls exceed T. That's a breaker borrowing the bulkhead's job. It works, and it has one advantage (it fails fast rather than making callers queue) and one disadvantage (it's all-or-nothing: 100% of traffic or 0%, whereas a bulkhead degrades gracefully to N concurrent). Having both is still better than either.


4. What resource are you actually partitioning?

"Bulkhead" is abstract until you name the resource. Get this wrong and you build a limiter that guards the wrong thing.

Resource Exhaustion symptom How to partition
Goroutines / threads Memory growth, scheduler pressure, GC pauses Semaphore around the call, or a fixed worker pool
Connections (HTTP, DB, gRPC) Calls block waiting for a pool slot Separate pool per dependency; cap MaxConnsPerHost
Memory OOM kill Cap concurrency × per-request footprint; cap body sizes
File descriptors accept: too many open files — you can't accept any connection Cap total connections, raise ulimit, reserve headroom
CPU Latency rises across the board Worker pool sized to GOMAXPROCS; not a semaphore
Inbound request slots Server queues grow, everything slows Bound inbound concurrency (section 14)
Downstream capacity Their problem, then yours Per-dependency concurrency cap + rate limit

Two notes from experience.

File descriptors are the nastiest because exhaustion is global and total: once you can't open a socket, you can't accept an inbound connection either, so your health check fails and you look completely dead. Any bulkhead sizing must leave FD headroom.

In Go, "goroutines" is usually the right answer, but the goroutine is a proxy for what it holds. A goroutine blocked in a network read is ~8 KB of stack — cheap. A goroutine holding a 10 MB decoded request body is not. Size against the expensive thing.

The shared-pool trap

The most common real-world bulkhead failure is not an absent bulkhead — it's a shared one that nobody realized was shared:

// Everything uses http.DefaultClient.
// DefaultTransport: MaxIdleConns 100, MaxIdleConnsPerHost 2, MaxConnsPerHost 0 (unlimited).
resp, err := http.DefaultClient.Do(req)

Every dependency shares one Transport, therefore one connection pool, therefore one failure domain. Also note MaxConnsPerHost: 0 means unlimited connections per host — there is no cap at all, so a slow host will happily accumulate thousands of connections. And MaxIdleConnsPerHost: 2 means that under any real concurrency you're constantly closing and re-dialing, which adds latency and FD churn.

One client per dependency, configured deliberately, is the baseline bulkhead you get almost for free (section 13).


5. Two flavors: semaphore and thread-pool isolation

Hystrix named these, and the distinction survives the JVM.

Semaphore isolation

A counter with a maximum. Acquire before the call, release after. The call runs on the caller's goroutine.

   caller goroutine ──► [acquire] ──► call dependency ──► [release]
                            │
                            └─► full? reject immediately
  • Pro: near-zero overhead (one atomic or a channel op), no extra goroutine, context and stack traces stay intact.

  • Con: the caller's goroutine is still consumed for the duration. You've capped how many are consumed, which is the point — but if the caller's goroutine is expensive (holds a big buffer), that cost is still paid N times.

  • Con: cannot enforce a timeout on a call that ignores its context. A dependency doing blocking syscall I/O with no context support will hold its slot indefinitely.

This is the default choice in Go, because goroutines are cheap and context-based cancellation is universal.

Worker-pool isolation

N pre-spawned worker goroutines pull tasks from a bounded queue. Callers submit and wait for a result.

   caller ──► [submit to queue] ──► worker 1 ──┐
                    │                worker 2  ├──► dependency
                    │                worker 3 ──┘
                    └─► queue full? reject
  • Pro: hard, absolute cap on concurrency and on the goroutines doing the work. The caller can abandon (context cancelled) while the worker is still running — which means the caller's goroutine is freed even when the dependency hangs.

  • Pro: natural place to add prioritization, batching, or per-worker resources (a dedicated connection each).

  • Con: an extra hop (channel send + receive) per call, ~microseconds.

  • Con: context propagation is manual — you must pass the caller's context in the task.
  • Con (the big one): if the caller abandons and the worker is stuck, the worker is still stuck. The pool degrades until every worker is blocked on a hung dependency. You've protected the caller but not the pool. Worker-side timeouts are mandatory.

Use worker pools when the work is CPU-bound (size to GOMAXPROCS), when you need each worker to own a resource, or when you truly cannot let the caller's goroutine be held. Otherwise, semaphore.


6. Sizing: Little's Law and where the number comes from

The single question everyone asks: what number? There is an actual answer, not a guess.

Little's Law

   L = λ × W

   L = average number of requests in the system (concurrency)
   λ = arrival rate (requests per second)
   W = average time in the system (latency, seconds)

To support λ requests/second at W latency, you need L concurrent slots. Rearranged, a bulkhead of size L supports throughput λ = L / W.

Worked example. Dependency B is called 50 times/second at p99 latency 200 ms.

   L = 50 × 0.2 = 10 concurrent calls, on average

Size the bulkhead at 10 and you'll reject constantly, because 10 is the average and arrivals are bursty. Add headroom:

   limit = ceil(L × burst_factor)
         = ceil(10 × 2) = 20

burst_factor of 2–3 covers normal Poisson burstiness. Now check the failure case:

   B degrades to 5 s latency.
   With limit=20: throughput = 20 / 5 = 4 rps served, 46 rps rejected.
   Goroutines held: 20. Memory: 20 × per-request footprint. Bounded. 

That is the whole design, in three lines of arithmetic.

The upper bound: what you can afford

Little's Law gives the number you need. The other constraint is what you can survive:

   max_limit = min(
       available_memory / per_request_memory,
       connection_pool_size,
       fd_limit − reserved_headroom,
       downstream's_stated_concurrency_limit
   )

If L × burst_factor > max_limit, you have a capacity problem that no bulkhead will fix — but the bulkhead is still what converts "OOM at 3 a.m." into "rejections you can see on a graph".

Sum across compartments

The compartments are separate, but they draw on one process. Check:

   Σ (limit_i) ≤ total capacity

Five dependencies × 100 slots each = 500 concurrent outbound calls if all saturate simultaneously. Can your process hold 500? If not, you've partitioned the resource without actually bounding it — the compartments are watertight but the ship is overloaded. Either shrink the limits or add a global cap on top (a two-level bulkhead: per-dependency limits plus a total limit).

When you don't know W

You often don't, especially for a new dependency. Options, in order:

  1. Measure it. Deploy with the bulkhead in "observe" mode — count in-flight, never reject — and read the high-water mark off a graph for a week. Then set the limit to watermark × 2.

  2. Start generously and tighten. A limit of 200 that never rejects still gives you the metric, and still prevents unbounded growth.

  3. Use an adaptive limit that discovers W itself (section 15). Best for dependencies whose capacity genuinely varies (autoscaling backends).

The mistake is setting a tight limit on day one with no data, discovering it rejects legitimate traffic, and concluding bulkheads are a bad idea.


7. Queueing: the bounded waiting room

Pure "reject when full" is harsh: a 10 ms burst above the limit sheds requests that would have been served fine 10 ms later. So most bulkheads allow a bounded wait.

        ┌──────────── bulkhead ────────────┐
        │                                  │
   ───► │  queue (bounded)  →  N slots     │ ───► dependency
        │  ├─ full? reject                 │
        │  └─ waited too long? reject      │
        └──────────────────────────────────┘

Three knobs, all of which must be finite:

limit — concurrent slots. From section 6.

queueSize — how many may wait. Zero is a legitimate and often correct choice. Non-zero smooths bursts; too large converts a concurrency problem into a latency problem.

maxWait — how long a queued request waits before giving up. Usually derived from the caller's context deadline rather than configured.

Why the queue must be small

This is the deepest point in the whole pattern, so it gets its own derivation.

A queued request is a request that is not making progress but is still holding resources — its goroutine, its parsed body, its slot in the inbound limit. A large queue therefore reintroduces the exact problem the bulkhead exists to solve, just one layer out.

Worse, it inflates latency. By Little's Law applied to the queue:

   wait_time = queue_length / throughput

With limit = 20, W = 200 ms (so throughput = 100 rps) and queueSize = 1000:

   wait_time at full queue = 1000 / 100 = 10 seconds

Ten seconds of waiting to then take 200 ms. Every one of those callers has a 3 s deadline, so every one of them times out — after occupying a queue slot for their full deadline, blocking newcomers who might have been served. This is bufferbloat, and it is a performance regression disguised as generosity.

The rule:

queueSize should be small enough that a request at the back of a full queue can still be served within its deadline.

   queueSize ≤ (deadline − W) × throughput
             = (3 s − 0.2 s) × 100 = 280

And that's the maximum; in practice limit to 2 × limit (i.e. 20–40 here) is a better default, because a queue that deep already tells you you're overloaded.

Deadline-aware queueing beats deep queues

Better than sizing a queue perfectly: make queued requests leave when they can't be served in time. Two mechanisms:

  1. Context-aware waiting (section 11): a request whose context expires while queued abandons immediately and frees the slot. This is nearly free in Go and you should always do it.

  2. Drop-oldest / LIFO under load. Counter-intuitive but effective: under overload, serving the newest request first means at least some requests meet their deadline, whereas FIFO means everyone waits the full queue depth and everyone times out. Finagle and Envoy both do variants of this. It's an advanced move — it makes latency distributions weird — but when you're shedding load, "some requests succeed" beats "all requests fail fairly".


8. Partitioning dimensions: dependency, tenant, priority

Same question as breaker granularity (Circuit Breakers, section 6): what's a compartment?

By dependency — the default

One bulkhead per downstream service (or per service+endpoint, if endpoints hit different backends). This is the case from section 1 and covers most needs.

By tenant — noisy-neighbor isolation

In multi-tenant systems, one customer's traffic spike shouldn't starve everyone else.

   ┌─ tenant A: 50 slots ─┐
   ┌─ tenant B: 50 slots ─┤──► shared backend (200 total)
   ┌─ tenant C: 50 slots ─┤
   └─ shared:   50 slots ─┘

The catch: static per-tenant limits waste capacity. If A is idle, its 50 slots sit unused while B is being rejected. Two fixes:

  • Reserved + shared: each tenant gets a small guaranteed reservation plus access to a shared pool. Guarantees a floor without capping the ceiling.

  • Weighted fair queueing: allocate proportionally to demand, so an idle tenant's share is redistributed. More machinery; use when tenant counts are large or dynamic.

Also: bound the number of compartments. A bulkhead per tenant with 10,000 tenants is 10,000 semaphores, and if tenant IDs come from requests it's an unbounded map (same OOM risk as the breaker registry). Bucket small tenants together.

By priority / criticality

   ┌─ interactive (user-facing): 80 slots ─┐
   ├─ batch (reports, exports):  15 slots ─┤──► shared DB
   └─ background (cleanup):       5 slots ─┘

This is often the highest-value partitioning and the most neglected. A nightly batch job that shares a connection pool with user traffic will eventually degrade a user-facing path. Giving background work a small, hard budget is a one-line change that prevents a whole class of incidents.

Note the asymmetry: it's fine for batch work to be slow. It is not fine for interactive work to be slow. The bulkhead encodes that priority in a way "we'll be careful" does not.

By operation cost

Reads and writes, or cheap and expensive queries, can warrant separate compartments — a full-table-scan report shouldn't be able to consume every connection that point-lookups need.


9. Failure modes and what rejection means

Rejection is a feature, not an error

ErrBulkheadFull means: "the system is at capacity, and I am telling you now rather than in 30 seconds." Handle it accordingly:

Response When
503 + Retry-After Your caller can retry later. The standard answer.
Serve degraded/cached Same fallbacks as a breaker (Circuit Breakers, section 7).
Shed by priority Reject low-priority work, admit high-priority. Requires a priority signal.
Backpressure upstream If the caller is a queue consumer, stop consuming — the best possible response, since it propagates the signal to where the work originates.

Never: retry immediately in a loop (spins against the semaphore), or convert it into a generic 500 (loses the "I'm overloaded" signal that would have told you to scale).

Ways bulkheads go wrong

Failure mode Symptom Cause Fix
Limit too low Rejections during normal traffic Sized without measuring section 6; observe first
Limit too high Never engages; you OOM anyway "Safe" large number Compute from Little's Law
Queue too deep Everything times out; latency cliff Bufferbloat section 7
Leaked slots Slowly stops admitting anything, forever Missing release on an error path defer release(), always
Shared pool underneath Bulkheads exist but don't isolate One http.Transport for all deps section 13
Compartment sum > capacity All limits respected, process still dies Σ limits unbounded section 6
Unbounded compartments Memory growth Per-tenant map keyed by request data section 8
Worker pool wedged Pool alive, nothing progresses Every worker blocked on a hung call Worker-side timeouts (section 12)
No timeout inside Slots held forever, limit is meaningless Bulkhead without a deadline section 16

The leaked-slot bug deserves emphasis because it is silent and permanent. Every acquire must have exactly one release, on every path including panics. defer release() on the line after a successful acquire is the only pattern that's reliably correct — and note the ordering: defer must come after the acquire succeeds, never before, or you'll release a slot you never took.


Part II — Building them in Go


10. The semaphore bulkhead

A buffered channel is a semaphore. This is the whole pattern:

package bulkhead

import (
    "context"
    "errors"
)

var (
    // ErrFull means the bulkhead is at capacity and the caller did not wait.
    ErrFull = errors.New("bulkhead: at capacity")
)

type Bulkhead struct {
    slots chan struct{}
}

func New(limit int) *Bulkhead {
    if limit <= 0 {
        panic("bulkhead: limit must be > 0")
    }
    return &Bulkhead{slots: make(chan struct{}, limit)}
}

// TryAcquire takes a slot if one is free, without waiting.
func (b *Bulkhead) TryAcquire() (release func(), ok bool) {
    select {
    case b.slots <- struct{}{}:
        return b.releaseFn(), true
    default:
        return nil, false
    }
}

func (b *Bulkhead) releaseFn() func() {
    var once sync.Once
    return func() { once.Do(func() { <-b.slots }) }
}

// Do runs op if a slot is available, otherwise returns ErrFull immediately.
func (b *Bulkhead) Do(ctx context.Context, op func(context.Context) error) error {
    release, ok := b.TryAcquire()
    if !ok {
        return ErrFull
    }
    defer release()
    return op(ctx)
}

Why a channel rather than sync/semaphore or an atomic counter:

  • It composes with select, which is what makes context-aware waiting (section 11) trivial.
  • len(b.slots) gives you the in-flight gauge for free.
  • The default branch gives you non-blocking acquire with no extra machinery.

golang.org/x/sync/semaphore is a fine alternative and supports weighted acquisition (useful when requests have very different costs), at the price of a dependency.

The sync.Once in releaseFn is the same defense as in the breaker: a double release would add a slot to the pool, permanently raising the limit — a silent correctness bug that only shows up as "the bulkhead stopped working" months later.

Reporting saturation

func (b *Bulkhead) InFlight() int  { return len(b.slots) }
func (b *Bulkhead) Limit() int     { return cap(b.slots) }
func (b *Bulkhead) Available() int { return cap(b.slots) - len(b.slots) }

These are inherently racy — the value can change between read and use — which is fine for metrics and wrong for decisions. Never do if b.Available() > 0 { acquire() }; that's the check-then-act race from Circuit Breakers, section 11. The select is the atomic decision.


11. Bounded queueing with a deadline

Now add the waiting room from section 7, with the crucial property that a caller whose context expires stops waiting.

type Config struct {
    Limit     int           // concurrent slots
    QueueSize int           // 0 = reject immediately when full
    MaxWait   time.Duration // 0 = bounded only by ctx
}

type Bulkhead struct {
    slots chan struct{}
    queue chan struct{} // bounds the number of WAITERS
}

func New(c Config) *Bulkhead {
    b := &Bulkhead{slots: make(chan struct{}, c.Limit)}
    if c.QueueSize > 0 {
        b.queue = make(chan struct{}, c.QueueSize)
    }
    b.maxWait = c.MaxWait
    return b
}

// Acquire takes a slot, waiting up to MaxWait or until ctx is done.
func (b *Bulkhead) Acquire(ctx context.Context) (release func(), err error) {
    // Fast path: a slot is free right now.
    select {
    case b.slots <- struct{}{}:
        return b.releaseFn(), nil
    default:
    }

    if b.queue == nil {
        return nil, ErrFull
    }

    // Claim a waiting-room slot. Full waiting room = immediate rejection,
    // which is what keeps the queue bounded.
    select {
    case b.queue <- struct{}{}:
        defer func() { <-b.queue }()
    default:
        return nil, ErrQueueFull
    }

    if b.maxWait > 0 {
        var cancel context.CancelFunc
        ctx, cancel = context.WithTimeout(ctx, b.maxWait)
        defer cancel()
    }

    select {
    case b.slots <- struct{}{}:
        return b.releaseFn(), nil
    case <-ctx.Done():
        // Deadline hit while queued: leave, free the waiting-room slot
        // (the deferred receive above), admit someone with a better chance.
        return nil, fmt.Errorf("bulkhead: %w", ctx.Err())
    }
}

The structure is two nested gates:

   ┌─ queue (bounded waiters) ─┐
   │   ┌─ slots (bounded ─┐    │
   │   │    in-flight)    │    │
   │   └──────────────────┘    │
   └───────────────────────────┘

The outer gate is what makes this safe. Without b.queue, an unbounded number of goroutines would sit in the select, each holding a goroutine and its request state — you'd have moved the unbounded resource consumption from "in flight" to "waiting", which is no improvement at all. The waiting room must be bounded for the same reason the slot pool must be.

The defer func() { <-b.queue }() placement is deliberate: it runs on every exit path from that point on — success, timeout, cancellation. Leaking a waiting-room slot has the same permanent-degradation effect as leaking a real slot.

On fairness

Go channels do not guarantee FIFO wakeup for a select on a send. Under contention the runtime may wake waiters in an order that leaves some goroutine waiting much longer than others — tail-latency unfairness. For most bulkheads this doesn't matter (everyone's context bounds their wait). If you need strict FIFO — say, ordered processing — build an explicit queue of channels, one per waiter, and hand off in order. That's real code and real cost; don't reach for it without a measured need.


12. The worker-pool bulkhead

When you want the work off the caller's goroutine entirely (section 5).

type task struct {
    ctx    context.Context
    op     func(context.Context) error
    result chan error
}

type Pool struct {
    tasks   chan task
    wg      sync.WaitGroup
    quit    chan struct{}
    timeout time.Duration // per-task, worker-side
}

func NewPool(workers, queueSize int, taskTimeout time.Duration) *Pool {
    p := &Pool{
        tasks:   make(chan task, queueSize),
        quit:    make(chan struct{}),
        timeout: taskTimeout,
    }
    p.wg.Add(workers)
    for i := 0; i < workers; i++ {
        go p.worker()
    }
    return p
}

func (p *Pool) worker() {
    defer p.wg.Done()
    for {
        select {
        case <-p.quit:
            return
        case t, ok := <-p.tasks:
            if !ok {
                return
            }
            p.run(t)
        }
    }
}

func (p *Pool) run(t task) {
    // Recover: a panicking task must not kill the worker, or the pool
    // silently shrinks to zero over time.
    defer func() {
        if r := recover(); r != nil {
            t.result <- fmt.Errorf("bulkhead: task panicked: %v", r)
        }
    }()

    ctx := t.ctx
    // Worker-side timeout is MANDATORY (§5): without it, a hung dependency
    // wedges this worker forever even though the caller gave up long ago.
    if p.timeout > 0 {
        var cancel context.CancelFunc
        ctx, cancel = context.WithTimeout(ctx, p.timeout)
        defer cancel()
    }

    t.result <- t.op(ctx)
}

// Submit enqueues op and waits for its result, or for ctx to expire.
func (p *Pool) Submit(ctx context.Context, op func(context.Context) error) error {
    // Buffered size 1: the worker can always deliver the result and move on,
    // even if the caller has already abandoned. Unbuffered would leak the
    // worker on the send.
    res := make(chan error, 1)
    t := task{ctx: ctx, op: op, result: res}

    select {
    case p.tasks <- t:
    case <-ctx.Done():
        return fmt.Errorf("bulkhead: %w", ctx.Err())
    default:
        return ErrQueueFull
    }

    select {
    case err := <-res:
        return err
    case <-ctx.Done():
        // The caller stops waiting; the worker keeps running until its own
        // timeout. That asymmetry is the pool's main hazard — see below.
        return fmt.Errorf("bulkhead: %w", ctx.Err())
    }
}

func (p *Pool) Shutdown(ctx context.Context) error {
    close(p.quit)
    done := make(chan struct{})
    go func() { p.wg.Wait(); close(done) }()
    select {
    case <-done:
        return nil
    case <-ctx.Done():
        return ctx.Err()
    }
}

Three details that are easy to get wrong:

res must be buffered (size 1). If it's unbuffered and the caller has already returned on ctx.Done(), the worker blocks forever on t.result <- .... One leaked worker per abandoned request, and the pool silently dies. This is the most common worker-pool bug in Go.

recover() in the worker is not optional. A panic in op without it kills the goroutine; the pool now has workers-1 workers, and nothing ever notices. Over weeks you degrade to zero.

The caller/worker asymmetry. Submit returning on ctx.Done() frees the caller, but the worker is still executing. If the dependency hangs and taskTimeout is unset, every worker eventually wedges and the pool is dead while looking perfectly healthy (goroutine count normal, no errors). Always set taskTimeout, and alert on "tasks completed" going to zero while "tasks submitted" stays non-zero.

Note the combined select with both <-ctx.Done() and default in Submit: the default makes the send non-blocking, so a full queue is rejected instantly rather than waiting. If you want bounded waiting instead, drop default and rely on ctx.


13. Connection pools are bulkheads (and where they lie to you)

You already have bulkheads. They're just misconfigured.

http.Transport

func newClient(host string) *http.Client {
    return &http.Client{
        Transport: &http.Transport{
            // THE bulkhead: hard cap on concurrent connections to this host.
            // Default is 0 = UNLIMITED. This is the line that matters.
            MaxConnsPerHost: 50,

            // Keep-alive pool sizing. Default MaxIdleConnsPerHost is 2, which
            // causes constant re-dialing under concurrency. Match MaxConnsPerHost.
            MaxIdleConns:        50,
            MaxIdleConnsPerHost: 50,
            IdleConnTimeout:     90 * time.Second,

            DialContext: (&net.Dialer{
                Timeout:   2 * time.Second,  // bound connection establishment
                KeepAlive: 30 * time.Second,
            }).DialContext,
            TLSHandshakeTimeout:   2 * time.Second,
            ResponseHeaderTimeout: 5 * time.Second, // first byte of response
            ExpectContinueTimeout: 1 * time.Second,
        },
        // Total per-request budget, covering redirects and body read.
        Timeout: 10 * time.Second,
    }
}

One client per dependency. Sharing http.DefaultClient shares the pool, which means sharing the failure domain (section 4).

But MaxConnsPerHost alone is a leaky bulkhead, and here's why: when the pool is exhausted, RoundTrip blocks waiting for a connection rather than failing. That wait is unbounded except by the request context. So you get concurrency capping without load shedding — the goroutines pile up in the wait, exactly the section 1 problem. MaxConnsPerHost bounds connections, not callers.

The fix is to put an explicit semaphore bulkhead outside the client, sized at or below MaxConnsPerHost, so that excess callers are rejected rather than queued:

// bulkhead limit ≤ MaxConnsPerHost, so the transport never becomes the
// blocking point and rejection happens at our (fast, observable) layer.
type Transport struct {
    Next http.RoundTripper
    BH   *Bulkhead
}

func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) {
    release, err := t.BH.Acquire(req.Context())
    if err != nil {
        return nil, fmt.Errorf("%s: %w", req.URL.Host, err)
    }

    resp, err := t.Next.RoundTrip(req)
    if err != nil {
        release()
        return nil, err
    }

    // CRITICAL: the slot is held until the BODY is closed, not until headers
    // arrive. A caller that streams a response for 30s is occupying the
    // dependency for 30s, and the bulkhead must reflect that.
    resp.Body = &releaseOnClose{ReadCloser: resp.Body, release: release}
    return resp, nil
}

type releaseOnClose struct {
    io.ReadCloser
    release func()
    once    sync.Once
}

func (r *releaseOnClose) Close() error {
    defer r.once.Do(r.release)
    return r.ReadCloser.Close()
}

The body-close detail is the one people miss. RoundTrip returns as soon as response headers arrive; the body may stream for a long time afterward, holding a connection the whole time. Releasing the slot at RoundTrip return would let you admit far more concurrent work than the connection pool can support — the bulkhead would be reporting "10 in flight" while 200 connections are open.

The cost: if a caller forgets resp.Body.Close(), the slot leaks permanently. That is already a bug (it leaks the connection too), but this makes the consequence more severe. Worth a comment at the call site, and net/http/httputil's leak checkers in tests.

database/sql

db.SetMaxOpenConns(25)                  // the bulkhead
db.SetMaxIdleConns(25)                  // match, to avoid churn
db.SetConnMaxLifetime(5 * time.Minute)  // survive DB failovers, rotate creds
db.SetConnMaxIdleTime(1 * time.Minute)

Same leak: db.QueryContext blocks waiting for a free connection when MaxOpenConns is reached. Bounded only by the context. So the same rule applies — pass a context with a deadline to every query, always, and consider an explicit bulkhead in front for the load-shedding behavior.

Sizing MaxOpenConns has an extra constraint: replicas × MaxOpenConns ≤ database's max_connections, with headroom for admin sessions. Fifty replicas × 25 conns = 1250, which exceeds a default Postgres max_connections of 100 by an order of magnitude. This is a real and common production outage — the DB starts refusing all connections, including your monitoring's. Use a connection pooler (PgBouncer) or size down hard.


14. Server-side: bounding inbound concurrency

Bulkheads apply to work you accept, not just work you make. An unbounded inbound concurrency is the server-side version of section 1.

// LimitConcurrency bounds in-flight handler invocations. Requests over the
// limit get 503 immediately rather than queueing in the runtime.
func LimitConcurrency(limit int, next http.Handler) http.Handler {
    sem := make(chan struct{}, limit)
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        select {
        case sem <- struct{}{}:
            defer func() { <-sem }()
            next.ServeHTTP(w, r)
        default:
            w.Header().Set("Retry-After", "1")
            http.Error(w, "server at capacity", http.StatusServiceUnavailable)
        }
    })
}

Per-route partitioning is where this gets valuable — the section 1 scenario, solved at the door:

mux := http.NewServeMux()
mux.Handle("/health",  healthHandler)                                // no limit: must always answer
mux.Handle("/orders",  LimitConcurrency(200, ordersHandler))         // the money path
mux.Handle("/reports", LimitConcurrency(20,  reportsHandler))        // the risky path

/health deliberately has no limit. It must respond even when everything else is saturated, or your load balancer will pull a node that is correctly shedding load — the worst possible outcome, since it moves that load to the remaining nodes and cascades.

Three companions to this middleware:

Server timeouts. A concurrency limit is useless if requests never complete:

srv := &http.Server{
    ReadHeaderTimeout: 5 * time.Second,   // slowloris defense
    ReadTimeout:       30 * time.Second,
    WriteTimeout:      30 * time.Second,
    IdleTimeout:       120 * time.Second,
    MaxHeaderBytes:    1 << 20,
}

Body size limits. http.MaxBytesReader(w, r.Body, 10<<20). Concurrency × body size is your memory exposure; capping concurrency without capping body size caps nothing.

Total connection cap. netutil.LimitListener from golang.org/x/net bounds accepted connections, protecting file descriptors below the HTTP layer.

The full stack, outermost first:

   LimitListener (FDs) → Server timeouts → LimitConcurrency (goroutines)
     → MaxBytesReader (memory) → handler → outbound bulkhead → breaker → retry → timeout

15. Adaptive bulkheads: AIMD and Gradient

Static limits have a real weakness: the right number changes. The dependency autoscales, a deploy makes it faster, a neighbor makes it slower. A limit tuned in March is wrong in June.

Adaptive limiters discover the concurrency limit from observed latency, using the same idea as TCP congestion control: latency rising above baseline means you're queueing somewhere downstream, which means back off.

AIMD — additive increase, multiplicative decrease

type AIMDLimiter struct {
    mu       sync.Mutex
    limit    float64
    minLimit float64
    maxLimit float64
    backoff  float64 // e.g. 0.9
}

// Update is called after every completed call.
func (l *AIMDLimiter) Update(rtt time.Duration, inFlight int, dropped bool) {
    l.mu.Lock()
    defer l.mu.Unlock()

    if dropped {
        // Multiplicative decrease: react fast to overload.
        l.limit = math.Max(l.minLimit, l.limit*l.backoff)
        return
    }
    // Only grow when we're actually using what we have. Growing while idle
    // would let the limit drift to maxLimit with no evidence it's safe.
    if float64(inFlight) >= l.limit*0.9 {
        l.limit = math.Min(l.maxLimit, l.limit+1)
    }
}

func (l *AIMDLimiter) Limit() int {
    l.mu.Lock()
    defer l.mu.Unlock()
    return int(l.limit)
}

Same shape as TCP: probe upward slowly, retreat quickly. dropped here means a timeout or a rejection — evidence of overload.

Gradient — latency ratio

Netflix's concurrency-limits library. Compare current latency to the best latency seen (the "no queueing" baseline):

type GradientLimiter struct {
    mu        sync.Mutex
    limit     float64
    longRTT   float64 // slow-moving average
    shortRTT  float64 // recent
    minLimit  float64
    maxLimit  float64
    smoothing float64 // e.g. 0.2
}

func (l *GradientLimiter) Update(rtt time.Duration, inFlight int) {
    l.mu.Lock()
    defer l.mu.Unlock()

    sample := float64(rtt.Microseconds())
    l.shortRTT = sample
    if l.longRTT == 0 {
        l.longRTT = sample
    } else {
        // Exponentially weighted; tracks the "uncongested" baseline.
        l.longRTT = l.longRTT*0.95 + sample*0.05
    }

    // gradient < 1 => we are slower than baseline => queueing => shrink.
    // Clamped at 0.5 so one latency spike can't halve the limit repeatedly.
    gradient := math.Max(0.5, math.Min(1.0, l.longRTT/l.shortRTT))

    // Allow headroom to probe upward: sqrt(limit) is the classic choice.
    newLimit := l.limit*gradient + math.Sqrt(l.limit)
    l.limit = l.limit*(1-l.smoothing) + newLimit*l.smoothing
    l.limit = math.Max(l.minLimit, math.Min(l.maxLimit, l.limit))
}

The intuition: if requests are taking twice as long as they do when uncongested, there's a queue somewhere, and adding concurrency will only make the queue longer. Shrink until latency returns to baseline.

When to use adaptive limits

Use static Use adaptive
Capacity is known and stable Capacity varies (autoscaling, shared, multi-tenant)
You want predictable, explainable behavior You can't keep re-tuning by hand
Small number of dependencies Many dependencies, hand-tuning doesn't scale
Debuggability matters most Efficiency matters most

Start static. An adaptive limiter is another control loop that can oscillate, and when it misbehaves at 3 a.m. "why is the limit 4 right now?" is a genuinely hard question. Always keep minLimit well above zero and maxLimit at a value you know you can survive — the adaptive logic operates inside the static bounds, never replaces them.


16. Composing bulkhead + breaker + retry + timeout

The full stack, with the reasoning for each layer's position (see also Circuit Breakers, section 8):

   ┌─────────────────────────────────────────────────┐
   │ 1. BULKHEAD    cap concurrency                  │  reject when full
   │  ┌───────────────────────────────────────────┐  │
   │  │ 2. BREAKER   skip a known-broken dep      │  │  reject when open
   │  │  ┌─────────────────────────────────────┐  │  │
   │  │  │ 3. RETRY    re-attempt failures     │  │  │  N attempts
   │  │  │  ┌───────────────────────────────┐  │  │  │
   │  │  │  │ 4. TIMEOUT  bound one attempt │  │  │  │  frees the slot
   │  │  │  │      the actual call          │  │  │  │
   │  │  │  └───────────────────────────────┘  │  │  │
   │  │  └─────────────────────────────────────┘  │  │
   │  └───────────────────────────────────────────┘  │
   └─────────────────────────────────────────────────┘

Bulkhead outermost — it protects a resource that must be bounded regardless of dependency health, and it's the only layer that helps when the dependency is slow but succeeding. It must also cover the retries: three attempts inside the bulkhead consume one slot, not three, so the concurrency cap means what it says.

Breaker next — outside the retry so one logical operation is one observation, and so that an open breaker skips the whole retry loop.

Retry inside the breaker — the breaker gets an accurate per-operation failure signal.

Timeout innermost — it's what produces the failure signal and what releases the bulkhead slot. Without it, slots are held indefinitely and the bulkhead's limit is a fiction.

type Resilient struct {
    BH    *bulkhead.Bulkhead
    CB    *breaker.Breaker
    Retry retry.Policy
    PerAttempt time.Duration
}

func (r *Resilient) Do(ctx context.Context, op func(context.Context) error) error {
    // 1. Bulkhead: covers everything below, including all retry attempts.
    release, err := r.BH.Acquire(ctx)
    if err != nil {
        return err // ErrFull — shed load, fast
    }
    defer release()

    // 2. Breaker: outside the retry loop.
    done, err := r.CB.Allow()
    if err != nil {
        return err // ErrOpen — fail fast
    }

    // 3. Retry, with 4. per-attempt timeouts inside.
    err = r.Retry.Do(ctx, func(ctx context.Context) error {
        attemptCtx, cancel := context.WithTimeout(ctx, r.PerAttempt)
        defer cancel()
        return op(attemptCtx)
    })

    done(err) // one observation per logical operation
    return err
}

The budget must nest

   caller deadline                    10 s
     bulkhead max wait                 1 s   ← give up queueing early
       retry: 3 attempts
         per-attempt timeout           2 s   ← 3 × 2 = 6 s
         backoff + jitter             ~1 s
                                     ──────
                                      ~8 s   ← fits in 10 s ✓

If maxWait + attempts × perAttempt + backoff > callerDeadline, the last attempt is always cancelled in flight: you generate load on the dependency and never use the answer. Check this arithmetic explicitly; nothing will check it for you.

Ordering of the error signals

Note that ErrFull and ErrOpen mean different things and should be distinguishable by the caller and in metrics:

  • ErrFull → we are saturated. Scale up, or shed. The dependency may be fine.
  • ErrOpen → they are broken. Scaling up won't help.

Collapsing both into "503 upstream error" throws away the one bit of information that tells you what to do.


17. Testing and observability

Metrics — four, same shape as the breaker's

  1. bulkhead_in_flight{name} (gauge) — current occupancy. Graph it against the limit; the ratio is your saturation, and it's the leading indicator of everything else.

  2. bulkhead_rejected_total{name, reason} (counter) — reason ∈ {full, queue_full, timeout}. This is user-visible impact. Alert on any sustained non-zero value.

  3. bulkhead_wait_seconds{name} (histogram) — how long callers queued. If p99 wait approaches the deadline, your queue is too deep (section 7).

  4. bulkhead_hold_seconds{name} (histogram) — how long slots were held. This is W in Little's Law; when it rises, your effective throughput has fallen and the limit needs revisiting.

Saturation (in_flight / limit) sustained above ~80% is the number to alert on. It gives you warning before rejections start, which is the whole reason to instrument this.

Testing

The properties worth asserting:

func TestNeverExceedsLimit(t *testing.T) {
    const limit = 10
    b := New(Config{Limit: limit})

    var current, peak atomic.Int32
    var wg sync.WaitGroup

    for i := 0; i < 1000; i++ {
        wg.Add(1)
        go func() {
            defer wg.Done()
            _ = b.Do(context.Background(), func(context.Context) error {
                n := current.Add(1)
                defer current.Add(-1)
                // Track the high-water mark.
                for {
                    p := peak.Load()
                    if n <= p || peak.CompareAndSwap(p, n) {
                        break
                    }
                }
                time.Sleep(time.Millisecond)
                return nil
            })
        }()
    }
    wg.Wait()

    if got := peak.Load(); got > limit {
        t.Fatalf("peak concurrency = %d, want ≤ %d", got, limit)
    }
    if n := b.InFlight(); n != 0 {
        t.Fatalf("leaked %d slots", n)
    }
}

That second assertion — zero in-flight at the end — is the slot-leak detector, and it belongs in every bulkhead test. Run the whole suite under -race.

Other tests worth having:

Test Guards against
Rejection when full, without waiting (QueueSize: 0) Accidental blocking
Queued caller with an expired context returns promptly section 11 deadline handling
Panic inside op still releases the slot Missing defer
Worker pool: caller abandons, worker still finishes and doesn't block section 12 unbuffered-result bug
Worker pool: task panics, pool still has N workers section 12 missing recover
Slot held until resp.Body.Close(), not until RoundTrip returns section 13

Load testing is where bulkheads prove themselves

Unit tests verify the mechanism; only a load test verifies the sizing. The experiment:

  1. Run at expected load. Confirm zero rejections and in_flight well below the limit.
  2. Inject latency into the dependency (a proxy like toxiproxy, or a time.Sleep in a test double). Confirm in_flight pins at the limit, rejections start, and unrelated endpoints are unaffected — that last check is the entire point of the pattern.

  3. Remove the latency. Confirm recovery is prompt and there's no backlog of queued requests still timing out (which would indicate bufferbloat, section 7).

Step 2 is a test you can only get from a fault injection run, and it's the one that turns "we have bulkheads" into "we know our bulkheads work".


Reference

Sizing cheat sheet

   1. Measure λ (rps) and W (p99 latency) for the dependency.
   2. L = λ × W
   3. limit = ceil(L × 2)                     ← burst headroom
   4. Sanity-check against capacity:
        limit ≤ memory_budget / per_request_memory
        limit ≤ connection_pool_size
        Σ all limits ≤ what the process can actually hold
   5. queueSize = 0, or limit..2×limit if you need burst smoothing.
        Never more than (deadline − W) × throughput.
   6. Verify: at degraded latency W', throughput = limit / W'. Acceptable?
Scenario limit queueSize Notes
Critical low-latency dep (50 rps, 20 ms) 10 10 L = 1; headroom dominates
Normal dep (100 rps, 200 ms) 40 20 L = 20
Slow/batch dep (5 rps, 2 s) 20 0 L = 10; reject rather than queue
Background/cleanup work 2–5 0 Deliberately starved
Inbound, money path 200 0 Shed fast, don't queue
Inbound, health check ∞ — Must always answer

Anti-patterns

Anti-pattern Why it's wrong
Unbounded queue in front of a bulkhead Reintroduces unbounded resource use; bufferbloat (section 7)
Bulkhead without an inner timeout Slots held forever; the limit is fiction (section 16)
Sharing http.DefaultClient across dependencies One failure domain; no isolation at all (section 4)
Sizing by round number ("100 feels safe") Either too low (rejects real traffic) or too high (doesn't protect) (section 6)
Retry immediately on ErrFull Spins against the semaphore, adds load during overload (section 9)
A limit per user ID from request data Unbounded map; slow OOM (section 8)
Health check behind the bulkhead LB removes a node that is correctly shedding load (section 14)
Releasing a slot at RoundTrip return Body streaming still holds the connection (section 13)
Worker pool with an unbuffered result channel Leaks a worker per abandoned caller (section 12)
Bulkhead instead of a breaker No protection against a fast-failing dependency (section 3)
Breaker instead of a bulkhead No protection against a slow-but-succeeding dependency (section 3)

Glossary

  • Bulkhead — Resource partition limiting how much one failure domain can consume.
  • Semaphore isolation — Counting limiter; work runs on the caller's goroutine.
  • Thread-pool / worker-pool isolation — Fixed workers pull from a bounded queue.
  • Little's Law — L = λ × W; concurrency = arrival rate × time in system.
  • Load shedding — Deliberately rejecting work to protect the rest.
  • Backpressure — Propagating "slow down" toward the source of the work.
  • Bufferbloat — Deep queues that convert a throughput problem into a latency disaster.
  • Noisy neighbor — One tenant's load degrading others sharing a resource.
  • Saturation — in_flight / limit; the leading indicator of trouble.
  • AIMD — Additive increase, multiplicative decrease. TCP's congestion algorithm.
  • Gradient limiter — Adaptive limit driven by the ratio of current to baseline latency.
  • Blast radius — How much of the system one failure can reach.

Exercises

  1. Build the section 1 scenario: a service with /orders and /reports, where /reports calls a dependency you can make slow. Load-test it, watch goroutine count explode, then add a bulkhead and confirm /orders survives. This is the single most convincing demonstration of the pattern.

  2. Compute the limit for a dependency you actually own, from real λ and W. Compare it to whatever number is configured today. Explain the difference.

  3. Implement the releaseOnClose body wrapper from section 13 and write a test that a caller who forgets Close() leaks a slot. Then decide whether to add a finalizer or a leak detector.

  4. Take the worker pool from section 12, remove the buffer on res, and write the test that demonstrates the leaked worker. Then remove the recover() and demonstrate the shrinking pool.

  5. Implement the AIMD limiter (section 15) and drive it with a simulated dependency whose capacity halves at t=60 s. Plot the limit over time. How long does it take to converge? Does it oscillate?

  6. Compare: a breaker with a "slow call rate" trip condition vs. a bulkhead, against a dependency at 30 s latency returning 200s. Which sheds load faster? Which recovers faster? Which would you rather explain in a postmortem?

  7. Argue for queueSize: 0 as the default. What do you lose?

See also