Pipeline
A pipeline is a sequence of stages connected by channels. Each stage is a goroutine (or a pool) that receives values, transforms them, and sends them on. Closing the first channel should unwind the rest.
Detailed Explanation
Unix pipes (cmd | cmd) are the metaphor. In Go, stage one reads a source and sends records on chan Record. Stage two filters. Stage three writes. Each stage is a function func(in <-chan T) <-chan U that starts a goroutine and returns the output channel. The caller composes write(filter(read(ctx))).
Cancellation. Every stage should select on ctx.Done() as well as in. When the context is cancelled, the stage returns and closes out so the next stage unblocks. Without that, a blocked send on a full buffer keeps the whole chain alive after the user left.
Errors. Either send type result struct { val T; err error } through the pipe, or cancel the context on the first error and return the error from a supervisor (errgroup). Silent log.Print in a stage hides failure.
Backpressure. Unbuffered or small-buffer channels between stages stop a fast producer from running away. That is the pipeline doing its job.
What it costs. Each stage is a goroutine and a channel. For a handful of items, a straight-line function is clearer. Pipelines pay off when stages are I/O or when you insert fan-out in the middle. Do not build a framework; write three functions that return channels.
Code Examples
package main
import "context"
func gen(ctx context.Context, n int) <-chan int {
out := make(chan int)
go func() {
defer close(out)
for i := 0; i < n; i++ {
select {
case <-ctx.Done():
return
case out <- i:
}
}
}()
return out
}
func sq(ctx context.Context, in <-chan int) <-chan int {
out := make(chan int)
go func() {
defer close(out)
for v := range in {
select {
case <-ctx.Done():
return
case out <- v * v:
}
}
}()
return out
}
func main() {
ctx := context.Background()
for v := range sq(ctx, gen(ctx, 4)) {
_ = v
}
}Common Gotchas
Pass `ctx` into every stage
do not rely on closing `in` alone if a stage can block on something else.
Keep stage functions small and typed
`chan any` is a pipeline you cannot compile-check.
A stage that only ranges `in` and never watches `ctx` can block on send after ca
A stage that only ranges `in` and never watches `ctx` can block on send after cancel
Forgetting `close(out)` deadlocks the next `range`
Forgetting `close(out)` deadlocks the next `range`