DevPath
Foundation lesson · 12 min

Fan out with bounded workers

Cap concurrent work and stop promptly on cancellation.

Bound the fan-out

Starting one goroutine per item can overwhelm a downstream API when input grows. Use a fixed number of workers reading from a jobs channel or a semaphore. Select a limit from downstream capacity and measure throughput rather than assuming more workers are always faster.

Give every path an exit

Workers should stop when the context is canceled or the jobs channel closes. The producer must also stop sending when cancellation arrives, or it can block forever. Use a WaitGroup or an error group to know when workers have finished, and close output channels only after all senders exit.

select {
case jobs <- item:
case <-ctx.Done():
    return ctx.Err()
}

Decide how errors combine

If any item failure invalidates the batch, cancel the rest and return the first useful error. If partial success is acceptable, return successes plus item-level failures. Test empty input, a failed item, and cancellation while the queue is full. A race detector run is valuable for shared results.

Check your understanding

Why can a producer hang after all workers cancel?

Show explanation

It may still be blocked sending to the jobs channel. The send path must also select on ctx.Done().

Try it at foundation level

Design a three-worker pipeline for twenty jobs. Show how producers stop when the context is canceled and how results are drained.

Check your work

Concurrency never exceeds three, channels close from their sender, and cancellation cannot leave a goroutine blocked on send.

Self-guided practice. This does not record assessed mastery.

Put this lesson into practice

A related activity in this module at mid level.

Try: Fan out with a bounded worker pool

Further reading

Primary references for this module. Check the current version when behavior or framework guidance may have changed.