Coordinate concurrent work and cancellation

Build a Bounded Go Worker Pool That Cancels and Shuts Down Cleanly

Build a Go worker pool with a bounded queue, first-error cancellation, explicit shutdown, and lifecycle tests.

By Niko Minadze6 min read

Editorial illustration for Build a Bounded Go Worker Pool That Cancels and Shuts Down Cleanly

A worker pool needs two bounds: the number of handlers running at once and the number of jobs waiting to run. It also needs an answer to a less visible question: when a job fails or the caller cancels, who unblocks the producer and waits for every goroutine to exit?

The implementation below gives one producer ownership of the jobs channel. A fixed set of workers receives from it. On cancellation, queued jobs are abandoned, but handlers already running must return before Run does. A handler error recorded before cancellation is returned; otherwise, caller cancellation is returned. Cancellation is cooperative, so a handler must pass its context to cancellable calls or check it during its own work.

Pick the queue capacity separately from the worker count

An unbuffered jobs channel makes each send wait for a receiver. A buffered channel lets the producer get ahead by at most its capacity; when it fills, sending waits again. That finite queue can absorb a short burst, but it does not make the workers process jobs faster. Choose a capacity based on acceptable waiting and memory use, then measure the workload rather than treating a larger buffer as a general performance fix.

Several workers reading one channel are a form of fan-out, as described in the Go pipelines article. Its cancellation discussion highlights the shutdown hazard: if receivers stop, a goroutine sending to them can remain blocked. Here, the producer selects between sending and cancellation so that it has an exit path even when the queue is full.

Implement the pool

Put this in pool.go. workers limits concurrent handlers; queue limits waiting jobs. Only the producer closes jobs, and the WaitGroup joins both the producer and the workers before Run reads the recorded error or returns.

package pool

import (
    "context"
    "fmt"
    "sync"
)

type Job struct {
    ID int
}

type Handler func(context.Context, Job) error

func Run(callerCtx context.Context, jobsToRun []Job, workers, queue int, handle Handler) error {
    if workers < 1 || queue < 0 {
        return fmt.Errorf("workers must be positive and queue must be nonnegative")
    }
    if handle == nil {
        return fmt.Errorf("handler must not be nil")
    }

    ctx, cancel := context.WithCancel(callerCtx)
    defer cancel()

    jobs := make(chan Job, queue)
    var wg sync.WaitGroup
    var first sync.Once
    var firstErr error

    wg.Add(workers + 1)
    go func() {
        defer wg.Done()
        defer close(jobs)
        for _, job := range jobsToRun {
            if ctx.Err() != nil {
                return
            }
            select {
            case jobs <- job:
            case <-ctx.Done():
                return
            }
        }
    }()

    for i := 0; i < workers; i++ {
        go func() {
            defer wg.Done()
            for {
                if ctx.Err() != nil {
                    return
                }
                select {
                case <-ctx.Done():
                    return
                case job, ok := <-jobs:
                    if !ok || ctx.Err() != nil {
                        return
                    }
                    if err := handle(ctx, job); err != nil {
                        if ctx.Err() == nil {
                            first.Do(func() {
                                firstErr = err
                                cancel()
                            })
                        }
                        return
                    }
                }
            }
        }()
    }

    wg.Wait()
    if firstErr != nil {
        return firstErr
    }
    return callerCtx.Err()
}

The checks around select matter because, when cancellation and a channel operation are both ready, the code must not assume the cancellation case wins. A producer might enqueue a job at that boundary, but a worker checks cancellation before invoking its handler. Once cancellation is observed, the pool makes no promise to finish queued jobs.

sync.Once records one handler error and cancels the group. If caller cancellation has already been observed, an error returned by a handler is not recorded as a new job failure. If a job error was recorded first, Run returns it even if the caller subsequently cancels. A near-simultaneous job failure and caller cancellation is a race between those events, not a promise that one always wins.

The wait is unconditional. Closing the jobs channel signals that normal production is over; cancellation handles early exit. Neither substitutes for waiting while an in-flight handler finishes. This follows the same ownership principle used in the pipeline fan-in example: finish the goroutines that may use a channel before treating their work as complete.

Test completion, failure, and cancellation

Put this in pool_test.go. The cancellation test waits for the handler to start, then cancels while another job still needs an unbuffered handoff. Its timer is a watchdog, not a delay used to guess whether shutdown happened. Receiving a result proves Run completed its wait; the exited channel also makes the handler's return explicit.

package pool

import (
    "context"
    "errors"
    "testing"
    "time"
)

func TestRunSuccess(t *testing.T) {
    seen := make(chan int, 3)
    jobs := []Job{{ID: 1}, {ID: 2}, {ID: 3}}
    err := Run(context.Background(), jobs, 2, 1, func(_ context.Context, j Job) error {
        seen <- j.ID
        return nil
    })
    if err != nil {
        t.Fatal(err)
    }
    if len(seen) != len(jobs) {
        t.Fatalf("processed %d jobs, want %d", len(seen), len(jobs))
    }
}

func TestRunHandlerError(t *testing.T) {
    failure := errors.New("job failed")
    called := 0
    err := Run(context.Background(), []Job{{ID: 1}, {ID: 2}}, 1, 0,
        func(_ context.Context, _ Job) error {
            called++
            return failure
        })
    if !errors.Is(err, failure) {
        t.Fatalf("got %v, want job failure", err)
    }
    if called != 1 {
        t.Fatalf("called handler %d times, want 1", called)
    }
}

func TestRunCallerCancellation(t *testing.T) {
    ctx, cancel := context.WithCancel(context.Background())
    defer cancel()
    started := make(chan struct{})
    exited := make(chan struct{})
    result := make(chan error, 1)

    go func() {
        result <- Run(ctx, []Job{{ID: 1}, {ID: 2}}, 1, 0,
            func(ctx context.Context, _ Job) error {
                close(started)
                defer close(exited)
                <-ctx.Done()
                return ctx.Err()
            })
    }()

    select {
    case <-started:
    case <-time.After(2 * time.Second):
        t.Fatal("handler did not start")
    }
    cancel()
    select {
    case err := <-result:
        if !errors.Is(err, context.Canceled) {
            t.Fatalf("got %v, want caller cancellation", err)
        }
    case <-time.After(2 * time.Second):
        t.Fatal("Run did not return")
    }
    select {
    case <-exited:
    default:
        t.Fatal("Run returned before the handler exited")
    }
}

Run the tests with the race detector:

go test -race ./...

The tests check lifecycle and error behavior without claiming that a scheduler reaches a particular send instruction before cancellation. For a service using this pool, observe job latency, errors, and goroutine count under representative load. If jobs wait too long, investigate both handler time and worker capacity; if the producer must tolerate bursts, examine queue capacity. Those are different adjustments, and neither has a universal numeric default.

Comments

No comments yet.

Leave a comment

Your comment appears after approval. Plain text only; links stay as text. Line breaks and indentation are kept.

Up to 5,000 characters. No account or email needed.

All articles

Type at least two characters.

Press <kbd>Esc</kbd> to closeOpen the search page