Mahdi.Kh
November 23, 2026
We chain goroutines with channels into stages that work at the same time, and learn to cancel a pipeline, pass its errors along and size the buffers between its stages.
Say you have a folder of photos to publish. Each one has to be downloaded from wherever the user uploaded it, resized into a thumbnail, and uploaded to a CDN. The obvious code is a loop that does all three steps for one photo and then moves on to the next. It works, but look at where the time goes: while a photo is downloading, the CPU that could be resizing sits idle, and while it is being resized, the network sits idle. Every step waits for the other two.
A pipeline lets every step work at the same time, each on a different photo. In the previous part we learned to wait on several channels at once with the select statement; in this one we chain goroutines together with channels and build pipelines that stream their data, stop cleanly, report errors and leave no goroutine behind. If channels still feel new, the Channels post of the Golang basics series is a short read first.
A pipeline is a series of stages connected by channels. Each stage is a goroutine that does one job: it receives values from its inbound channel, does its work on each one, and sends the result on its outbound channel. The first stage has no inbound channel, because it produces the values itself (from a list, a file, a database query), and the last one is simply whoever reads the final channel, often main.
A car wash works the same way. One person soaps, the next rinses, the last dries. Three cars are being worked on at once, nobody needs to know how the others do their part, and the only thing that passes between them is the car.
In the diagram above each gopher is a stage. At this moment download has already moved on to owl.jpg, while resize works on dog.jpg and upload sends cat.jpg on its way. Two rules make this shape work:
<-chan T). The stage is then the only code that can send on it or close it.for range loop ends, it closes its own channel, and the close ripples down the line until the last loop ends. Nobody counts items and nobody sends a special "done" value.Here is the photo pipeline with the real work replaced by a 100 ms sleep per step:
What happens when it runs:
download, resize and upload all have the same shape: make a channel, start a goroutine that fills it, return the channel right away. The goroutine is what makes it a stage, and the returned channel is how you plug it into the next one.upload(resize(download(...))) wires the whole pipeline in one line. All three calls return immediately, and by the time main reaches its loop, the three goroutines are already running.main doesn't drive anything; it just ranges over urls. When download runs out of names it closes its channel, resize's loop ends and closes its channel, then upload's does, and finally main's loop ends.The output looks like this:
The first photo needs all three steps, so it comes out after 300 ms. After that a new one comes out every 100 ms, because every stage hands its photo over and immediately picks up the next. The whole batch takes about 600 ms, where the plain loop needs 1.2 seconds:
Your timings may be a few milliseconds higher (sleeps and the scheduler are not exact), but the order of the photos never changes. Each stage is one goroutine reading one channel in order, so what goes in first comes out first. Keep that in mind; in the next part it stops being true.
The timeline also shows what a pipeline does not do: cat.jpg still takes 300 ms from start to finish. A pipeline doesn't lower the latency of one item, it raises the throughput of the whole batch, because the steps overlap. And that throughput is set by the slowest stage: if resizing took 300 ms, a photo would come out every 300 ms no matter how fast the other two were.
The first version has two problems you would hit in real code. It can't be stopped: if main stops reading early (the user cancelled, a request timed out), the stages stay blocked on their sends forever. And errors have nowhere to go: what should happen when an upload fails?
The answer to both is a context. Every stage gets the same ctx, and every send becomes a select between delivering the value and ctx.Done(). When anything cancels the context, every stage that is waiting to send gives up, closes its channel and returns. For errors, context.WithCancelCause gives us a cancel function that takes an error: a stage that fails calls it, which cancels every other stage at once, and main reads the error back with context.Cause.
And since every stage has the same shape, we can write that shape once with generics and pass the actual work in as a plain function. Here is an order import: parse each line, add tax, save it to a database that loses its connection after three writes.
The interesting parts:
source and stage are written once. The work lives in parse, addTax and db.save, ordinary functions that know nothing about channels and are easy to test on their own. They take a ctx because real work (an HTTP call, a query) should be cancellable too.stage is a plain for range, with no select. It can't block forever: the stage before it either sends a value or, once the context is cancelled, returns and closes the channel. Only the sends need guarding, and that holds because every stage follows the same rule.save calls fail(err), which cancels ctx, and returns, which closes receipts and ends the loop in main. Meanwhile addTax and source, blocked on their sends, see ctx.Done() and return too. Orders 5 and 6 are never processed.context.Cause(ctx) is nil when everything went well and the error otherwise. defer fail(nil) plays the role of the usual defer cancel().The same wiring gives you timeouts and Ctrl+C for free: derive ctx from context.WithTimeout or signal.NotifyContext, and every stage stops when it fires. In real projects, golang.org/x/sync/errgroup packages the "first error cancels the rest and is returned at the end" part of this design; it is worth knowing, even though our examples stay within the standard library.
Stopping on the first error is the right default when a failure makes the whole batch pointless, like losing the database. When one bad item shouldn't stop the rest (a malformed line in a big file), don't cancel: send the error downstream inside the value, as a
struct{ order order; err error }, and let the last stage decide what to log, skip or retry.
Every channel so far was unbuffered, so every handoff is a meeting: the sender waits until the receiver is ready to take the value. That keeps the stages in lockstep. Would buffered channels be better?
A buffer helps when stages run at uneven speeds: one is fast for a while and then slow (a cache hit, then a miss), while the next does the opposite. The fast stage can run ahead and fill the buffer, and the slow one catches up later from what is waiting there. A buffer does not help when one stage is simply slower than the others. The buffer fills up, stays full, and the stage before it waits on every send exactly as before. This program measures both cases:
With uneven stages the buffer saves a third of the time. With one slow stage it changes nothing, because the slow stage sets the pace either way.
That waiting on a full buffer is backpressure, and it is a feature. A slow stage slows everything before it down to its own pace, so the pipeline never holds more than its buffers allow and its memory use stays flat however big the input is. Swapping the channel for a queue that grows without limit, so that "nothing ever blocks", only turns a slow stage into a memory leak: the queue grows until the process runs out of memory. Use small buffers to smooth out bumps, with a size you can explain. When one stage is simply too slow, give it more goroutines; that is exactly what the next part is about.
Walking away without cancelling. The classic pipeline leak: the consumer stops reading early (it found what it needed, or returned on an error), and every stage before it stays blocked on a send forever. Those goroutines, and everything they hold, are never freed. The program below runs the same small pipeline twice, without and with a context, and counts what is left behind:
In a long-running server this happens on every request, and the goroutine count only goes up. The fix is the rule from above: give every stage the context, guard every send with ctx.Done(), and defer cancel() where the pipeline is built, so leaving early cancels it.
Closing a channel you don't own. Only the stage that sends on a channel closes it. If a consumer closes its input to "stop the producer", the producer's next send panics with send on closed channel. To stop the stages upstream, cancel the context.
Forgetting to close. If a stage never closes its outbound channel, the next stage's for range waits forever. When that stage is main, the runtime stops the program with fatal error: all goroutines are asleep - deadlock!; in a server, it is just another silent leak. Writing defer close(out) as the first line of the goroutine makes it impossible to forget, even on an early return.
Touching a value after sending it. When you send a pointer, a slice or a map, the next stage gets the same memory and works on it at the same time. If the sender keeps modifying it, that is a data race. Treat a send as handing the value over: send a copy, or don't touch it again. Running your tests with -race catches this.
Stages that are too small. Every handoff costs a channel operation and often a goroutine switch, somewhere between tens and hundreds of nanoseconds. If a stage only trims a string, the pipeline is slower than a plain loop. Split the work where the steps wait on different things (the network, the disk, the CPU), not at every line of code.
A pipeline is a good fit when:
Choose something simpler when:
ctx.Done(); with context.WithCancelCause, errors stop the pipeline the same way.In the next part we take the slowest stage of a pipeline and spread its work over several goroutines: the fan-out/fan-in pattern.
Previous part: The select Statement | Concurrency in Go
Next part: Fan-Out/Fan-In Pattern | Concurrency in Go