Production engineering workshop · 50 MIN
Go · Cancellation in a bounded worker pool
Cancellation must reach both work and blocked channel operations.
A fixed worker count bounds concurrent work. The caller owns job production; workers only consume jobs and publish results. One coordinator closes the result channel after every worker exits. Every potentially blocking channel operation selects on ctx.Done so a consumer that stops early does not strand goroutines. A buffer changes scheduling but cannot repair missing cancellation. This example computes squares; replace that operation with context-aware I/O in a service.
First reproduce the normal path. Then force a failure at each boundary and inspect what remains true.
Read the example
package main
import ("context"; "fmt"; "sync")
func Squares(ctx context.Context, jobs <-chan int, workers int) <-chan int {
if workers < 1 { panic("workers must be positive") }
out := make(chan int)
var wg sync.WaitGroup
wg.Add(workers)
for i := 0; i < workers; i++ {
go func() {
defer wg.Done()
for {
select {
case <-ctx.Done(): return
case n, ok := <-jobs:
if !ok { return }
select {
case out <- n*n:
case <-ctx.Done(): return
}
}
}
}()
}
go func() { wg.Wait(); close(out) }()
return out
}
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
jobs := make(chan int, 3)
for _, n := range []int{1,2,3} { jobs <- n }
close(jobs)
for value := range Squares(ctx, jobs, 2) { fmt.Println(value) }
}Check the expected output
Review the behavior in the stated project environment.
Your challenge
Create main.go in a Go module. Implement Squares, drain its results, then cancel after receiving one result. Add a test with an unbuffered input that never receives a job and cancel it. Run go test -race and verify workers exit. Output order is deliberately unspecified.
Solution cost: O(n) computation across w workers; scheduling and I/O dominate real services. time · O(w) goroutines plus channel buffers. space
Common trap
Closing out from a worker can race with another worker’s send. A buffer alone does not guarantee shutdown.
Study the project implementation
package main
import ("context"; "fmt"; "sync")
func Squares(ctx context.Context, jobs <-chan int, workers int) <-chan int {
if workers < 1 { panic("workers must be positive") }
out := make(chan int)
var wg sync.WaitGroup
wg.Add(workers)
for i := 0; i < workers; i++ {
go func() {
defer wg.Done()
for {
select {
case <-ctx.Done(): return
case n, ok := <-jobs:
if !ok { return }
select {
case out <- n*n:
case <-ctx.Done(): return
}
}
}
}()
}
go func() { wg.Wait(); close(out) }()
return out
}
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
jobs := make(chan int, 3)
for _, n := range []int{1,2,3} { jobs <- n }
close(jobs)
for value := range Squares(ctx, jobs, 2) { fmt.Println(value) }
}Further reading: Official documentation