0Pricing
Go Academy · Lesson

Fan-in and Fan-out Patterns

Merging multiple channels and distributing work

Fan-in and Fan-out Patterns is a free Go Academy lesson on CoddyKit — lesson 3 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.

What is fan-out?

Fan-out distributes work from one channel across multiple goroutines, allowing parallel processing. Each worker receives from the same input channel.

Fan-out example

Spin up N workers all reading from a shared jobs channel:

func fanOut(jobs <-chan Job, n int) {
    for i := 0; i < n; i++ {
        go func() {
            for job := range jobs {
                process(job)
            }
        }()
    }
}

What is fan-in?

Fan-in merges multiple channels into one, so a single consumer can read results from many producers.

Fan-in with goroutines

Launch a goroutine per input channel; each goroutine forwards values to a shared output channel.

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

Fan-in with select

For a fixed number of input channels, a select loop is simpler than goroutines per channel.

func merge(a, b <-chan int) <-chan int {
    out := make(chan int)
    go func() {
        defer close(out)
        for a != nil || b != nil {
            select {
            case v, ok := <-a: if !ok { a = nil } else { out <- v }
            case v, ok := <-b: if !ok { b = nil } else { out <- v }
            }
        }
    }()
    return out
}

Pipeline stage

Combine fan-out and fan-in to build a pipeline stage: one input channel, N parallel workers, one merged output channel.

func parallelStage(in <-chan Work, n int) <-chan Result {
    outs := make([]<-chan Result, n)
    for i := 0; i < n; i++ {
        outs[i] = worker(in)
    }
    return fanIn(outs...)
}

Closing channels cleanly

The sender closes the channel; the receiver detects closure via the two-value receive form or by ranging. Never close from the receiver side.

for v := range in { // exits when in is closed
    process(v)
}

WaitGroup coordination

Use sync.WaitGroup to know when all fan-out workers are done, then close the output channel so downstream consumers can finish.

Back-pressure

Use buffered channels between pipeline stages to absorb bursts. Size the buffer based on the expected latency difference between producer and consumer.

out := make(chan Result, 100) // buffer absorbs bursts

Error propagation

Wrap results in a struct carrying both the value and an error, so errors flow through the pipeline alongside data without panicking.

type Result struct {
    Value int
    Err   error
}

Context cancellation

Pass a context through pipeline stages and check ctx.Done() in each stage so the entire pipeline stops when cancelled.

case <-ctx.Done():
    return ctx.Err()

Quick Check

In a fan-in pattern, what closes the merged output channel?

Recap: Fan-in and Fan-out

Key points:

  • Fan-out: multiple workers read from one channel
  • Fan-in: one goroutine per source merges into one output channel
  • WaitGroup coordinates closure of the merged channel
  • Use context for cancellation; buffered channels for back-pressure

Frequently asked questions

Is the “Fan-in and Fan-out Patterns” lesson free?

Yes — the full text of “Fan-in and Fan-out Patterns” 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-in and Fan-out Patterns”?

Merging multiple channels and distributing 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 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Fan-in and Fan-out Patterns” 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. The select Statement
  2. Timeouts and Tickers
  3. Fan-in and Fan-out Patterns
  4. Worker Pool Pattern
← Back to Go Academy