WaitGroup.Go and errgroup

suggest change

Wait for goroutines to finish shows the classic sync.WaitGroup pattern with Add and Done. This article covers newer and higher-level tools for running a group of goroutines:

wg.Go

Before Go 1.25, starting a goroutine tracked by a WaitGroup took three steps: wg.Add(1) before go, then defer wg.Done() inside the goroutine. Forgetting either one, or putting Add in the wrong place, is a bug.

wg.Go(f) does all three for you:

package main

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

func main() {
	words := []string{"go", "rust", "zig", "odin"}
	upper := make([]string, len(words))

	var wg sync.WaitGroup
	for i, w := range words {
		wg.Go(func() {
			upper[i] = strings.ToUpper(w)
		})
	}
	wg.Wait()
	fmt.Println(upper)
}
[GO RUST ZIG ODIN]

wg.Go increments the counter in the calling goroutine, starts f in a new goroutine and decrements the counter when f returns. f takes no arguments and returns nothing. You pass data to it by capturing variables in the closure. Since Go 1.22 every loop iteration has its own i and w, so capturing them is safe (see Closures).

A WaitGroup can be reused after Wait returns. A goroutine started with Go can itself call wg.Go to add more work, because the counter is not zero while it runs.

The bug wg.Go prevents: Add inside the goroutine

This code looks fine, and when you run it, it usually prints the right result:

package main

import (
	"fmt"
	"sync"
)

func main() {
	var wg sync.WaitGroup
	results := make([]int, 5)
	for i := range 5 {
		go func() {
			wg.Add(1) // BUG: races with wg.Wait
			defer wg.Done()
			results[i] = i * i
		}()
	}
	wg.Wait()
	fmt.Println(results)
}
[0 1 4 9 16]

go func() only schedules the goroutine. It can start running much later. If main reaches wg.Wait() before any goroutine has called wg.Add(1), the counter is still 0, Wait returns right away, and main prints a partly filled slice (or exits before the work is done). It's a race that shows up under load, on a different machine, or once in a thousand test runs.

The rule: Add must be called by the goroutine that starts the new goroutine, before the go statement. wg.Go follows this rule by design.

Since Go 1.25 go vet includes a waitgroup analyzer that catches this mistake:

$ go vet ./...
ex2\main.go:13:10: WaitGroup.Add called from inside new goroutine

Run go vet in CI. It catches this and many other bugs that compile fine.

Upgrading old code with go fix

Go 1.27's go fix has a waitgroupgo fixer that rewrites the wg.Add(1) / go func() { defer wg.Done() ... }() pattern to wg.Go. Given this code:

	var wg sync.WaitGroup
	results := make([]int, 5)
	for i := range 5 {
		wg.Add(1)
		go func() {
			defer wg.Done()
			results[i] = square(i)
		}()
	}
	wg.Wait()

go fix -diff shows what would change without changing any files:

$ go fix -diff ./...
@@ -11,11 +11,9 @@
 	var wg sync.WaitGroup
 	results := make([]int, 5)
 	for i := range 5 {
-		wg.Add(1)
-		go func() {
-			defer wg.Done()
+		wg.Go(func() {
 			results[i] = square(i)
-		}()
+		})
 	}
 	wg.Wait()
 	fmt.Println(results)

go fix ./... applies the changes. It runs all fixers by default. To run only this one, use go fix -waitgroupgo ./.... The fix is applied only when the go line in go.mod is 1.25 or later, since older Go versions don't have wg.Go.

Collecting results without data races

Goroutines return nothing, so results must be written somewhere shared. There are three race-free ways to do it.

package main

import (
	"fmt"
	"sync"
)

func main() {
	words := []string{"a", "bb", "a", "ccc", "bb", "a"}

	// 1. Each goroutine writes its own slice element: no lock needed.
	lengths := make([]int, len(words))
	var wg sync.WaitGroup
	for i, w := range words {
		wg.Go(func() { lengths[i] = len(w) })
	}
	wg.Wait()
	fmt.Println("lengths:", lengths)

	// 2. Shared map: protect it with a mutex.
	var mu sync.Mutex
	counts := map[string]int{}
	for _, w := range words {
		wg.Go(func() {
			mu.Lock()
			defer mu.Unlock()
			counts[w]++
		})
	}
	wg.Wait()
	fmt.Println("counts:", counts)

	// 3. Channel: close it after all senders are done.
	ch := make(chan int)
	var senders sync.WaitGroup
	for _, w := range words {
		senders.Go(func() { ch <- len(w) })
	}
	go func() {
		senders.Wait()
		close(ch)
	}()
	total := 0
	for n := range ch {
		total += n
	}
	fmt.Println("total:", total)
}
lengths: [1 2 1 3 2 1]
counts: map[a:3 bb:2 ccc:1]
total: 10
  1. Preallocated slice, one element per goroutine. Different elements of a slice are different memory locations, so goroutines can write them at the same time. The writes are visible after wg.Wait() returns. This is the simplest and fastest option and it keeps results in input order.
  2. Mutex around a shared map or counter. Maps are not safe for concurrent writes, and append to a shared slice isn't either. See Mutex.
  3. Channel. Useful when the consumer should process results as they arrive. Note the extra goroutine that waits and then closes the channel. If main called senders.Wait() itself before reading, it would deadlock, because senders block on the unbuffered channel until someone reads.

Use go test -race or go run -race to verify. See Detecting races.

errgroup: goroutines that return errors

sync.WaitGroup doesn't know about errors. The package golang.org/x/sync/errgroup is a WaitGroup for functions that return error. It's maintained by the Go team but lives outside the standard library, so add it to your module:

$ go get golang.org/x/sync/errgroup

g.Go(f) runs f func() error in a new goroutine. g.Wait() waits for all of them and returns the first non-nil error:

package main

import (
	"errors"
	"fmt"
	"time"

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

var errNotFound = errors.New("not found")

var prices = map[string]int{"apple": 120, "pear": 90, "plum": 150}

// lookupPrice pretends to be a slow network call.
func lookupPrice(item string) (int, error) {
	time.Sleep(10 * time.Millisecond)
	p, ok := prices[item]
	if !ok {
		return 0, fmt.Errorf("price of %q: %w", item, errNotFound)
	}
	return p, nil
}

func totalPrice(items []string) (int, error) {
	results := make([]int, len(items))
	var g errgroup.Group
	for i, item := range items {
		g.Go(func() error {
			p, err := lookupPrice(item)
			if err != nil {
				return err
			}
			results[i] = p
			return nil
		})
	}
	if err := g.Wait(); err != nil {
		return 0, err
	}
	total := 0
	for _, p := range results {
		total += p
	}
	return total, nil
}

func main() {
	total, err := totalPrice([]string{"apple", "pear", "plum"})
	fmt.Println(total, err)

	total, err = totalPrice([]string{"apple", "kiwi", "plum"})
	fmt.Println(total, err)
	fmt.Println("is errNotFound:", errors.Is(err, errNotFound))
}
360 <nil>
0 price of "kiwi": not found
is errNotFound: true

Things to know:

Canceling the rest with WithContext

errgroup.WithContext(ctx) returns a group and a derived context. The context is canceled as soon as any function returns an error (and also when Wait returns). The functions must watch that context to stop early:

package main

import (
	"context"
	"errors"
	"fmt"
	"time"

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

// download pretends to download a file. It takes d to finish
// and gives up early if ctx is canceled.
func download(ctx context.Context, name string, d time.Duration, fail bool) error {
	select {
	case <-time.After(d):
		if fail {
			return fmt.Errorf("%s: server returned 500", name)
		}
		fmt.Println(name, "done")
		return nil
	case <-ctx.Done():
		fmt.Println(name, "canceled:", context.Cause(ctx))
		return ctx.Err()
	}
}

func main() {
	start := time.Now()
	g, ctx := errgroup.WithContext(context.Background())

	g.Go(func() error { return download(ctx, "small.zip", 10*time.Millisecond, false) })
	g.Go(func() error { return download(ctx, "broken.zip", 50*time.Millisecond, true) })
	g.Go(func() error { return download(ctx, "huge.iso", 5*time.Second, false) })
	g.Go(func() error { return download(ctx, "video.mp4", 3*time.Second, false) })

	err := g.Wait()
	fmt.Println("Wait:", err)
	fmt.Println("is context.Canceled:", errors.Is(err, context.Canceled))
	fmt.Println("took less than 1s:", time.Since(start) < time.Second)
	fmt.Println("ctx after Wait:", ctx.Err())
}
small.zip done
video.mp4 canceled: broken.zip: server returned 500
huge.iso canceled: broken.zip: server returned 500
Wait: broken.zip: server returned 500
is context.Canceled: false
took less than 1s: true
ctx after Wait: context canceled

(The order of the two "canceled" lines varies between runs.)

When broken.zip fails after 50ms, the context is canceled and the two long downloads return right away instead of running for 3 and 5 seconds. Notes:

Bounded parallelism with SetLimit

Starting 10,000 goroutines that each open a network connection or decode a large image will exhaust file descriptors or memory. g.SetLimit(n) caps the number of goroutines running at once. g.Go blocks until a slot is free:

package main

import (
	"fmt"
	"sync"
	"time"

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

func main() {
	var mu sync.Mutex
	running, maxRunning := 0, 0

	resize := func(img int) error {
		mu.Lock()
		running++
		maxRunning = max(maxRunning, running)
		mu.Unlock()

		time.Sleep(20 * time.Millisecond) // pretend to resize image img

		mu.Lock()
		running--
		mu.Unlock()
		return nil
	}

	start := time.Now()
	var g errgroup.Group
	g.SetLimit(3)
	for img := range 12 {
		// Go blocks while 3 goroutines are already running.
		g.Go(func() error { return resize(img) })
	}
	if err := g.Wait(); err != nil {
		fmt.Println(err)
	}
	fmt.Println("max running at once:", maxRunning)
	fmt.Println("took at least 4 x 20ms:", time.Since(start) >= 80*time.Millisecond)
}
max running at once: 3
took at least 4 x 20ms: true

This replaces the buffered-channel semaphore from Limiting concurrency with a semaphore with one line. For CPU-bound work, runtime.NumCPU() is a good limit. For I/O, choose a limit based on what the remote side can handle.

Call SetLimit before starting goroutines. Changing it while goroutines are running panics.

Stop starting work after a failure

With a limit and a context, there's one more thing to handle. g.Go blocks in the loop, so after a failure the loop would keep starting new tasks, which would then see a canceled context and fail right away. Check the context in the loop to stop starting new work:

package main

import (
	"context"
	"fmt"
	"time"

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

func process(ctx context.Context, item int) error {
	if item == 3 {
		return fmt.Errorf("item %d is corrupt", item)
	}
	select {
	case <-time.After(20 * time.Millisecond):
		return nil
	case <-ctx.Done():
		return ctx.Err()
	}
}

func main() {
	g, ctx := errgroup.WithContext(context.Background())
	g.SetLimit(2)

	started := 0
	for item := range 100 {
		if ctx.Err() != nil {
			break // a task failed: don't start the rest
		}
		started++
		g.Go(func() error { return process(ctx, item) })
	}
	err := g.Wait()
	fmt.Println("error:", err)
	fmt.Println("started fewer than 100:", started < 100, started)
}
error: item 3 is corrupt
started fewer than 100: true 5

The exact number of started tasks depends on timing, but it is far fewer than 100.

TryGo: start only if there's a free slot

g.TryGo(f) is the non-blocking version of Go. It starts f only if the group is below its limit, and reports whether it did:

package main

import (
	"fmt"
	"time"

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

func main() {
	var g errgroup.Group
	g.SetLimit(2)

	for i := range 5 {
		started := g.TryGo(func() error {
			time.Sleep(50 * time.Millisecond)
			fmt.Println("task", i, "finished")
			return nil
		})
		if !started {
			fmt.Println("task", i, "skipped: no free slot")
		}
	}
	g.Wait()
}
task 2 skipped: no free slot
task 3 skipped: no free slot
task 4 skipped: no free slot
task 1 finished
task 0 finished

Use it for optional work: a background cache refresh that you skip if one is already running, or a request handler that does the work itself instead of queueing when all workers are busy. Without SetLimit, TryGo always starts the goroutine.

Panics in goroutines

A panic that isn't recovered in a goroutine crashes the whole program. recover in main doesn't help, because recover only works in the goroutine that panicked. Deferred calls in main don't run either:

package main

import (
	"fmt"
	"sync"
)

func main() {
	defer fmt.Println("deferred in main") // never runs

	var wg sync.WaitGroup
	wg.Go(func() {
		var m map[string]int
		m["x"] = 1 // panics: assignment to entry in nil map
	})
	wg.Wait()
	fmt.Println("unreachable")
}
panic: assignment to entry in nil map [recovered, repanicked]

goroutine 7 [running]:
sync.(*WaitGroup).Go.func1.1()
	C:/Program Files/Go/src/sync/waitgroup.go:251 +0x45
panic({0x7ff75edb23f8?, 0x7ff75edc7400?})
	C:/Program Files/Go/src/runtime/panic.go:859 +0x125
main.main.func1()
...
exit status 2

The documentation of wg.Go says f must not panic. If it does, wg.Go deliberately doesn't call Done. Otherwise Wait could return and main could exit cleanly before the panic finishes crashing the process, and the crash would go unnoticed.

errgroup doesn't recover panics either. Its source explains why: turning a panic into a value delays the crash, hides the stack from crash-reporting tools and can leave the program in a broken state.

Crashing is usually the right outcome, because a panic means a bug. When a single task must not take down a long-running server (e.g. a plugin or user-supplied code), recover inside the goroutine and turn the panic into an error:

package main

import (
	"fmt"
	"io"
	"log"
	"runtime/debug"

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

// goSafe runs f in g and turns a panic in f into an error.
func goSafe(g *errgroup.Group, f func() error) {
	g.Go(func() (err error) {
		defer func() {
			if r := recover(); r != nil {
				log.Printf("stack of recovered panic:\n%s", debug.Stack())
				err = fmt.Errorf("recovered panic: %v", r)
			}
		}()
		return f()
	})
}

func main() {
	log.SetOutput(io.Discard) // keep the example output short

	var g errgroup.Group
	goSafe(&g, func() error { return nil })
	goSafe(&g, func() error {
		var items []int
		fmt.Println(items[3])
		return nil
	})
	fmt.Println("Wait:", g.Wait())
	fmt.Println("program keeps running")
}
Wait: recovered panic: runtime error: index out of range [3] with length 0
program keeps running

The deferred function sets the named result err, so the panic becomes an ordinary error. Log debug.Stack() inside the deferred function, because that's the only place where the stack of the panicking goroutine is still available. See Panic and recover for more about recover.

Which one to use

Situation Use
Tasks can't fail, just wait for all sync.WaitGroup with wg.Go
Tasks return errors, want the first one errgroup.Group
First error should stop the others errgroup.WithContext
Limit how many run at once g.SetLimit(n)
Skip work when all slots are busy g.TryGo
Need every error, not just the first per-task []error plus errors.Join

In code written for Go 1.25 or later, there's little reason to call wg.Add and wg.Done directly. They're still needed when the counter has to be increased by more than one at a time, or when Done is called somewhere other than at the end of a goroutine's function.

For more goroutine mistakes, see Common pitfalls.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents