Skip to content
GDP for Noobs
☰ All patterns
ConcurrencyIntermediate

Pipeline

Chain stages with channels so data flows through like an assembly line.

01

Explain it like I'm new

Real-life analogy

A car assembly line

One station fits the wheels, the next paints, the next inspects. All stations work at the same time on different cars, and each car flows down the line.

😩 The problem

Reading, transforming and filtering a big stream in one loop means each step waits for the others, and the code becomes a tangled blob.

πŸ’‘ The pattern

Each stage is a function that takes an input channel and returns an output channel, running its own goroutine. Stages connect like LEGO bricks.

02

Play with it

An interactive model of the pattern. Click around, nothing can break.

generate→
square→
atLeast(10)β†’
main: for range

πŸ’‘ Watch several numbers sit in different stages at the same time. Every stage is its own goroutine, connected by channels.

03

Walk through the code

Click a step to highlight its lines. This is a complete program you can copy and run.

main.go
1package main
2
3import "fmt"
4
5// Each stage: takes a channel in, returns a channel out, runs in its own goroutine.
6
7// Stage 1: turn a list of numbers into a stream.
8func generate(nums ...int) <-chan int {
9 out := make(chan int)
10 go func() {
11 defer close(out) // always close when you're done sending
12 for _, n := range nums {
13 out <- n
14 }
15 }()
16 return out
17}
18
19// Stage 2: square every number.
20func square(in <-chan int) <-chan int {
21 out := make(chan int)
22 go func() {
23 defer close(out)
24 for n := range in {
25 out <- n * n
26 }
27 }()
28 return out
29}
30
31// Stage 3: only let big numbers through.
32func atLeast(min int, in <-chan int) <-chan int {
33 out := make(chan int)
34 go func() {
35 defer close(out)
36 for n := range in {
37 if n >= min {
38 out <- n
39 }
40 }
41 }()
42 return out
43}
44
45func main() {
46 // Connect the stages like LEGO bricks: generate -> square -> atLeast.
47 for v := range atLeast(10, square(generate(1, 2, 3, 4, 5, 6))) {
48 fmt.Println("got", v)
49 }
50 fmt.Println("pipeline drained, all goroutines finished")
51}
terminal
Press β–Ά Run to execute this program.

This output was captured by running the program with Go 1.24. Copy it into your editor or the Go Playground and try changing things.

04

When should I use it?

βœ… Reach for it when…

  • β€’ETL jobs, log processing, streaming transforms, image processing chains.

🚫 Skip it when…

  • β€’Each stage is trivially cheap. Channel overhead may outweigh the benefit.

🐹 Go tip

Pass a context.Context into every stage and select on ctx.Done() so the whole pipeline can be cancelled.

🌍 You've already seen it in

io.Pipe and Unix-style data processing tools, plus streaming ETL in Go data platforms.

05

Quick check

One question. No pressure.

Who should close a stage's output channel?

Related: Fan-out / Fan-in, Worker Pool, Iterator