0Pricing
Go Academy · Lesson

Fan-Out Fan-In

Distribute and collect work.

Fan-Out Fan-In is a free Go Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Fan-Out and Fan-In

Fan-out means starting several goroutines to read from one channel, distributing work. Fan-in means merging the outputs of several goroutines back into one channel.

  • Fan-out spreads load across workers
  • Fan-in consolidates results for the consumer

A Generator Stage

The pipeline starts with a generator: a function that returns a channel and feeds values into it from its own goroutine, then closes it.

func gen(nums ...int) <-chan int {
    out := make(chan int)
    go func() {
        for _, n := range nums {
            out <- n
        }
        close(out)
    }()
    return out
}

Fanning Out

To fan out, start multiple goroutines that all read from the same input channel. Each runs the same processing function and produces its own output channel.

in := gen(1, 2, 3, 4, 5)
c1 := square(in)
c2 := square(in)

A Processing Stage

The square stage reads from in, squares each value, and sends it to a new output channel. Multiple instances of this stage share one input.

func square(in <-chan int) <-chan int {
    out := make(chan int)
    go func() {
        for n := range in {
            out <- n * n
        }
        close(out)
    }()
    return out
}

Fanning In with merge

Fan-in merges several channels into one. A sync.WaitGroup tracks the per-channel goroutines, and a closer goroutine waits for all of them before closing the merged output.

func merge(cs ...<-chan int) <-chan int {
    out := make(chan int)
    var wg sync.WaitGroup
    for _, c := range cs {
        wg.Add(1)
        go func(c <-chan int) {
            for n := range c {
                out <- n
            }
            wg.Done()
        }(c)
    }
    go func() { wg.Wait(); close(out) }()
    return out
}

Why the WaitGroup

Each merging goroutine copies one input channel into out. We must not close out until every input is drained. The WaitGroup counts active copiers; the closer goroutine blocks on wg.Wait() until they finish.

Capturing the Loop Variable

In older Go, the closure must take c as a parameter so each goroutine binds its own channel, not the shared loop variable. Passing c explicitly avoids the classic loop-variable bug.

A Complete Fan-Out Fan-In

This program generates numbers, fans out to two square stages, then fans in and sums the merged results.

package main

import (
    "fmt"
    "sync"
)

func gen(nums ...int) <-chan int {
    out := make(chan int)
    go func() { for _, n := range nums { out <- n }; close(out) }()
    return out
}

func square(in <-chan int) <-chan int {
    out := make(chan int)
    go func() { for n := range in { out <- n * n }; close(out) }()
    return out
}

func merge(cs ...<-chan int) <-chan int {
    out := make(chan int)
    var wg sync.WaitGroup
    for _, c := range cs {
        wg.Add(1)
        go func(c <-chan int) { for n := range c { out <- n }; wg.Done() }(c)
    }
    go func() { wg.Wait(); close(out) }()
    return out
}

func main() {
    in := gen(1, 2, 3, 4, 5)
    c1 := square(in)
    c2 := square(in)
    total := 0
    for n := range merge(c1, c2) {
        total += n
    }
    fmt.Println("sum of squares:", total)
}

Order Is Not Guaranteed

Because two square stages race over the same input, the merged output order is nondeterministic. If you need ordering, attach an index to each item or use a single stage.

When to Fan Out

Fan out when a stage is the bottleneck and the work is parallelizable. If the upstream generator is slow, adding more downstream workers will not help, they will just starve.

Backpressure

Unbuffered channels create natural backpressure: a fast stage blocks when a slow consumer cannot keep up. This prevents unbounded memory growth across the pipeline.

Quick Check

Test your fan-in knowledge.

Recap

You learned fan-out and fan-in:

  • Fan-out: multiple goroutines read one channel
  • Fan-in: merge many channels into one via WaitGroup
  • Order is not preserved across parallel stages
  • Unbuffered channels provide backpressure

Frequently asked questions

Is the “Fan-Out Fan-In” lesson free?

Yes — the full text of “Fan-Out Fan-In” is free to read here on the web, and the Go Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Go Academy course, upgrade to CoddyKit PRO.

What will I learn in “Fan-Out Fan-In”?

Distribute and collect work. You practise Go Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Go Academy?

No prior experience is required. Go Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Fan-Out Fan-In” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Go Academy lesson?

Yes. Every Go Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Worker Pool Pattern
  2. Fan-Out Fan-In
  3. Pipeline Stages
  4. Graceful Shutdown
← Back to Go Academy