TExcelTAD
Home › Go › Go Worker Pools

Go Worker Pools

Starting one goroutine per task is fine for a few hundred tasks. But for thousands of tasks that each open a file, hit a database or call an API, you want to limit how many run at once. A worker pool does exactly that: a fixed number of worker goroutines take tasks from a shared jobs channel and send answers to a results channel.

text
             ┌──────────┐
 jobs ──────►│ worker 1 │──────┐
   │         └──────────┘      │
   ├────────►│ worker 2 │──────┼──► results
   │         └──────────┘      │
   └────────►│ worker 3 │──────┘
             └──────────┘

The building blocks

Piece Role
jobs channel the queue of work; closed when all jobs are sent
N worker goroutines each loops for job := range jobs
results channel where workers deliver answers
sync.WaitGroup knows when every worker has finished, so results can be closed

A basic worker pool

Each job carries its own index, so results can be put back in the original order no matter which worker finished first.

go · try it yourself
package main

import (
	"fmt"
	"sync"
)

type Job struct {
	ID    int
	Input int
}

type Result struct {
	JobID  int
	Output int
}

func worker(jobs <-chan Job, results chan<- Result) {
	for j := range jobs {
		results <- Result{JobID: j.ID, Output: j.Input * j.Input}
	}
}

func main() {
	inputs := []int{2, 3, 5, 7, 11, 13, 17, 19}
	jobs := make(chan Job)
	results := make(chan Result)

	const numWorkers = 3
	var wg sync.WaitGroup
	for range numWorkers {
		wg.Go(func() { worker(jobs, results) })
	}

	// send all jobs, then close the queue
	go func() {
		for i, n := range inputs {
			jobs <- Job{ID: i, Input: n}
		}
		close(jobs)
	}()

	// close results once every worker has returned
	go func() {
		wg.Wait()
		close(results)
	}()

	// collect into the slot that matches each job ID
	squares := make([]int, len(inputs))
	for r := range results {
		squares[r.JobID] = r.Output
	}
	fmt.Println(squares)
}
[4 9 25 49 121 169 289 361]

Why the two helper goroutines? If main sent all jobs itself before reading results, workers could block sending to results while main blocks sending to jobs — a deadlock. Feeding jobs and closing results in their own goroutines keeps everything flowing.

Handling errors in workers

Real tasks fail. Put the error inside the result and decide afterwards what to do with it.

go · try it yourself
package main

import (
	"fmt"
	"strconv"
	"sync"
)

type Result struct {
	Index int
	Value int
	Err   error
}

func main() {
	lines := []string{"10", "20", "oops", "40", "5x"}
	jobs := make(chan int, len(lines)) // buffered: holds all job indexes
	results := make(chan Result, len(lines))

	var wg sync.WaitGroup
	for range 2 {
		wg.Go(func() {
			for i := range jobs {
				n, err := strconv.Atoi(lines[i])
				results <- Result{Index: i, Value: n, Err: err}
			}
		})
	}

	for i := range lines {
		jobs <- i
	}
	close(jobs)
	wg.Wait()
	close(results)

	ordered := make([]Result, len(lines))
	for r := range results {
		ordered[r.Index] = r
	}

	sum := 0
	for _, r := range ordered {
		if r.Err != nil {
			fmt.Printf("line %d: %v\n", r.Index+1, r.Err)
			continue
		}
		sum += r.Value
	}
	fmt.Println("sum of valid lines:", sum)
}
line 3: strconv.Atoi: parsing "oops": invalid syntax
line 5: strconv.Atoi: parsing "5x": invalid syntax
sum of valid lines: 70

With buffered channels big enough for every job and result, main can send everything, wait, and then read — no extra goroutines needed. That works when you know the number of jobs up front.

Counting work per worker

Which worker handles which job is decided by the scheduler, so it changes from run to run. Aggregate numbers, though, are stable — here every job is counted exactly once:

go · try it yourself
package main

import (
	"fmt"
	"sync"
)

func main() {
	const numWorkers = 4
	jobs := make(chan int, 100)
	perWorker := make([]int, numWorkers) // each worker owns one slot

	var wg sync.WaitGroup
	for w := range numWorkers {
		wg.Go(func() {
			for range jobs {
				perWorker[w]++
			}
		})
	}

	for i := range 100 {
		jobs <- i
	}
	close(jobs)
	wg.Wait()

	total := 0
	for _, n := range perWorker {
		total += n
	}
	fmt.Println("jobs processed:", total)
}
jobs processed: 100

Choosing the pool size

Work type Typical number of workers
CPU-bound (hashing, compression) runtime.NumCPU()
I/O-bound (HTTP calls, DB queries) more — 10, 50, 100 — limited by what the remote side tolerates
Rate-limited APIs whatever the API's limit allows

Tip: For "run these N tasks with at most K at a time and stop at the first error", the golang.org/x/sync/errgroup package with g.SetLimit(K) gives you a ready-made worker pool.

Test yourself

How does a worker know there are no more jobs?

  1. It counts them
  2. The jobs channel is closed, so its range loop ends
  3. It times out
  4. main kills it

Why include an index or ID in each job?

  1. Channels require it
  2. So results can be put back in the original order
  3. To make workers faster
  4. To avoid closing channels

When is it safe to close the results channel?

  1. Immediately after starting workers
  2. After all workers have finished sending (e.g. after wg.Wait())
  3. Before sending jobs
  4. Never