System Design Academy

Saving…

Lesson 9 of 10 in Module 40 of 45 lessons complete

Worker Pools, context & Cancellation

Module 4, lesson 9Concept12 min

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.

A fixed team shares jobs and cancellation.

Jobs feeds three workers, each sending to Results; Cancel context signals all three workers.

After: a small fixed batch demonstrates cancellable workers and result sends.
Go
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)
	}
}
After: a 20-millisecond timeout bounds a simulated slow geocoding call.
Go
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.

After: a small fixed batch demonstrates cancellable workers and result sends.
Go
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.

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

The user cancels an export of 50,000 rows. What should stop the workers?
After ctx, cancel := context.WithTimeout(...), what must you always do?

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.

Try the quick check above whenever you feel ready.

Previous: Deadlocks