All articles
9 min read
November 28, 20269 min read

Go Concurrency Patterns: Building Resilient Worker Pools with Context Cancellation

Prevent goroutine leaks, handle burst traffic gracefully, and implement graceful shutdown using worker pools, buffered channels, and context propagation.

Tags:#Go#Concurrency#Goroutines#Backend
Go Concurrency Patterns: Building Resilient Worker Pools with Context Cancellation

Spawning an unbounded number of goroutines (go doWork()) is an anti-pattern that can quickly exhaust system memory and file descriptors during traffic spikes.

A robust Go service controls concurrency using Worker Pools paired with Context Cancellation.


1. Production Worker Pool Implementation

go
type Job struct {
	ID      string
	Payload []byte
}

type Result struct {
	JobID string
	Err   error
}

func Worker(ctx context.Context, id int, jobs <-chan Job, results chan<- Result) {
	for {
		select {
		case <-ctx.Done():
			return
		case job, ok := <-jobs:
			if !ok {
				return
			}
			err := processJob(ctx, job)
			results <- Result{JobID: job.ID, Err: err}
		}
	}
}

2. Graceful Shutdown & Drain

When a SIGTERM signal arrives, we close the job channel, allow workers to finish inflight operations, and wait using sync.WaitGroup:

go
func RunPool(ctx context.Context, numWorkers int, jobs []Job) []Result {
	jobsChan := make(chan Job, len(jobs))
	resultsChan := make(chan Result, len(jobs))
	var wg sync.WaitGroup

	for w := 1; w <= numWorkers; w++ {
		wg.Add(1)
		go func(id int) {
			defer wg.Done()
			Worker(ctx, id, jobsChan, resultsChan)
		}(w)
	}

	for _, j := range jobs {
		jobsChan <- j
	}
	close(jobsChan); // Signals workers to terminate when queue drains

	wg.Wait()
	close(resultsChan)

	var output []Result
	for r := range resultsChan {
		output = append(output, r)
	}
	return output
}