Task cancellation stops work that is no longer needed: a consumer may stop reading results, a deadline may expire, or a user may interrupt a command. In Go, context.Context is the idiomatic cancellation signal passed across package APIs and goroutines. Cancellation is cooperative: receiving a signal does not stop work automatically; each stage must observe it and return cleanly. section 7.2 section 7.2.1 section 7.8
Start with a root Context and derive a cancellable child with context.WithCancel or a deadline-bound child with context.WithTimeout. Contexts form a tree: cancellation flows from parent to children, while a child cannot cancel its parent. Always call the returned cancel function when finished, including when a timeout might fire, so associated resources can be released. section 7.2.2 section 7.2.2
Stopping a concurrent pipeline
Pass ctx as the first parameter. A producer can select between sending its next request and receiving from ctx.Done(). On cancellation, it returns and closes its output channel; downstream stages detect that closure and stop. Attach the same Context to cloned HTTP requests so in-flight requests can stop as well. Every stage that might block on a send should also select on cancellation, preventing goroutines from remaining stuck after an iterator exits early. section 7.2.3 section 7.2.4
Figure 7.3 Cancellation signals propagate through the hierarchy. Canceling the parent cancels both the parent and its children. The cross-out indicates the cancellation.
The cancellation tree shows the one-way propagation rule: canceling a parent cancels all descendants, but canceling a child leaves its ancestors running. section 7.2.2
Graceful Ctrl+C handling
signal.NotifyContext converts an operating-system interrupt into Context cancellation. Pass that Context into the client pipeline, defer the returned stop function, and let the iterator stop while the command still prints its accumulated summary. Returning ctx.Err() reports that execution ended through cancellation rather than silently discarding the cause. section 7.2.5
Use cancellation deliberately:
- Accept Context explicitly as the first parameter; do not store it in a struct. section 7.2.3
- Listen on Done, commonly in a select with useful work such as channel sends or receives. section 7.2.2
- Use Err to identify cancellation and Cause when a cancellable Context carries a specific reason. section 7.2.2




