Skip to Content
Skip to content
Go Intermediate: Interfaces, Concurrency, and Services
Intermediate
Courses
Go Intermediate: Interfaces, Concurrency, and Services

Run Concurrent Work Safely With sync.WaitGroup

Launch concurrent tasks with sync.WaitGroup, collect results without shared-memory races, and verify safety with go test -race. After this, you can parallelize I/O without data races.

Course content

Sign in to save your progress.

Course Home

Suppose your health dashboard needs to probe 10 microservices and display their HTTP status codes in the exact order they were listed. Calling them one after another takes 10 × 150 ms = 1.5 seconds. Launching 10 goroutines concurrently cuts the whole check to ~150 ms—as long as you wait for every goroutine deterministically and collect their results without triggering a data race.

Skip ahead

If you already coordinate goroutines with sync.WaitGroup (or Go 1.25's wg.Go), collect results safely into pre-allocated slices, and know when to switch to errgroup, continue to "Coordinate Pipelines and Timeouts With Channels and select."

Experiment 1: Why launching goroutines without a WaitGroup loses results

If main() or a handler starts goroutines with go probe(u) and immediately returns without waiting, Go tears down the function (or exits the process) before those goroutines finish. Using time.Sleep(200 * time.Millisecond) is just as broken: it wastes 180 ms when endpoints are fast and silently drops results when one endpoint takes 250 ms.

sync.WaitGroup solves this cleanly with two strict ordering rules:

  1. Call wg.Add(1) before go func()—never inside the goroutine, or wg.Wait() can execute before the scheduler starts the goroutine and return early!
  2. Call defer wg.Done() as the first line inside the goroutine so even early returns or panics decrement the counter cleanly.

Experiment 2: Probing multiple URLs concurrently with zero locks

Look at how probeAll avoids shared-slice races: instead of appending to one slice from 10 goroutines, it pre-allocates results := make([]Probe, len(urls)) and lets goroutine i write exclusively to its own slot results[i]:

package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"sync"
)

type Probe struct {
	URL    string
	Status int
	Err    error
}

func probeAll(client *http.Client, urls []string) []Probe {
	results := make([]Probe, len(urls))
	var wg sync.WaitGroup

	for i, u := range urls {
		wg.Add(1)
		go func() {
			defer wg.Done()
			resp, err := client.Get(u)
			if err != nil {
				results[i] = Probe{URL: u, Err: err}
				return
			}
			resp.Body.Close()
			results[i] = Probe{URL: u, Status: resp.StatusCode}
		}()
	}

	wg.Wait()
	return results
}

func main() {
	s1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(200) }))
	defer s1.Close()
	s2 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(503) }))
	defer s2.Close()

	out := probeAll(s1.Client(), []string{s1.URL, s2.URL, s1.URL})
	for i, p := range out {
		fmt.Printf("idx=%d status=%d err=%v\n", i, p.Status, p.Err)
	}
}
$ go run -race .
idx=0 status=200 err=<nil>
idx=1 status=503 err=<nil>
idx=2 status=200 err=<nil>

Experiment 3: Why results[i] is race-free while append crashes

If all 10 goroutines ran results = append(results, probe) concurrently, they would fight over the exact same slice header (pointer, length, capacity)—triggering a data race under -race and silently dropping items in production. By contrast, Go guarantees that distinct elements of a pre-allocated slice (results[0], results[1], results[2]) are independent variables in memory, and wg.Wait() inserts a memory synchronization barrier so main sees every write once Wait() returns.

Experiment 4: Cleaner spawning in Go 1.25+ and canceling on first error

In Go 1.25+, wg.Go(func() { ... }) combines wg.Add(1), go func(), and defer wg.Done() into one call so mismatched counts become impossible:

var wg sync.WaitGroup
for i, u := range urls {
	wg.Go(func() {
		results[i] = checkOne(client, u)
	})
}
wg.Wait()

And when you want to stop sibling tasks immediately as soon as the first call returns an error (or cap concurrency across 10,000 items), reach for errgroup.WithContext(ctx) + g.SetLimit(16) from golang.org/x/sync/errgroup.

Common mistakes

  • Calling wg.Add(1) inside the goroutine: Creates a race where wg.Wait() sees count 0 and returns before workers even start.
  • Passing a sync.WaitGroup by value to a helper function: Copies the internal counter so wg.Done() decrements the copy while the caller hangs forever on wg.Wait()! Always pass *sync.WaitGroup.
  • Appending to a shared slice or writing to a shared map without a lock: Fails immediately under go test -race and corrupts memory under real load.

💡 Tip

Make go test -race ./... your default test command in CI. Go's race detector instruments memory accesses at runtime and catches subtle concurrency bugs on the very first run.

What happens if you skip this step

Without proper WaitGroup discipline and disjoint writes (or mutexes), concurrent code passes 99% of local runs and then randomly returns truncated slices or crashes with concurrent map writes in production.

You pass wg sync.WaitGroup (not *sync.WaitGroup) to a worker helper function that calls defer wg.Done(). What happens when the caller hits wg.Wait()?

About

Launch concurrent tasks with sync.WaitGroup, collect results without shared-memory races, and verify safety with go test -race. After this, you can parallelize I/O without data races.

Duration
5 min
Last update
11/27/2026
Was this helpful?
​ 0 ​ 0

Comments

Sign in to comment

No comments yet.