1. Why do we need a worker pool
When you first learn about goroutine, the brain makes a natural conclusion: «Great! Then one goroutine per task». It is like the moment when someone first learned about infinite pasta: you want to check whether it is really infinite. The problem is that infinity usually ends at the word memory.
If there are few tasks (for example, 10–100), the «one goroutine per task» approach often really works and looks nice. But if there are many tasks (thousands, hundreds of thousands), you suddenly create a huge army of goroutine that:
- first, has overhead costs (small, but not zero);
- second, is harder to shut down correctly (especially if there are result channels);
- third, you lose control: «how many tasks are currently running at the same time» becomes a matter of faith.
Worker pool solves this: we create a fixed number of workers (for example, 4, 8, 16), which take tasks from a shared queue and process them. It is roughly like checkout lanes in a supermarket: there may be many customers, but the number of cashiers is finite, and the queue regulates the load.
2. Roles and the worker pool protocol
Before writing code, it is important not to jump into make(chan ...) headfirst, but to agree on the roles. In a worker pool it is usually convenient to think in terms of several «characters»: someone puts tasks into the queue, someone takes them, someone closes the output, someone collects the final result.
Below is a mini-schema to fix the picture in your mind (we will come back to it when we connect everything into one program):
flowchart LR
P[Producer<br/>creates tasks] -->|jobs channel| W1[Worker 1]
P -->|jobs channel| W2[Worker 2]
P -->|jobs channel| WN[Worker N]
W1 -->|results channel| C[Collector<br/>collects results]
W2 -->|results channel| C
WN -->|results channel| C
The most important rule, which saves you from half of the panics and deadlocks:
The channel is closed by the one who writes to it (the sender owner), and it is closed exactly once.
And if there are many writers (many workers write to results), then the closing is done by a separate entity (the coordinator), which does not write results, but only waits for the workers to finish and then closes the channel. This rule helps avoid the classic panic: close of closed channel.
About close, it is useful to keep the basic meaning in mind: closing a channel means «no more values will be sent». There is no «data deletion magic» there: values sent earlier can still be read.
3. Preparing an example: Task, Job and Result
So that the examples are not the abstract «job #123», let us continue in the style of a fictional task-list application. Imagine that we have Task, and we want to calculate statistics for titles: for example, the number of words in Title. The task is intentionally simple: we do not need a file system, HTTP, or databases — only concurrent processing.
Task model
package main
type Task struct {
ID int
Title string
Done bool
}
TaskJob and TaskResult types
Let us define what a «job» and what a «result» are. Important: we introduce separate types not because Go forces us to, but because of readability. A chan int channel without a name is a mystery. A chan TaskJob channel is already almost documentation.
package main
type TaskJob struct {
Task Task
}
type TaskResult struct {
TaskID int
WordCount int
Err error
}
Note: TaskResult contains Err error. Today we will not build a complex error strategy, but it is already useful to get used to the fact that the result of work can be «success or error», and it is convenient to pass that in a single object.
Error ErrEmptyTitle
package main
import "errors"
var ErrEmptyTitle = errors.New("empty title")
4. Basic versions without a worker pool
Any concurrency becomes clearer if you first see the ordinary sequential version. And then — what channels and goroutine turn it into.
Sequential version
package main
import (
"fmt"
"strings"
)
func wordCount(title string) int {
return len(strings.Fields(title))
}
func main() {
tasks := []Task{
{ID: 1, Title: "buy milk"},
{ID: 2, Title: "write go code"},
}
for _, t := range tasks {
fmt.Println(t.ID, wordCount(t.Title)) // 1 2; 2 3 (order is stable)
}
}
The sequential version gives a stable order, simplicity, and minimal details. But if the processing is heavy (for example, parsing, hashing, validating a large import), the sequence can be slow. And then the desire to parallelize appears.
Naive concurrency: one goroutine per task
Now let us write the naive version: start a goroutine for each Task. It looks nice... right up until the moment when there are «many» tasks.
package main
import (
"fmt"
"strings"
"sync"
)
func main() {
tasks := []Task{{ID: 1, Title: "buy milk"}, {ID: 2, Title: "write go code"}}
var wg sync.WaitGroup
for _, t := range tasks {
wg.Add(1)
go func(task Task) {
defer wg.Done()
n := len(strings.Fields(task.Title))
fmt.Println(task.ID, n)
}(t)
}
wg.Wait()
}
Here an important newbie bump appears: we pass t as the argument task Task, so as not to fall into the loop-variable trap. You have seen this before: even in Go 1.22+ there are scenarios where you can accidentally share one variable across iterations, if it is declared in the wrong place.
But that is not the main problem. The problem is that if tasks grows to, say, 200_000, you will create 200_000 goroutine. They may be lightweight, but not light enough to celebrate that like a holiday. Worker pool makes this construction manageable.
5. Worker pool implementation: code step by step
Now we will assemble the key elements: the worker, the task queue, the coordinator that closes results, the producer and the collector, and then — main, which connects everything.
Worker: reads from jobs and writes to results
The key element is the worker. It must take tasks from jobs until the channel is closed. This fits perfectly with for range, because range over a channel ends when the channel is closed and all values have been read.
Pay attention to the signature: jobs <-chan TaskJob (read only), results chan<- TaskResult (write only). Directional channels are a small but very useful «brain safety belt»: the function cannot accidentally close someone else’s channel or read where it should not.
package main
import (
"strings"
"sync"
)
func worker(jobs <-chan TaskJob, results chan<- TaskResult, wg *sync.WaitGroup) {
defer wg.Done()
for j := range jobs {
title := j.Task.Title
if title == "" {
results <- TaskResult{TaskID: j.Task.ID, Err: ErrEmptyTitle}
continue
}
n := len(strings.Fields(title))
results <- TaskResult{TaskID: j.Task.ID, WordCount: n}
}
}
Important: the worker does not close results. It is not the «owner of the results channel», because there are many workers. If every worker tries to close results, there will be a race of «who closes first», and the others will panic.
Starting the pool: create N workers and a WaitGroup
A worker pool starts with a queue, but technically it is more convenient to write the worker launcher first.
package main
import "sync"
func startPool(n int, jobs <-chan TaskJob, results chan<- TaskResult) *sync.WaitGroup {
var wg sync.WaitGroup
for i := 0; i < n; i++ {
wg.Add(1)
go worker(jobs, results, &wg)
}
return &wg
}
Pay attention to WaitGroup discipline: Add(1) is done before starting the goroutine. This is not bureaucracy — it is a way to avoid a rare but very unpleasant race, where the goroutine managed to finish and call Done(), while the counter had not yet been incremented.
Coordinator: close results after the workers finish
Collector reads for r := range results { ... }. For the loop to finish, the results channel must be closed. But it can only be closed «when the time is right» by the one who knows that all workers have finished.
That is the role of the coordinator: wait for wg.Wait() and after that do close(results).
package main
func closeResultsWhenDone(wg *sync.WaitGroup, results chan<- TaskResult) {
go func() {
wg.Wait()
close(results)
}()
}
Why close results in a separate goroutine? Because if you call wg.Wait() directly in main, you may block too early and not have time, for example, to start reading results. In simple examples this is not always critical, but as a habit it is very useful: «the coordinator lives separately and performs the closing when the work is done».
Producer: send tasks and close jobs
The producer puts tasks into the queue. The ownership rule applies here: since the producer writes to jobs, the producer also closes jobs.
package main
func produceTasks(tasks []Task, jobs chan<- TaskJob) {
defer close(jobs)
for _, t := range tasks {
jobs <- TaskJob{Task: t}
}
}
defer close(jobs) is a good technique: even if you later add an early return or error handling, the chance of forgetting to close the channel is much lower.
Collector: read results until close and aggregate
The collector reads results and does something useful with them: prints them, stores them in a slice, builds a report.
Let us make a simple collection: print to the screen and count how many errors there were.
package main
import "fmt"
func collect(results <-chan TaskResult) int {
errCount := 0
for r := range results {
if r.Err != nil {
fmt.Println("error:", r.TaskID, r.Err) // error: 3 empty title
errCount++
continue
}
fmt.Println("ok:", r.TaskID, r.WordCount)
}
return errCount
}
Here it is important to accept the fact emotionally: the order of results is not guaranteed. Worker #2 may process task #10 faster than worker #1 processes task #1. If you need a stable order, that is solved separately (usually by sorting or placing the result by index), but that is already the next layer of logic.
Putting everything together in main
main does five things:
- creates channels,
- starts workers,
- starts the coordinator that closes results,
- starts the producer,
- reads the results.
package main
import "fmt"
func main() {
tasks := []Task{
{ID: 1, Title: "buy milk"},
{ID: 2, Title: "write go code"},
{ID: 3, Title: ""},
}
jobs := make(chan TaskJob)
results := make(chan TaskResult)
wg := startPool(2, jobs, results)
closeResultsWhenDone(wg, results)
go produceTasks(tasks, jobs)
errCount := collect(results)
fmt.Println("errors:", errCount) // errors: 1
}
Pay attention to several points that together give us a «no-deadlock scheme»:
- produceTasks is started in a goroutine so that main does not stop on task sending and can start collecting results in parallel.
- jobs is closed by the producer, and the workers finish naturally: for range jobs ends.
- results is closed by the coordinator, which waited for all workers.
- the collector reads results through range, and the loop ends automatically after the channel is closed.
That is the worker pool «protocol»: nobody waits for a «magic number of results», nobody closes channels «by eye», termination follows from the contract.
Why the scheme does not hang
When a beginner first sees a worker pool, they usually think: «There are a lot of blocking points here: channels, waits, goroutines... why does it not hang?» The calm answer is this: every blocking place has a guaranteed «unblocker».
- The producer may block on jobs <- ..., but the workers read jobs and drain the queue.
- A worker may block on results <- ..., but the collector reads results.
- The collector may «wait forever», but the coordinator closes results when the workers have finished.
- The workers may «wait forever» while reading jobs, but the producer closes jobs.
So termination is not based on a timer or luck, but logically follows from channel closes and WaitGroup.
6. Typical mistakes when working with a worker pool
Mistake #1: forgot to close jobs.
Then the workers will remain forever in for range jobs, because range over a channel ends only after close(jobs). And since the workers did not finish, the coordinator will not close results, and the collector will also wait forever. Usually this looks like «the program does nothing and does not terminate», and you start suspecting that the computer is offended.
Mistake #2: close results inside the worker.
This is almost a guaranteed panic: close of closed channel, because there are several workers, and each one thinks it is the boss. If channel closing depends on the completion of several goroutines, it is not closed by «any participant», but by the coordinator after wg.Wait().
Mistake #3: do wg.Add(1) after go worker(...).
Sometimes it «works», and sometimes you get a panic like sync: negative WaitGroup counter or strange hangs. The reason is that the goroutine may have managed to call Done() before you have done Add(1). The discipline is simple: Add is always before starting the goroutine.
Mistake #4: the collector does not read with range results, but «exactly N times».
Such code is fragile: you change the number of tasks, add an early return in the producer, add filtering — and suddenly you either under-read results or wait for extra ones. Reading with range over results is tied to the real completion protocol, not to assumptions.
Mistake #5: expect results to come in the same order as the tasks.
In a worker pool, execution order is not deterministic. If you need order, you must restore it explicitly: for example, store the results by TaskID in a slice/map and then output them in the required order. The important thing is not to «fight» concurrency by expecting a stable order, but to treat order as a separate formatting task.
GO TO FULL VERSION