Thuta Learning
Go
AdvancedProgrammingBeginner

Mini Project: An Order-Processing Worker Pool

GoLesson 2645 min

What you'll walk away with

  • Build a worker pool end to end with a jobs channel and a results channel
  • Decide which goroutine sends on each channel and which one closes it
  • Close results safely with a WaitGroup and a closer goroutine
  • Carry errors inside results as values and classify them with errors.Is
  • Keep output stable by sorting, even though completion order varies

Explain it simply

A worker pool in plain language

Picture a restaurant kitchen. Order slips arrive on a rail (the jobs channel), and three cooks (worker goroutines) each grab the next slip whenever they are free. Finished plates go onto the pass (the results channel), where the waiter (main) collects them.

This pattern is the foundation of real systems such as background email senders, image resizers, order processors and queue workers. Use it when there is a lot of work but you want to limit how many goroutines do it at the same time.

Problem → Why → Solution

The problem: workers that never stop and output that keeps changing

Two problems show up in almost every first worker pool. First, forget close(jobs) and each worker's for range jobs waits forever for more data; if main is also ranging over results, the whole program stops with 'all goroutines are asleep - deadlock!'. Second, workers finish in their own time, so printing results in arrival order makes the output change on every run, which makes it impossible to test.

pool_bug.go
jobs := make(chan Order)
results := make(chan Result)
for w := 1; w <= 3; w++ {
    go worker(jobs, results)
}
go func() {
    for _, o := range orders {
        jobs <- o
    }
    // BUG: no close(jobs), so workers block forever in "for o := range jobs"
}()
for r := range results { // BUG: nobody ever closes results either
    fmt.Println(r) // and arrival order differs from run to run
}

Why ownership has to be decided first

A for range ch loop ends only when the channel is closed. Closing a channel announces 'nothing more is coming', so only the sender should do it. Three workers send on results, so if one worker closed it, the others would panic with 'send on closed channel'. That is why you decide each channel's owner before writing any code.

Core concept: the design, four parts and their owners

This project has four kinds of goroutine, each with one job. The producer sends the order slice into jobs and then calls close(jobs); it is the only sender on jobs, so it alone may close it. Three workers range over jobs, process each order and send one Result on results. When a worker sees jobs closed, its loop ends and it calls wg.Done().

Three goroutines send on results, so no single worker can close it. The answer is a closer goroutine: it waits for every worker with wg.Wait() and only then calls close(results). Main ranges over results and gathers everything into a slice; when results closes, the loop ends and main knows it has every result. Running the producer and the closer in their own goroutines keeps main from blocking on an unbuffered channel while it is also supposed to be receiving.

Writing directions in the signature, jobs <-chan Order (receive-only) and results chan<- Result (send-only), makes the compiler reject a worker that tries to send on or close jobs by mistake. When an order is invalid, the worker does not panic; it puts the error in Result.Err, so one bad order does not stop the pool. Finally main sorts by OrderID, so the output is identical whatever order the goroutines finish in.

ChannelSenders / receiversClosed by
jobsone producer / three workersthe producer, after the last order
resultsthree workers / mainthe closer, after wg.Wait() returns

How many workers to start depends on the bottleneck. In this example, process spends most of its time waiting on the payment service, so three workers finish five orders far sooner than one would. For pure CPU work, more workers than cores stops helping. Both channels are unbuffered, so the producer can hand over the next order only when a worker is free; that backpressure keeps work from piling up in memory. Adding a buffer smooths out short bursts, but the ownership rules stay the same.

text
Who sends, who closes
---------------------
producer --jobs--> worker 1 --+
  (closes jobs)    worker 2 --+--results--> main (collect, sort, print)
                   worker 3 --+
                                 ^
closer: wg.Wait() then close(results)
One channel, one owner
  1. Producer: send, then close jobs
  2. Workers: range jobs until closed
  3. Closer: Wait, then close results
  4. Main: collect, sort, print

Closing is the sender's job. With many senders, a third goroutine that waits for all of them does the closing.

General pattern

go
func worker(jobs <-chan Job, results chan<- Result, wg *sync.WaitGroup) {
    defer wg.Done()
    for j := range jobs { results <- handle(j) }
}

for range n { wg.Add(1); go worker(jobs, results, &wg) }
go func() { for _, j := range all { jobs <- j }; close(jobs) }()
go func() { wg.Wait(); close(results) }()
for r := range results { /* collect */ }

Start n workers, let the producer send and close jobs, let the closer close results after every worker is done, and range over results in main. Swap the Job and Result types and these four lines are reusable.

Worked example: three workers process five orders

Each order has an ID, a quantity and a unit price in cents. process sleeps for 10 ms as if calling a payment service, then computes the total. Order 2 has quantity 0, so it returns an error that wraps ErrEmptyOrder. Money is kept in integer cents rather than floats, so a sum like $34.44 comes out exact.

orders.go
package main

import (
    "errors"
    "fmt"
    "slices"
    "sync"
    "time"
)

type Order struct {
    ID        int
    Quantity  int
    UnitCents int
}

type Result struct {
    OrderID    int
    TotalCents int
    Err        error
}

var ErrEmptyOrder = errors.New("order has no items")

func process(o Order) (int, error) {
    if o.Quantity <= 0 {
        return 0, fmt.Errorf("order %d: %w", o.ID, ErrEmptyOrder)
    }
    time.Sleep(10 * time.Millisecond) // pretend to call a payment service
    return o.Quantity * o.UnitCents, nil
}

func worker(jobs <-chan Order, results chan<- Result, wg *sync.WaitGroup) {
    defer wg.Done()
    for o := range jobs {
        total, err := process(o)
        results <- Result{OrderID: o.ID, TotalCents: total, Err: err}
    }
}

func main() {
    orders := []Order{{1, 2, 450}, {2, 0, 300}, {3, 1, 1299}, {4, 5, 99}, {5, 3, 250}}

    jobs := make(chan Order)
    results := make(chan Result)
    var wg sync.WaitGroup
    for range 3 {
        wg.Add(1)
        go worker(jobs, results, &wg)
    }

    go func() { // producer: the only goroutine that sends on jobs
        for _, o := range orders {
            jobs <- o
        }
        close(jobs)
    }()
    go func() { // closer: results closes after every worker returns
        wg.Wait()
        close(results)
    }()

    var collected []Result
    for r := range results {
        collected = append(collected, r)
    }
    slices.SortFunc(collected, func(a, b Result) int { return a.OrderID - b.OrderID })

    revenue, empty := 0, 0
    for _, r := range collected {
        if errors.Is(r.Err, ErrEmptyOrder) {
            empty++
            fmt.Println("skipped:", r.Err)
            continue
        }
        revenue += r.TotalCents
        fmt.Printf("order %d: $%d.%02d\n", r.OrderID, r.TotalCents/100, r.TotalCents%100)
    }
    fmt.Printf("%d orders, %d empty, revenue $%d.%02d\n",
        len(collected), empty, revenue/100, revenue%100)
}

Code breakdown

  1. Direction in the signaturefunc worker(jobs <-chan Order, results chan<- Result, wg *sync.WaitGroup) {

    A worker can only receive from jobs and only send on results; trying to close jobs is a compile error. wg is passed as a pointer, because Done on a copy would never reach main's WaitGroup.

  2. Error as a valueresults <- Result{OrderID: o.ID, TotalCents: total, Err: err}

    Every order produces exactly one Result, success or failure. So main always gets five results for five orders and can see which ones failed.

  3. Producer closes jobsclose(jobs)

    Once every order is sent, the producer closes jobs. That is the signal that ends each worker's for range loop.

  4. Closer goroutinewg.Wait()

    The closer waits until all three workers have called Done, then closes results. Waiting directly in main would deadlock: workers would block sending on the unbuffered results channel because main is not reading yet.

  5. Stable outputslices.SortFunc(collected, func(a, b Result) int { return a.OrderID - b.OrderID })

    Results may arrive in a different order each run, but sorting by OrderID before printing keeps the output identical. errors.Is then finds ErrEmptyOrder inside the wrapped error.

You should see
order 1: $9.00
skipped: order 2: order has no items
order 3: $12.99
order 4: $4.95
order 5: $7.50
5 orders, 1 empty, revenue $34.44
The path of one order
  1. The producer sends the order on jobs
  2. A free worker takes it and processes it
  3. The worker sends a Result, possibly with Err, on results
  4. Main collects, sorts and prints

Quantity > 0

order N: $X.YY

Quantity = 0

skipped: order N: order has no items

Next step: timeouts and stopping early

If the payment service stops responding, workers can wait forever. Pass the context.Context from the context lesson to each worker and have it select on ctx.Done(), and a timeout or Ctrl+C can shut the whole pool down cleanly. The producer must also stop sending once ctx is done, or it will block on a jobs channel nobody reads any more.

go
func worker(ctx context.Context, jobs <-chan Order,
    results chan<- Result, wg *sync.WaitGroup) {
    defer wg.Done()
    for o := range jobs {
        total, err := process(o)
        select {
        case results <- Result{OrderID: o.ID, TotalCents: total, Err: err}:
        case <-ctx.Done():
            return // stop promptly when the caller gives up
        }
    }
}

In real projects

This pattern in real systems

A worker pool caps the number of goroutines, which protects limited resources such as database connections, API rate limits and CPU cores. Ten workers taking turns through a hundred thousand items are steadier and more predictable than a hundred thousand goroutines started at once.

  • Email and notification senders work through a queue with a few workers so they stay under the provider's rate limit.
  • Image or video processing is CPU-heavy, so the worker count is often set to around runtime.NumCPU().
  • Crawlers and health checkers test thousands of URLs through a pool and collect failures as error values in a report.
  • Batch import jobs push hundreds of thousands of CSV rows into a database through a few workers, collect bad rows with their row numbers, and show one report when the import ends.

Common mistakes

Common worker-pool mistakes

Closing results from inside a worker

If a worker decides 'I am done' and calls close(results), the remaining workers panic with 'send on closed channel' on their next send. A channel with many senders must be closed by a single closer goroutine that waits on the WaitGroup.

Hard-coding the number of results

Writing for r := 1; r <= 3; r++ { <-results } loses results or waits forever the day the number of orders changes. Skipping the result for failed orders breaks the count too. Close results and read it with range, and always send exactly one result per job.

Relying on completion order

Assuming worker 1 finishes order 1 first and comparing that output in a test gives a test that fails only sometimes. Sort by order ID or store results by index, and keep 'which worker did it' out of the output.

Best practices

Best practices

  • Before coding, write a comment naming each channel's sender, receiver and closer.
  • Always put channel directions in worker signatures.
  • Handle money as integer cents, not floats.
  • Run the pool at least once with go run -race or go test -race.

Mini challenge

Mini challenge: count words across documents

Count the words in a list of documents with two concurrent workers. This time, do not sort: put each document's index in its job and write the result straight into that slot of a pre-sized slice. A document that is empty or only spaces must produce ErrEmptyDoc.

  • The job struct carries an index and the text
  • Create counts := make([]count, len(docs)); each worker writes only counts[j.index]
  • Close jobs after sending, and read counts only after wg.Wait()
  • Print each document's result and the total word count
wordcount.go
package main

import (
    "errors"
    "fmt"
    "strings"
    "sync"
)

var ErrEmptyDoc = errors.New("document is empty")

type job struct {
    // TODO: index and text
}

type count struct {
    words int
    err   error
}

func countWords(text string) (int, error) {
    // TODO: ErrEmptyDoc for blank text, otherwise len(strings.Fields(text))
    return 0, nil
}

func main() {
    docs := []string{
        "Go makes concurrency explicit",
        "   ",
        "channels pass ownership of data between goroutines",
        "share memory by communicating",
    }
    // TODO: jobs channel, counts slice sized len(docs), WaitGroup
    // TODO: start 2 workers that fill counts[j.index]
    // TODO: send every doc with its index, close jobs, wait
    // TODO: print per-document results and the total
    _, _ = docs, strings.Fields
    var wg sync.WaitGroup
    wg.Wait()
    fmt.Println("total words:", 0)
}

Expected: Every run prints doc 0: 4 words, doc 1: document is empty, doc 2: 7 words, doc 3: 4 words and total words: 15, in that order.

Show hint

Goroutines writing different indexes of one slice is not a race, because they touch different memory. wg.Wait() guarantees main sees every write the workers made. jobs is unbuffered, but main can send on it directly because the workers are already receiving.

Show solution
wordcount.go
package main

import (
    "errors"
    "fmt"
    "strings"
    "sync"
)

var ErrEmptyDoc = errors.New("document is empty")

type job struct {
    index int
    text  string
}

type count struct {
    words int
    err   error
}

func countWords(text string) (int, error) {
    if strings.TrimSpace(text) == "" {
        return 0, ErrEmptyDoc
    }
    return len(strings.Fields(text)), nil
}

func main() {
    docs := []string{
        "Go makes concurrency explicit",
        "   ",
        "channels pass ownership of data between goroutines",
        "share memory by communicating",
    }

    jobs := make(chan job)
    counts := make([]count, len(docs)) // one slot per document
    var wg sync.WaitGroup

    for range 2 {
        wg.Add(1)
        go func() {
            defer wg.Done()
            for j := range jobs {
                n, err := countWords(j.text)
                counts[j.index] = count{words: n, err: err} // each index written once
            }
        }()
    }

    for i, d := range docs {
        jobs <- job{index: i, text: d}
    }
    close(jobs)
    wg.Wait()

    total := 0
    for i, c := range counts {
        if c.err != nil {
            fmt.Printf("doc %d: %v\n", i, c.err)
            continue
        }
        total += c.words
        fmt.Printf("doc %d: %d words\n", i, c.words)
    }
    fmt.Println("total words:", total)
}

Quick quiz 1 / 3

Three workers send on results. Who should close results?

Quick quiz 2 / 3

The producer forgets close(jobs) after sending every order. What happens?

Quick quiz 3 / 3

In the challenge solution, two workers write counts[j.index] without a lock. Why is that safe?

What to remember

  • A worker pool bounds concurrency with a jobs channel, n workers and a results channel.
  • The sender closes a channel; with many senders, a closer goroutine closes it after wg.Wait().
  • Send errors as values inside results, and always send exactly one result per job.
  • Make output stable by sorting by ID or by storing results at their index.

A Tour of Go — Go

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Mini Project: An Order-Processing Worker Pool | Thuta Learning