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.
-
Interfaces and Standard Abstractions
-
Interfaces Are Satisfied Implicitly
-
Read and Stream With io.Reader and io.Writer
-
-
-
Context, Timeouts, and Cancellation
-
Use context.Context for Deadlines and Cancellation
-
Set Timeouts on HTTP Clients and Server Handlers
-
-
-
Goroutines, Channels, and Coordination
-
Run Concurrent Work Safely With sync.WaitGroup
-
Coordinate Pipelines and Timeouts With Channels and select
-
-
-
Structured Logging and Databases
-
Write Structured JSON Logs With log/slog
-
Query Relational Data Safely With database/sql
-
-
-
Middleware and Production-Ready Services
-
Wrap HTTP Handlers With Middleware
-
Build a Multi-Route Service With Graceful Shutdown
-
-
-
Generics, Transactions, Timers, and Test Doubles
-
Generics, Constraints, and slices/maps Packages
-
SQL Transactions and Connection Pool Limits
-
Timers, Tickers, and Avoiding time.After Leaks
-
Testing With Interface Fakes, t.TempDir, and testdata
-
-
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:
- Call
wg.Add(1)beforego func()—never inside the goroutine, orwg.Wait()can execute before the scheduler starts the goroutine and return early! - 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 wherewg.Wait()sees count0and returns before workers even start. - Passing a
sync.WaitGroupby value to a helper function: Copies the internal counter sowg.Done()decrements the copy while the caller hangs forever onwg.Wait()! Always pass*sync.WaitGroup. - Appending to a shared slice or writing to a shared map without a lock: Fails immediately under
go test -raceand 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
Comments
Sign in to commentNo comments yet.