Level: AdvancedGo Lang

Go Pipeline Pattern: Fan-Out and Fan-In Explained

8 min read
Go Pipeline Pattern featured image: source stage, fan-out workers and fan-in merge

The Go pipeline pattern connects small steps with channels so data flows from one stage to the next. In this post, you will learn how stages work. You will also see how to split work across many goroutines and how to stop everything cleanly. Then we will build a three-part pipeline that squares numbers.

This lesson builds on Go channels with examples and Go context for beginners. We also use ideas from Go worker pool pattern and Go select statement. Because of that, a quick look at those posts will help.

What Is the Go Pipeline Pattern?

In short, a pipeline is a chain of stages. Each stage is a function that reads values from an input channel and does one job. After that, it sends the results to an output channel. Then the next stage picks them up.

Think of a car wash. First, the car is soaped. Next, it is rinsed. Finally, it is dried. Each station does one job, and several cars can be inside at the same time. Similarly, in the Go pipeline pattern, every stage works while the others work too.

Every stage follows the same shape. It takes <-chan int as input and returns <-chan int as output. As a result, you can plug stages together like building blocks. For example, you could add a filter stage between two others without touching the rest of the code.

Why the Go Pipeline Pattern Matters

A long function that does everything is hard to test and hard to speed up. Splitting it into stages is the main idea of the Go pipeline pattern. Fortunately, pipelines fix that problem. So here is what the Go pipeline pattern gives you.

  • Small stages: each function does one job, so it is easy to read and test.
  • Built-in concurrency: stages run in parallel without extra locks.
  • Easy scaling: you can run a slow stage in several goroutines.
  • Clean stopping: one context can cancel every stage at once.
  • Low memory use: values flow one by one, so you never hold the whole data set.

Because of this, pipelines suit file processing, image resizing, log parsing and data imports. For instance, a log tool can read lines, parse them and count errors in three stages. Meanwhile, each stage can use its own number of goroutines.

How the Go Pipeline Pattern Works

In the Go pipeline pattern, a source stage first creates the data and sends it into a channel. Next, middle stages read, change and forward the values. Finally, the last stage collects the results. When a stage has no more values, it closes its output channel. As a result, the next stage ends its range loop on its own.

Go Pipeline Pattern diagram showing a generator, three square workers and a merge stage
A generator stage feeds three square workers through one channel. A merge stage then joins their outputs into a single result channel.

Notice the two special words used in this pattern. First, fan-out means that several goroutines read from the same channel to share the work. Second, fan-in means that one function merges many channels into a single channel.

The Stage Rules

Good stages follow three simple rules, so the table below lists them.

RuleWhy it matters
The stage that creates a channel closes itReaders can stop with range
Stages read from <-chan and return <-chanTypes prevent wrong sends
Every send also listens to ctx.Done()Stages can stop early without leaking

If you follow these rules, your pipeline will not leak goroutines. Otherwise, a stuck sender may wait forever. In practice, this single habit prevents most pipeline bugs. Because the Go pipeline pattern depends on closing channels, always check who owns each one.

Why Order Can Change

With one worker, results keep their order. However, with several workers, whichever worker finishes first sends first. As a result, the output order can change. So sort the results at the end, or attach an index to each value.

Go Pipeline Pattern vs Worker Pool

Both patterns use goroutines and channels, but they solve different problems. For that reason, the table below compares them.

FeaturePipelineWorker pool
Main ideaMany different stages in a lineMany workers doing the same job
Data flowOutput of one stage feeds the nextJobs go in, results come out
Typical useRead, transform, then saveProcess a big queue of tasks
ScalingFan-out a slow stageAdd more workers
ComplexityMediumLow
Go Pipeline Pattern diagram comparing a pipeline with a worker pool
A pipeline passes data through different stages one after another, while a worker pool sends identical jobs to a group of equal workers.

So when should you use which? Use a pipeline when the work has clear steps. On the other hand, use a worker pool when every task is the same. In fact, you can combine them by fanning out one stage of a pipeline.

Go Pipeline Pattern Hands-On: Square Numbers

Now let’s build a real pipeline. It sends the numbers 1 to 8 through a generator, three square workers and a merge step. Because everything uses only the standard library, you can run it as it is. Also, every output below comes from a real run on Go 1.24.

Step 1: The Generator and Square Stages

First, gen is the source. It sends each number into a channel. However, it stops early if the context is cancelled.

func gen(ctx context.Context, nums ...int) <-chan int {
	out := make(chan int)
	go func() {
		defer close(out)
		for _, n := range nums {
			select {
			case out <- n:
			case <-ctx.Done():
				return
			}
		}
	}()
	return out
}

Next, square reads numbers, squares them and sends the results on.

func square(ctx context.Context, in <-chan int) <-chan int {
	out := make(chan int)
	go func() {
		defer close(out)
		for n := range in {
			select {
			case out <- n * n:
			case <-ctx.Done():
				return
			}
		}
	}()
	return out
}

Both stages use select with ctx.Done(). Because of this, a cancel call frees every goroutine, even if nobody is reading the output any more.

Step 2: The Fan-In Merge Function

Then merge joins many channels into one. It starts one goroutine per input. Also, it uses a WaitGroup to know when all inputs are finished.

func merge(ctx context.Context, chans ...<-chan int) <-chan int {
	out := make(chan int)
	var wg sync.WaitGroup
	wg.Add(len(chans))
	for _, c := range chans {
		go func() {
			defer wg.Done()
			for v := range c {
				select {
				case out <- v:
				case <-ctx.Done():
					return
				}
			}
		}()
	}
	go func() {
		wg.Wait()
		close(out)
	}()
	return out
}

The last goroutine waits for all workers and then closes out. In other words, the closing happens in exactly one place, which avoids a “close of closed channel” panic.

Step 3: Fan-Out and Run the Pipeline

Now we connect everything. Three square calls read from the same source, which is the fan-out step. After that, merge collects their results.

func main() {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	src := gen(ctx, 1, 2, 3, 4, 5, 6, 7, 8)

	w1 := square(ctx, src)
	w2 := square(ctx, src)
	w3 := square(ctx, src)

	var results []int
	for v := range merge(ctx, w1, w2, w3) {
		results = append(results, v)
	}
	sort.Ints(results) // order can change, so we sort
	fmt.Println("squares:", results)
}

Here is the real output. We sort the results first, because the three workers finish in a different order on each run.

squares: [1 4 9 16 25 36 49 64]

Step 4: Stop the Pipeline Early

Sometimes you only need the first few values. In that case, call cancel and every stage exits. Here, we read two values and then stop.

ctx2, cancel2 := context.WithCancel(context.Background())
count := 0
for v := range square(ctx2, gen(ctx2, 10, 20, 30, 40, 50)) {
	count++
	fmt.Println("got", v)
	if count == 2 {
		cancel2() // tell every stage to stop
		break
	}
}
fmt.Println("stopped early after", count, "values")

The output confirms that the pipeline stops without waiting for the rest. In other words, the cancel call works as intended.

got 100
got 400
stopped early after 2 values

Without the cancel call, the gen and square goroutines would stay blocked forever on a send. That is called a goroutine leak. You can also run go run -race . on this code, and the detector reports nothing. This means that the pipeline shares no memory in an unsafe way.

Common Mistakes with the Go Pipeline Pattern

  • Forgetting to close channels: the next stage then waits forever. So always use defer close(out) in the stage that owns the channel, as every Go pipeline pattern needs.
  • Ignoring cancellation: a send with no ctx.Done() case can block forever. Therefore, use select on every send.
  • Closing a channel from the receiver: this can cause a panic. Instead, let only the sender close it.
  • Expecting the same order: fan-out changes the order. So sort or add an index.
  • Too many goroutines for tiny work: the cost of switching can be bigger than the gain. Measure first.

Best Practices for the Go Pipeline Pattern

  • Keep each stage small, because small stages are easy to test alone.
  • Pass a context to every stage, so you can stop the whole chain in one call.
  • Fan out only the slow stage, since fast stages gain nothing.
  • Use buffered channels with care, because a large buffer can hide a slow stage.
  • Return errors through a second channel or a result struct, so failures do not vanish.
  • **Run go test -race**, since pipelines are concurrent by nature.

Practice Task

To practise the Go pipeline pattern, build a pipeline with three stages. The first reads lines from a slice. Next, the second converts them to upper case. Finally, a third stage counts the total characters. This gives you practice with every part of the pattern. Then fan out the upper-case stage to two workers.

Hint: reuse the merge function but change the type to string. Since Go 1.18 you can even make it generic with func merge[T any](...). Then compare the results with and without fan-out.

Official Resources

These pages describe pipelines, context and the concurrency tools used here.

Quick Recap

  • The Go pipeline pattern chains stages with channels.
  • Each stage reads from one channel and sends to another.
  • Fan-out means many goroutines read from one channel.
  • Fan-in means a merge function joins many channels into one.
  • Use context so that one cancel call stops every stage.
  • Sort the results when order matters, because fan-out changes it.

What’s Next?

By now, you can build flows of goroutines. However, a fast pipeline can also overload a service. So next, we will learn how to protect an API with rate limiting.

Next up: Go rate limiting with the token bucket