Skip to main content

Parallel map in Go with errgroup

· 5 min read
Yaroslav Grebnov
Golang developer, SDET

The WaitGroup parallel map keeps every value and every item error. This interview exercise starts from a different contract: return all ordered values when every task succeeds, or return one error and no partial result slice.

golang.org/x/sync/errgroup adds error propagation and cooperative cancellation to the waiting behavior.

Task​

Initial task​

Implement a generic ParallelMapError that applies fn concurrently and returns ([]R, error). Preserve input order on success. Return nil and an error if any task fails.

Follow-up 1: bounded concurrency​

Limit the number of active tasks. Avoid creating one waiting goroutine for every input.

Follow-up 2: cancel sibling work​

Cancel the derived context when a task fails. Running tasks must receive that context so they can stop early.

Follow-up 3: panic isolation​

Convert a task panic into an error that follows the same all-or-nothing contract.

The code below is the final version after all follow-ups. It uses Go 1.25 and golang.org/x/sync/errgroup, as specified in the example module.

Solution​

package main

import (
"context"
"errors"
"fmt"
"runtime"

"golang.org/x/sync/errgroup"
)

func ParallelMapError[T, R any](
ctx context.Context,
items []T,
concurrency int,
fn func(context.Context, T) (R, error),
) ([]R, error) {
n := len(items)

if n == 0 {
return []R{}, nil
}

if concurrency <= 0 {
// NumCPU is a starting point for CPU work, not a universal I/O limit.
concurrency = runtime.NumCPU()
}
if concurrency > n {
concurrency = n
}

// Distinct indexed writes preserve order without a mutex. The slice costs O(n)
// memory; an unordered streaming API can avoid retaining every result.
results := make([]R, n)

g, gCtx := errgroup.WithContext(ctx)
// SetLimit bounds active goroutines. g.Go blocks while the limit is full, so a
// task that never returns can block both submission here and the later Wait.
g.SetLimit(concurrency)

for i := range n {
// Go 1.22+ gives each range iteration its own i. On older Go versions,
// `i := i` is required before this closure to avoid using the wrong slot.
g.Go(func() (err error) {
// errgroup does not recover panics. recover must run in this goroutine;
// the named return passes the converted panic error back to g.Wait.
defer func() {
if rErr := recover(); rErr != nil {
err = fmt.Errorf("execution panicked at index %d: %v", i, rErr)
}
}()

// The first observed task error cancels gCtx. Cancellation is cooperative:
// fn must check gCtx, and an uncooperative task can delay g.Wait indefinitely.
r, err := fn(gCtx, items[i])
if err != nil {
return err
}
results[i] = r
return nil
})
}

// Wait joins every started task and returns the first error observed by the
// group, not necessarily the error at the lowest input index. It also cancels
// gCtx on success, so the derived context must not escape this function.
if err := g.Wait(); err != nil {
return nil, err // discard partial values: this API is all-or-nothing
}

return results, nil
}

var ErrTest = errors.New("ErrTest")

// task simulates success, an ordinary error, and a panic for the demo.
func task(ctx context.Context, i int) (int, error) {
select {
case <-ctx.Done():
return 0, ctx.Err()
default:
}

if i == 2 {
return 0, ErrTest
}
if i == 3 {
panic("panic")
}

return i * i, nil
}

SetLimit differs from the semaphore in the WaitGroup implementation: g.Go waits for capacity before it creates the next goroutine. This bounds active goroutines but also means the submission loop can block.

The group returns the first error it observes in time. Concurrent completion is nondeterministic, so this is not necessarily the error belonging to the lowest input index. The WaitGroup version is the better contract when every item error must be retained.

Demo​

func demoParallelMapError() {
ctx := context.Background()
items := []int{1, 3, 4}
res, err := ParallelMapError(ctx, items, 3, task)
if err != nil {
fmt.Printf("ParallelMapError returned an error: %v\n", err)
return
}

fmt.Printf("ParallelMapError returned results:\n")
for i := range res {
fmt.Printf("index: %d, value: %d\n", i, res[i])
}
}

func main() {
demoParallelMapError()
}

Test​

The nominal test uses successful inputs and verifies ordered values. Error and cancellation behavior remain visible in the demo without expanding the interview test suite.

package main

import (
"context"
"reflect"
"testing"
)

func TestParallelMapError(t *testing.T) {
items := []int{1, 4, 5}
expected := []int{1, 16, 25}

actual, err := ParallelMapError(context.Background(), items, 3, task)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if !reflect.DeepEqual(actual, expected) {
t.Fatalf("expected %v, but got %v", expected, actual)
}
}

Run it with the race detector because tasks write the result slice concurrently:

$ go test -race -count=1 ./...
ok github.com/ygrebnov/test-concurrency6

Output example​

$ go run .
ParallelMapError returned an error: execution panicked at index 1: panic

Input value 3 is at index 1. Its panic becomes the group error, and the caller receives no values even if another task completed successfully.

The choice between the implementations is the API contract: collect every outcome with WaitGroup, or return ordered values only when every task succeeds with errgroup. The HTTP handler exercise applies the same bounded-concurrency idea to bursty request traffic.