Lesson 5 of 9 · 26m
Pipelines That Actually Shut Down
Compose multi-stage channel pipelines with explicit cancellation and completion so downstream failure cannot strand upstream producers.
A pipeline is easy on a whiteboard: read, transform, write. The production version has cancellation, partial failure, slow downstreams, duplicate input, and shutdown deadlines. Most pipeline bugs are not data bugs. They are lifecycle bugs: one stage exits early, another keeps sending, and the program wedges with every channel technically 'working as designed.'
Each stage owns its output
A stage receives until input closes or cancellation fires, then closes the output it created:
func normalize(ctx context.Context, in <-chan Raw) <-chan Event {
out := make(chan Event)
go func() {
defer close(out)
for raw := range in {
event, ok := convert(raw)
if !ok { continue }
select {
case out <- event:
case <-ctx.Done():
return
}
}
}()
return out
}defer close(out) is the downstream completion signal. The send select is mandatory because the next stage may already have stopped listening.
Fan-out still needs one owner
Fan-out runs multiple copies of a stage over the same input. Fan-in merges their outputs and closes the merged channel only after every source finishes:
func fanOut(ctx context.Context, in <-chan Job, n int) <-chan Result {
outs := make([]<-chan Result, 0, n)
for i := 0; i < n; i++ {
outs = append(outs, process(ctx, in))
}
return merge(ctx, outs...)
}The closer inside merge is part of the pipeline, not an afterthought. If nobody owns it, receivers wait forever; if every producer owns it, somebody panics by closing twice.
Failure must travel upstream
Suppose the final writer returns a permanent error and exits. The previous stage blocks on send unless sends include cancellation. Give the pipeline a shared context through errgroup or a small supervisor; when downstream fails, cancellation wakes upstream sends.
Channels do not provide durability
Dropping a replayable finite stream during cancellation may be fine. Dropping payments, webhook events, or audit records is a business decision. Acknowledge work only after durable completion or design explicit replay. Pipeline elegance does not excuse data loss.
Field notes
- Do not close a channel passed into your stage; close only channels your stage created and owns.
- A producer blocking when the pipeline stops is correct. The bug is failing to cancel or drain it.
- Test cancellation with unbuffered channels; buffers can hide lifecycle defects until shutdown.
- Document ordering. If the pipeline does not preserve order, callers will eventually assume it does anyway.
Was this lesson helpful?