Mahdi.Kh
November 23, 2026
We spread the slowest stage of a pipeline over several goroutines and merge their results back into one channel, then learn how to restore the order and choose how many workers to run.
Back to the photo pipeline from the previous part. Downloading and uploading take 50 ms a photo, but resizing takes 300 ms, so the whole pipeline produces one photo every 300 ms however fast the other stages are. We also saw that a bigger buffer doesn't help: it fills up and stays full. The resize stage simply needs more hands.
That is what fan-out/fan-in gives it. In the pipeline post every stage was one goroutine; here we run several copies of the slow stage side by side and join their results back into a single channel, so the rest of the pipeline doesn't even notice. Along the way we will see what happens to the order of the results, how to get it back when you need it, and how to choose the number of copies.
The pattern has two halves.
Fan-out: start several goroutines, the workers, that all receive from the same channel. A channel delivers each value to exactly one receiver, so the work is split between them with no extra code. The split also balances itself: whichever goroutine is free takes the next value, so one that is stuck on a big photo doesn't hold up the others, which a hand-written round-robin would.
Fan-in: each copy has its own output channel, and a function usually called merge joins them into one. It starts one goroutine per input that forwards everything to a shared output, counts them with a sync.WaitGroup, and starts one more goroutine whose only job is to wait for that count to reach zero and close the output.
A post office works this way: one queue, several counters, and whichever clerk is free calls "next". Customers leave through the same door no matter which counter served them, and they don't leave in the order they arrived.
In the diagram above, the first worker is still busy with photo 1, a big one, while photo 2 is already on its way to and photo 3 is right behind it. The workers keep pulling from as they become free, and the small gophers inside forward whatever arrives.
mainphotosmergeIf this reminds you of a worker pool, it should. A worker pool is a fan-out that lives as long as the program and takes jobs from anywhere; here the fan-out is just one stage of a pipeline, and it starts and ends with it.
Here are six photos of different sizes and a resize stage that takes 50 ms per megabyte, run as three copies:
Step by step:
resize is an ordinary stage, the same shape as in the pipeline post, plus a worker number so we can see who did what.resize three times with the same photos channel. That loop is the whole fan-out.merge calls wg.Add once for all inputs before it starts any goroutine, and each forwarder calls wg.Done when its input is closed. The closer goroutine waits and then closes out. It has to be a goroutine of its own: merge must return out right away so that somebody can start reading it.source closes photos, all three resize loops end and close their channels, the forwarders finish, the closer closes out, and the loop in main ends.One run printed this:
The batch took 300 ms, where a single resize goroutine would need 750 ms. Notice what happened to the order, though: cat.jpg went in first and came out fifth, because it is the biggest. Results come out in the order they finish, not the order they went in. Which worker takes which photo changes from run to run, and so does the order of photos that finish at the same moment. Worker 2 handled three photos because it kept being the first one free; that is the self-balancing at work.
The rules from the pipeline post still apply: every goroutine that sends gets the context and gives up when it is cancelled. With a fan-out that includes the forwarders inside merge, which would otherwise block forever on a send nobody will receive. In this version a deadline cuts the batch short: twelve photos, four workers, 100 ms per photo, but only 250 ms to do it all.
It also handles errors differently from the pipeline post. There, one failure stopped everything. Here a failed photo shouldn't cost us the other eleven, so each result carries its own err, and the consumer decides what to do with it.
The first two rounds of four finish at about 100 and 200 ms. At 250 ms the deadline fires in the middle of the third round: the work itself is a select against ctx.Done(), so each worker drops its photo at once instead of finishing a resize nobody will read. The forwarders in merge stop, the closer closes the output, and the last line confirms that no goroutine is left behind. The GIF failed on its own without disturbing anyone.
When one error should stop the whole fan-out, use context.WithCancelCause exactly as in the pipeline post. In real projects, golang.org/x/sync/errgroup with SetLimit(n) gives you a bounded fan-out, cancellation on the first error and a Wait that returns it, in a few lines.
Often the order doesn't matter: thumbnails can be uploaded in any order. Sometimes it does: the lines of a file, the rows of a report, the frames of a video. The trick is to number every value before the fan-out and carry that number through the workers. After the merge you have two options.
If you need all the results before doing anything anyway, the simplest option is a slice: results[item.index] = item.value, written by the one goroutine that reads the merged channel, so there is no race. If you want results to keep streaming, put a small reorder stage after the merge that remembers values arriving early and sends each one as soon as everything before it has gone out:
In the picture, 0 and 1 have already gone out and next is 2. Value 3 arrived early, so it waits in pending; as soon as 2 arrives, both leave, one after the other. Here it is in code, translating the lines of a short story on three workers:
The indented lines are printed by the workers as they finish, in whatever order that happens; the story itself always comes out in order. Line 1 finished first but waited until line 0, a long one, was done, and then both came out together.
Ordering has a cost. While one slow item holds up the line, everything behind it piles up in pending, and nothing reaches the consumer. If the first item is a huge one, the map can grow large and you lose much of what the fan-out bought you. Restore the order only when the consumer really needs it.
It depends on what the workers spend their time on. This program runs the same 16 jobs on 1, 2, 4 and 8 goroutines, once with work that only computes and once with work that only waits:
On the code runner of this page, which has two CPUs, it prints something like this (your numbers will differ, the shape won't):
CPU-bound work stops getting faster at the number of CPUs. Past that point the extra goroutines just take turns on the same cores. A good starting point is runtime.GOMAXPROCS(0), the number of goroutines Go will run in parallel.
I/O-bound work (network calls, disk, a database) keeps getting faster well beyond that, because a goroutine waiting on I/O uses no CPU at all. The limit is on the other side: the size of the database's connection pool, an API's rate limit, open files, the memory each item in flight takes. Choose a number from that limit, measure, and make it configurable rather than hard-coded.
What you should not do is start one goroutine per item for input of unknown size. That is a fan-out with no limit at all, and a million items means a million goroutines hitting your database at once. Later posts on semaphores and rate limiters show other ways to put a ceiling on concurrency.
Waiting in the wrong place. This version of merge looks reasonable, and deadlocks:
The forwarders block on out <- v because nobody reads out, and nobody can read it because merge hasn't returned it yet: it is waiting for the forwarders. Moving wg.Wait() and close(out) into their own goroutine breaks the circle.
Every worker closing the shared channel. Some code skips merge and lets all the workers send on one shared channel. That works, but then no worker may close it: the first one to finish would close it while the others are still sending, and the next send panics with send on closed channel. Close a shared channel exactly once, after wg.Wait(), in one place.
Calling wg.Add inside the goroutine. If each forwarder calls wg.Add(1) as its first line, the closer can run wg.Wait() before any of them has started, see a count of zero and close the output too early. Call Add before the go statement. (Newer Go versions add WaitGroup.Go, which does both for you.)
Fanning out a stage that remembers. A stage that keeps state across items, such as a running total, a set of IDs it has already seen or the previous line, gives wrong answers when it is copied N times, and races if the copies share that state. Keep such a stage single, or split the work so that the same key always goes to the same worker.
Fan-out/fan-in fits when:
Look elsewhere when:
go, a WaitGroup and results[i] = ... is simpler, with no channels at all.merge: a forwarder per input, a WaitGroup, and a separate goroutine that waits and closes the output.In the next part we turn the idea around: instead of giving each value to one of many receivers, we give each message to all of them, with the pub/sub pattern.
Previous part: Pipeline Pattern | Concurrency in Go
Next part: Pub/Sub Pattern | Concurrency in Go