1. Why stopping is a separate task
When you first write a concurrent scheme, it seems simple: “we found an error in one place — we did return.” And then Go politely (as politely as Go can be) reminds you: return exits only from the current goroutine, while the others keep living their own lives. The problem is not that they live, but that they may keep waiting to read from or write to a channel — and your program will hang so quietly that it is almost embarrassing: no panic, no stack trace, just eternal waiting.
A typical “eternal waiting” scenario looks like this: the collector has already stopped reading results, a worker tries to do results <- r and blocks forever; the coordinator waits for wg.Wait(), but the worker will not finish because it is blocked on send; and main just stands there and looks at it philosophically. At that moment you begin to understand why concurrency is not “faster”, but “more complicated, but manageable”.
For stopping to be manageable, you need a protocol: an agreement on who tells whom and how that “everything, we are done”.
Stopping tools: close and context.Cancel
Right now we have two very different “stop signals”, and it is important not to confuse their roles. The first is closing a channel (close(ch)), which means: “there will be no more values”. The second is canceling the context (cancel()), which means: “the operation must stop as soon as possible”.
In context, the key mechanic is that ctx.Done() returns a signal channel that is closed on cancellation; and that is exactly why it is convenient to listen to it in select. This is not magic, but a direct contract of the context package: Done is a cancellation channel, and derived contexts (WithCancel, WithTimeout, etc.) give you a tree where canceling a parent cancels its children.
And closing a channel is not “kill everyone”, but specifically “sending is no longer allowed”. A closed channel is not a trash bin, but a sign that says “store closed”. And, as in real life, if you try to “close the store a second time”, there will be a scandal (panic: close of closed channel).
2. Channel ownership: who has the right to call close
The most common cause of panic in worker pools is the struggle for the right to close a channel. Just like a queue to a single microphone: everyone wants to announce “I am done”, and in the end the microphone falls.
Remember the rule that saves hours of life: the channel is closed by the one who writes to it. But in a worker pool there is a nuance: many workers write to results, and here “collective responsibility” appears, which in Go usually ends in panic. Therefore results is not closed by a worker, but by the coordinator — the only one who knows when all workers have definitely finished.
It is convenient to fix this in a small table (and then keep it in mind, like traffic rules):
| Channel | Who writes | Who closes | Why exactly this one |
|---|---|---|---|
|
producer | producer | it is the only source of tasks |
|
workers | coordinator | there are many workers; only one must close it after wg.Wait() |
If you feel like closing results from a worker, stop and ask yourself: “have all the other workers definitely stopped trying to write there?” If the answer is not “absolutely yes” — then you must not close it.
4. Cancel-on-error: guarantees and deadlock points
Cancel-on-error is not “everything disappears instantly on error”. It is more realistic: “on the first serious error we give a shared stop signal, and all goroutine instances commit to having an exit path and not blocking on channels”.
Two guarantees matter here.
First guarantee: the producer must not block on sending tasks if workers have already started shutting down. For this, the producer sends to jobs through select with ctx.Done().
Second guarantee: the worker must not block on sending a result if the collector has already “got tired and left”. For this, the worker sends to results also through select with ctx.Done().
That is exactly why people love ctx.Done(): it turns potentially endless waiting into “waiting, but with an emergency exit”. That is the practical value of context, the reason it exists at all.
Mini diagram: roles and stop signals
Before code, it is useful to see the whole system as a diagram once. This reduces the chance that you “fix” a deadlock in one place and accidentally create it in another (concurrency can be very vindictive).
flowchart LR
P[producer] -- jobs --> W1[worker 1]
P -- jobs --> W2[worker 2]
P -- jobs --> W3[worker 3]
W1 -- results --> C[collector]
W2 -- results --> C
W3 -- results --> C
K[coordinator] -->|wg.Wait| W1
K -->|wg.Wait| W2
K -->|wg.Wait| W3
K -->|"close(results)"| C
X["cancel()"] -->|"ctx.Done() is closed"| P
X -->|"ctx.Done()"| W1
X -->|"ctx.Done()"| W2
X -->|"ctx.Done()"| W3
There are exactly two weak spots here: the jobs and results arrows. If reading stops somewhere — someone will stop writing and will block. Cancel-on-error is needed so that instead of “block” we get “see Done and exit cleanly”.
5. Example: parallel task processing
To keep the examples from being “abstract workers that multiply by 2”, let us imagine a real useful operation in our task application: we have a batch of tasks, and we want to normalize titles before saving/output. For example, we forbid empty titles and remove extra spaces.
Let us make a function that takes []Task, processes them in parallel, and stops the others at the first error.
Let us start with models (short and boring — but it is the kind of boredom that saves you from chaos):
package main
import "strings"
type Task struct {
ID int
Title string
}
func normalizeTitle(s string) (string, error) {
t := strings.TrimSpace(s)
if t == "" {
return "", ErrEmptyTitle
}
return t, nil
}
Let ErrEmptyTitle be a sentinel so that it can be recognized with errors.Is (we already discussed this in the errors module, and it is really useful).
package main
import "errors"
var ErrEmptyTitle = errors.New("empty title")
6. Implementing cancel-on-error in code
Skeleton: context.WithCancel and the discipline of defer cancel()
Now — the basis of the protocol. We create a child context and a cancel, and immediately add defer cancel(). This is not “superstition”, but discipline: even on success we correctly release the resources associated with the context (timers/references, etc.).
package main
import (
"context"
)
func processBatch(parent context.Context, tasks []Task) ([]Task, error) {
ctx, cancel := context.WithCancel(parent)
defer cancel()
_ = ctx
_ = tasks
return nil, nil
}
Yes, this is just a draft for now. But an important point is already there: we have a single stop signal for the whole goroutine group.
Data types: job and result
Now let us introduce types for the queue and the result. This slightly increases the number of letters, but drastically reduces the number of “what is this int in this channel?” mistakes.
package main
type job struct {
Idx int
Task Task
}
type result struct {
Idx int
Task Task
Err error
}
Next we create two channels: jobs and results. And we immediately agree: jobs is closed by the producer (in our case, a separate goroutine), and results is closed by the coordinator after wg.Wait().
Worker: respect for ctx.Done() and two selects
The most slippery part of cancel-on-error is the worker. It can block in two places: when reading tasks and when sending the result. So both places need a select with ctx.Done().
package main
import (
"context"
"fmt"
"sync"
)
func worker(ctx context.Context, jobs <-chan job, results chan<- result, wg *sync.WaitGroup) {
defer wg.Done()
for {
select {
case <-ctx.Done():
return
case j, ok := <-jobs:
if !ok {
return
}
title, err := normalizeTitle(j.Task.Title)
if err != nil {
err = fmt.Errorf("task id=%d: %w", j.Task.ID, err)
}
r := result{Idx: j.Idx, Task: Task{ID: j.Task.ID, Title: title}, Err: err}
select {
case <-ctx.Done():
return
case results <- r:
}
}
}
}
Pay attention to error wrapping: fmt.Errorf("...: %w", err) makes the error part of the cause chain, and it can later be checked with errors.Is. It is like a label on a box: “broke while processing task 17”, but inside you can still see that the cause is ErrEmptyTitle.
Producer: sending tasks through select and defer close(jobs)
The producer is obliged to close jobs in any case: both on success and on cancellation. Therefore defer close(jobs) is literally part of the protocol.
package main
import "context"
func produce(ctx context.Context, jobs chan<- job, tasks []Task) {
defer close(jobs)
for i, t := range tasks {
select {
case <-ctx.Done():
return
case jobs <- job{Idx: i, Task: t}:
}
}
}
Here there is an important psychological point: the producer does not “have to send all tasks at any cost”. If the system is canceled — it stops sending. That is the point of cancel-on-error: we save time and resources.
Coordinator: wg.Wait() and closing results exactly once
The coordinator is the “person on duty for turning off the lights”. It does not calculate or validate anything; its job is boring: wait for wg.Wait() and close results. Boring tasks are the most important, because that is what prevents panics.
package main
import "sync"
func closeResultsWhenDone(results chan<- result, wg *sync.WaitGroup) {
wg.Wait()
close(results)
}
Yes, this is a tiny function. But it makes your closing protocol explicit and visually checkable.
Collector: first error, cancel(), and clean shutdown
The collector reads results and decides what to do. In a cancel-on-error strategy, the logic is usually this: find the first error — remember it, call cancel(), and then continue reading results until it is closed, so the scheme ends correctly.
Why keep reading? Because even with select in the worker, some results may “arrive” after cancellation (the worker could have sent them in time), and we want to finish the range results loop cleanly. This is not “always mandatory”, but it is a very stable habit.
package main
import (
"context"
"sync"
)
func processBatch(parent context.Context, tasks []Task) ([]Task, error) {
ctx, cancel := context.WithCancel(parent)
defer cancel()
jobs := make(chan job)
results := make(chan result)
var wg sync.WaitGroup
workers := 3
for i := 0; i < workers; i++ {
wg.Add(1)
go worker(ctx, jobs, results, &wg)
}
go produce(ctx, jobs, tasks)
go closeResultsWhenDone(results, &wg)
out := make([]Task, len(tasks))
var firstErr error
for r := range results {
if r.Err != nil && firstErr == nil {
firstErr = r.Err
cancel()
}
if r.Err == nil {
out[r.Idx] = r.Task
}
}
if firstErr != nil {
return nil, firstErr
}
return out, nil
}
There is an important engineering detail here: we do not “exit the range results immediately after cancel”. We wait until results is closed by the coordinator, that is, until all workers are done. This way we do not leave dangling goroutine instances.
7. Where the protocol is most often broken
In cancel-on-error, one of two places is usually broken.
The first is when the worker reads with for range jobs and sends results <- r without a select. In peaceful conditions this works. But with early stopping, the collector stops reading — and the worker blocks on send. This blockage “moves up”: wg.Wait() does not finish, results is not closed, main waits forever.
The second is when the producer does not listen to ctx.Done() and keeps trying to send tasks into jobs. But the workers have already exited, and the queue may stop being read. The producer blocks on jobs <- .... And then it is the same sad chain again.
Cancel-on-error does not work “by itself”. It works only if every potentially blocking operation (send/receive) has an emergency exit through ctx.Done().
Mental check: who owes what to whom
To make the protocol a system, not a set of tricks, it helps to keep three short obligations in your head, like in a lease agreement (only here the tenant is a goroutine).
- The producer promises to close jobs and stop sending tasks when the context is canceled.
- The worker promises to have an exit path and not block either on reading tasks or on sending results.
- The coordinator promises to close results exactly once and only after all workers have finished.
The collector promises not to do anything that leaves the system “half alive”. If it initiates stopping, it either keeps reading until results is closed, or it guarantees that workers cannot block on send (which is exactly what the select on send achieves).
8. Typical mistakes in cancel-on-error and channel closing
Mistake #1: closing results from a worker.
This almost always leads to panic: close of closed channel, because there are several workers, and “the first one who got there” closes the channel, while the next one tries to close it again or send a value into an already closed channel. results must be closed by the coordinator after wg.Wait().
Mistake #2: sending the result as results <- r without select with ctx.Done().
In the normal scenario this looks fine, but during early stopping the collector may stop reading, and the worker will block on send. The correct pattern is select { case results <- r: case <-ctx.Done(): return }, so that the worker has an emergency exit.
Mistake #3: reading tasks with for range jobs and ignoring context cancellation.
A range over a channel ends only when the channel is closed. If the producer for some reason blocks or does not close jobs, the worker will wait forever. For cancel-on-error, a clear loop with select is better, with a case <-ctx.Done(): return branch.
Mistake #4: the producer writes to jobs without select and does not react to cancellation.
If workers have started shutting down, the producer may hang on jobs <- .... In the end you get “cancel() was called, but the program still hung”. The producer must send tasks through select and have a case <-ctx.Done(): return branch.
Mistake #5: you canceled the context, but forgot the discipline of defer cancel().
If you create WithCancel but never call cancel(), strange effects begin to appear in the code: someone waits for a signal that never comes, or resources are held longer than necessary. The simple rule “created cancel — immediately defer cancel()” makes behavior predictable.
GO TO FULL VERSION