Nov 23, 20267 min read

Build a Worker Pool in Go

How to bound concurrent work in a Go backend with a worker pool, why launching one goroutine per item can exhaust memory and file descriptors, a generic pool that reports one result per input, cancellation with context, panic recovery, and running a bounded fan-out in an Encore endpoint.

Illustration for Build a Worker Pool in Go

Goroutines are cheap, but the work inside them usually is not. Ten goroutines calling a shipping API is fine, and ten thousand, one per unprocessed row, can exhaust file descriptors, memory or that API's rate limit before the first response comes back.

A worker pool keeps a fixed number of goroutines and feeds them jobs through a channel. This guide builds one that reports a result for every input, stops when cancelled and survives a panic in a worker.

When is a pool better than errgroup?

errgroup.Group with SetLimit is the right tool when you have a handful of tasks and the first error should cancel the rest, for example fetching three required records for one request. A pool is a better fit when:

  • The list is large, and even waiting goroutines would use too much memory or stack.
  • Every input needs a result, including failures, so the caller can retry only the ones that failed.
  • The work talks to a third-party API or a database with a concurrency cap of its own.

Unlike a job queue, a pool lives for one batch, usually one request, and goes away when that batch is done. Work that has to survive process restarts belongs in a database or a Pub/Sub subscription.

How do you structure the pool?

The pool below is generic over the input and result types. The feeder sends indexes into a buffered results slice, so the output stays in input order without a lock on every write, and sync.WaitGroup.Go, added in Go 1.25, starts each worker:

// pool/pool.go package pool import ( "context" "fmt" "sync" ) type Result[T, R any] struct { Input T Value R Err error } // Run processes inputs with at most workers goroutines and returns one result per input. // It stops handing out new work when ctx is cancelled. func Run[T, R any](ctx context.Context, workers int, inputs []T, fn func(context.Context, T) (R, error)) []Result[T, R] { workers = max(1, min(workers, len(inputs))) jobs := make(chan int) results := make([]Result[T, R], len(inputs)) var wg sync.WaitGroup for range workers { wg.Go(func() { for i := range jobs { results[i] = call(ctx, inputs[i], fn) } }) } feed: for i := range inputs { select { case jobs <- i: case <-ctx.Done(): for j := i; j < len(inputs); j++ { results[j] = Result[T, R]{Input: inputs[j], Err: ctx.Err()} } break feed } } close(jobs) wg.Wait() return results } // call runs fn and turns a panic into an error, since a panic in a worker would crash the process. func call[T, R any](ctx context.Context, in T, fn func(context.Context, T) (R, error)) (res Result[T, R]) { res.Input = in defer func() { if p := recover(); p != nil { res.Err = fmt.Errorf("panic: %v", p) } }() res.Value, res.Err = fn(ctx, in) return res }

The WaitGroup.Go docs state that f must not panic, and an unrecovered panic in any goroutine exits the process, so the recovery has to be inside the worker. Jobs already in a worker keep running after cancel, unless fn itself checks ctx, which it should for any I/O. The feeder marks remaining jobs cancelled and returns, so the caller sees a complete slice with a mixture of results and ctx.Err().

The first line clamps workers between one and the number of inputs, since zero workers would leave the feeder blocked on its first send and more workers than inputs would only start goroutines with nothing to do.

How many workers should you start?

The number is a property of the work, not of the CPU count:

Kind of workStarting point
CPU-bound, no I/Oruntime.GOMAXPROCS(0)
Outbound HTTP to one hostThe concurrency the API or your client can take, often 10 to 50
Database queriesWell below max_connections, shared with the rest of the process
Mixed or unknownStart small, measure p99 and errors, then raise

A pool of 200 workers against a connection pool of 20 queues 180 of them on the pool's mutex. Size the workers to the scarce resource, which is usually the other system, not your Go process.

How do you use the pool in an Encore service?

Encore

Encore is a backend framework with built-in infrastructure, and a worker pool is ordinary Go inside an endpoint. The endpoint below fans out quote requests to several carriers with a cap of four in flight, records each result, and returns them together, with the HTTP client timeouts from the companion guide on the shared client.

Application code passes through Encore and infrastructure guardrails to resources provisioned in your own AWS or GCP account.

Set up the app

Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

~
$ encore app create shipping-api --example=hello-world$ cd shipping-api && mkdir quotes

The quotes endpoint fans out over the pool:

// quotes/quotes.go package quotes import ( "context" "encoding/json" "fmt" "io" "net/http" "net/url" "time" "encore.app/pool" "encore.dev/beta/errs" "encore.dev/rlog" ) var client = &http.Client{Timeout: 4 * time.Second} type Carrier struct { Name string BaseURL string } var carriers = []Carrier{ {Name: "north", BaseURL: "https://north.example/v1/quote"}, {Name: "south", BaseURL: "https://south.example/v1/quote"}, {Name: "east", BaseURL: "https://east.example/v1/quote"}, {Name: "west", BaseURL: "https://west.example/v1/quote"}, {Name: "central", BaseURL: "https://central.example/v1/quote"}, } type QuoteParams struct { Zip string `query:"zip"` } type Quote struct { Carrier string `json:"carrier"` PriceCents int64 `json:"price_cents,omitempty"` Error string `json:"error,omitempty"` } type QuoteResponse struct { Quotes []Quote `json:"quotes"` } //encore:api public method=GET path=/quotes func GetQuotes(ctx context.Context, p *QuoteParams) (*QuoteResponse, error) { if len(p.Zip) < 3 || len(p.Zip) > 10 { return nil, errs.B().Code(errs.InvalidArgument).Msg("invalid zip").Err() } results := pool.Run(ctx, 4, carriers, func(ctx context.Context, c Carrier) (int64, error) { return fetch(ctx, c, p.Zip) }) out := make([]Quote, len(results)) ok := 0 for i, r := range results { out[i].Carrier = r.Input.Name if r.Err != nil { rlog.Warn("carrier quote failed", "carrier", r.Input.Name, "err", r.Err) out[i].Error = "unavailable" continue } out[i].PriceCents = r.Value ok++ } if ok == 0 { return nil, errs.B().Code(errs.Unavailable).Msg("no carrier responded").Err() } return &QuoteResponse{Quotes: out}, nil } func fetch(ctx context.Context, c Carrier, zip string) (int64, error) { req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.BaseURL+"?zip="+url.QueryEscape(zip), nil) if err != nil { return 0, err } resp, err := client.Do(req) if err != nil { return 0, err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { io.Copy(io.Discard, io.LimitReader(resp.Body, 64<<10)) return 0, fmt.Errorf("status %d", resp.StatusCode) } var body struct { PriceCents int64 `json:"price_cents"` } if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&body); err != nil { return 0, err } return body.PriceCents, nil }

Four workers for five carriers means at most four outbound calls at once, and a cancelled request, for example a client that hung up, stops the fifth from starting. Failed carriers stay in the response so the frontend can show a partial list, and the endpoint only errors when none of them answered. encore run starts the service locally, and each request to the endpoint appears in the development dashboard's traces with its total duration, which shows whether the slowest carrier sets the response time.

When the work should continue after the request returns, publish each job to a topic and process it in a subscription with MaxConcurrency set, which is the same bound, persisted and retried. An agent adding a sixth carrier appends it to the carriers slice and tests the endpoint locally, with the pool already capping how many run at once.

Best fit: Backends that fan out to several APIs or records in one request and want a hard cap on how many of those calls run at once, with a result for every input.

Go worker pool checklist

  • Bound the workers to the scarce resource, usually the other system, not GOMAXPROCS.
  • Return one result per input, including failures and cancelled jobs.
  • Stop handing out work when the context is cancelled, and have fn check it too.
  • Recover panics in the worker and turn them into errors.
  • Share one HTTP client or database pool across workers.
  • Use a topic and a subscription, not an in-process pool, for work that must outlive the request.

Frequently asked questions

What is a worker pool in Go?

A worker pool is a fixed number of goroutines that take jobs from a channel, so the number of running tasks is bounded. Unlike launching a goroutine per item, the pool caps CPU, memory and open connections no matter how long the input list is.

When should I use a worker pool instead of errgroup?

Use errgroup.SetLimit when you have a small list and the first error should cancel the rest. Use a worker pool when you need one result, success or failure, for every input, or when the list is large enough that one goroutine per item would cost too much even if they wait to start.

How do I cancel a Go worker pool?

Pass a context and stop sending new jobs when it is cancelled, then close the jobs channel and Wait for the workers to finish their current job. Work already in a worker is not cancelled unless that worker also checks the context.

What happens if a worker goroutine panics?

An unrecovered panic in a worker exits the process, and WaitGroup.Go from Go 1.25 does not recover it. Catch the panic in the worker, turn it into an error on that job, and keep the rest of the pool running.

When should a worker pool run in an Encore service?

Use a worker pool inside a service when many tasks share a process and need a cap on concurrency, such as CPU-bound work or a limited dependency. For work that should run as a separate consumer, declare a Pub/Sub subscription in the service and let Encore provision the queue in your own AWS or GCP account.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders