Worker Pools, context & Cancellation
Definition
Worker pool
- In plain English
- A worker pool is a fixed number of goroutines that take jobs from a shared channel.
- Think of it like
- It is like a call centre with eight agents answering one queue of calls.
context
- In plain English
- A context carries a cancellation signal and an optional deadline that every goroutine in a piece of work can watch.
- Think of it like
- It is like a fire alarm that tells everyone in the building to stop and leave.
Why it exists
Generating audio for 10,000 cards should not start 10,000 simultaneous service calls. Eight reusable workers can process a bounded queue.
If the user cancels, workers should stop taking unnecessary work. The producer and any blocked result sends need an exit too.
How it works
Deadline
- In plain English
- A deadline is a point in time after which work should give up.
- Think of it like
- Like a shop's closing time.
Graceful shutdown
- In plain English
- Graceful shutdown means finishing or cleanly stopping in-progress work before exiting.
- Think of it like
- Like a restaurant serving seated guests but not seating new ones at closing time.
Jobs feeds three workers, each sending to Results; Cancel context signals all three workers.
package main
import (
"context"
"fmt"
"sync"
)
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
jobs, results := make(chan int, 12), make(chan int)
for i := 0; i < 12; i++ {
jobs <- i
}
close(jobs)
var wg sync.WaitGroup
for i := 0; i < 8; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for job := range jobs {
select {
case <-ctx.Done():
return
case results <- job:
}
}
}()
}
go func() { wg.Wait(); close(results) }()
for result := range results {
fmt.Println(result)
}
}
package main
import (
"context"
"fmt"
"time"
)
func geocode(ctx context.Context) error {
timer := time.NewTimer(100 * time.Millisecond)
defer timer.Stop()
select {
case <-ctx.Done():
return ctx.Err()
case <-timer.C:
return nil
}
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
defer cancel()
fmt.Println(geocode(ctx))
}
- Use ctx context.Context as the first parameter and pass it to calls that accept it.
- Immediately defer cancel() after creating a cancellable context.
- Check cancellation around job receives and result sends.
- Cancellation is cooperative; it cannot interrupt a function that ignores its context.
A ready result send may win select after cancellation. Real work should check ctx.Err before starting and pass context onward.
Examples
Reuse eight audio workers
Eight workers serve 10,000 cards. The demo uses twelve job numbers instead of speech requests.
package main
import (
"context"
"fmt"
"sync"
)
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
jobs, results := make(chan int, 12), make(chan int)
for i := 0; i < 12; i++ {
jobs <- i
}
close(jobs)
var wg sync.WaitGroup
for i := 0; i < 8; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for job := range jobs {
select {
case <-ctx.Done():
return
case results <- job:
}
}
}()
}
go func() { wg.Wait(); close(results) }()
for result := range results {
fmt.Println(result)
}
}
This demo preloads twelve job numbers. For 10,000 cards, stream through a bounded channel with a cancellation-aware producer.
The insight
A pool caps active work at a chosen size.
Retract an alert
A real alert might need 50,000 messages. This demo retracts after receiving the first result.
package main
import (
"context"
"fmt"
"sync"
)
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
jobs, results := make(chan int, 10), make(chan int)
for i := 0; i < 10; i++ {
jobs <- i
}
close(jobs)
var wg sync.WaitGroup
for i := 0; i < 3; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for job := range jobs {
select {
case <-ctx.Done():
return
case results <- job:
}
}
}()
}
go func() { wg.Wait(); close(results) }()
for result := range results {
fmt.Println(result)
cancel()
}
}
Output order and count can vary around cancellation. Real SMS calls must also accept context and bound their duration.
The insight
Shared context lets cancellation reach every worker.
Bound each address lookup
Each address lookup needs a two-second timeout. The demo shortens it to twenty milliseconds.
package main
import (
"context"
"fmt"
"time"
)
func geocode(ctx context.Context) error {
timer := time.NewTimer(100 * time.Millisecond)
defer timer.Stop()
select {
case <-ctx.Done():
return ctx.Err()
case <-timer.C:
return nil
}
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
defer cancel()
fmt.Println(geocode(ctx))
}
The slow operation itself watches ctx.Done. Giving only its caller a timeout would leave ignored work running.
The insight
Deadlines bound slow calls when those calls cooperate.
Trade-offs
Pros
- Bound active worker count.
- Propagate cancellation to related work.
Cons
- Pool size needs measurement.
- Every blocking path needs an exit.
Use when
- Many similar jobs share resources.
- Users may cancel long operations.
Avoid when
- A few independent tasks need only a WaitGroup.
- A sequential loop already meets the requirement.
Quick check
Takeaways
- A worker pool reuses a fixed number of goroutines.
- Context carries cancellation and deadlines, but stopping requires cooperation.
- Pass context first and defer cancel.