liveBook · Manning

Task cancellation

As explained in Go in Action, Second Edition

A cancellation signal is an indication that ongoing work should stop because it is no longer needed.

Task cancellation signals that ongoing work is no longer needed and should stop. In a Go service, a context carries that signal through the request call chain, allowing downstream goroutines, database operations, and HTTP calls to wind down instead of continuing after a client disconnects or deadline. section 1.4.3 section 1.4.2

Use cancellation to keep concurrent work bounded and responsive:

  • Create a context with a timeout when the operation has a known time budget. section 9.3
  • Pass contexts as values through function calls rather than embedding them in structs. section 9.3
  • Derive contexts for groups of concurrent operations so one error can cancel the remaining work. section 9.3
  • Call the cancel function when the operation ends, and use context for both cancellation and deadlines. section 9.3 section 9.6.1

Canceling concurrent feed fetches

A feed aggregator creates a 60-second context, passes it to each fetch, and derives an errgroup context. If one feed fetch fails, the derived context cancels the other requests; if the deadline expires, all downstream operations can return early. section 9.3

Figure 1.4 The life cycle of a single HTTP request

Trace cancellation from an HTTP client disconnect or deadline through the request goroutine and its downstream operations. section 1.4.3

How Go in Action, Second Edition covers it

How deep it goes
Explains propagation, timeouts, derived contexts, deferred cancellation, and errgroup coordination without detailing context internals.
Examples
Uses an HTTP request lifecycle and concurrent RSS feed fetching with a 60-second timeout and error-triggered cancellation.
What it assumes
Assumes goroutines and channels, while introducing context propagation, cancellation, deadlines, and coordinated concurrent shutdown.
What you can do after
Apply it via context.Context and errgroup to stop timed-out or failed concurrent operations and release downstream work.
How it connects
Connects cancellation to contexts, deadlines, goroutines, channels, HTTP requests, database operations, and error groups.

Also explained in

Compare how 5 books explain task cancellation →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Action, Second Edition. The section links point to the parts of the book it draws on.