Skip to content
GDP for Noobs
☰ All patterns
ConcurrencyAdvanced

Fan-out / Fan-in

Split work across many goroutines, then merge the results into one channel.

01

Explain it like I'm new

Real-life analogy

A group project

The teacher hands chapters to several students (fan-out). Each writes a summary, and the team lead collects them into one report (fan-in).

😩 The problem

Fetching 5 pages one after another takes 5× as long. You want them in parallel, then a single stream of results.

💡 The pattern

Fan-out: start several workers reading from the same input channel. Fan-in: a merge function forwards every worker's output into one channel.

02

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 (
4 "fmt"
5 "sort"
6 "strings"
7 "sync"
8 "time"
9)
10
11// fetch pretends to download a page and returns its "size".
12func fetch(id int, urls <-chan string) <-chan string {
13 out := make(chan string)
14 go func() {
15 defer close(out)
16 for u := range urls {
17 time.Sleep(10 * time.Millisecond)
18 out <- fmt.Sprintf("%-22s %3d bytes", u, len(u)*42)
19 }
20 }()
21 return out
22}
23
24// merge = FAN-IN: combine many channels into one.
25func merge[T any](chans ...<-chan T) <-chan T {
26 out := make(chan T)
27 var wg sync.WaitGroup
28 for _, c := range chans {
29 wg.Add(1)
30 go func(c <-chan T) {
31 defer wg.Done()
32 for v := range c {
33 out <- v
34 }
35 }(c)
36 }
37 go func() { wg.Wait(); close(out) }()
38 return out
39}
40
41func main() {
42 urls := make(chan string)
43 go func() {
44 defer close(urls)
45 for _, u := range []string{"go.dev", "pkg.go.dev", "gobyexample.com", "github.com/golang", "go.dev/blog"} {
46 urls <- u
47 }
48 }()
49
50 // FAN-OUT: three fetchers all read from the SAME urls channel.
51 f1, f2, f3 := fetch(1, urls), fetch(2, urls), fetch(3, urls)
52
53 var lines []string
54 for line := range merge(f1, f2, f3) {
55 lines = append(lines, line)
56 }
57 sort.Strings(lines) // arrival order is random; sort for tidy output
58 fmt.Println(strings.Join(lines, "\n"))
59 fmt.Println("fetched", len(lines), "pages using 3 workers")
60}
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.

03

When should I use it?

✅ Reach for it when…

  • •Parallel I/O: API calls, DB queries, file reads, then aggregating results.

🚫 Skip it when…

  • •Results must stay in strict input order. You'd need to re-sort or index them.

🐹 Go tip

Results from a fan-in arrive in random order. Carry an index with each result if order matters.

🌍 You've already seen it in

Search backends querying many shards, and aggregators calling several microservices at once.

04

Quick check

One question. No pressure.

In merge, when is it safe to close `out`?

Related: Pipeline, Worker Pool