Go concurrency
Concurrency in Go is cheap to start and expensive to get wrong. The failures — leaks, races, deadlocks — are invisible in the happy path and appear under load.
Never start a goroutine without knowing how it stops
Before writing go f(), answer: what makes this return, and who waits for it? A goroutine blocked forever on a channel send or receive is a permanent leak of its stack and everything it references.
// Bad — if nobody ever receives, this goroutine never exits
go func() { ch <- compute() }()
// Good — cancellation ends it, and the caller waits
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
select {
case ch <- compute():
case <-ctx.Done():
}
}()
wg.Wait()
The Add goes before the go, never inside the goroutine — otherwise Wait can run first and return immediately.
Context carries cancellation, not data
Pass ctx as the first parameter. Never store it in a struct. Every blocking operation selects on ctx.Done(), and every function that takes a ctx must honour it.
func poll(ctx context.Context, interval time.Duration) error {
t := time.NewTicker(interval)
defer t.Stop()
for {
select {
case <-ctx.Done():
return ctx.Err()
case <-t.C:
if err := checkOnce(ctx); err != nil { return err }
}
}
}
Always call the cancel returned by WithCancel / WithTimeout, usually via defer — skipping it leaks the timer and the child context.
ctx.Value is for request-scoped metadata that crosses API boundaries (trace ID, auth subject). It is not a way to pass arguments.
Channel ownership
One goroutine owns a channel: it creates, writes, and closes. Everyone else only receives. Closing from the receiver side, or from two writers, panics.
func generate(ctx context.Context, items []Item) <-chan Item {
out := make(chan Item) // owner creates
go func() {
defer close(out) // owner closes, always
for _, it := range items {
select {
case out <- it:
case <-ctx.Done():
return
}
}
}()
return out // receive-only to everyone else
}
Direction in the signature (<-chan T, chan<- T) makes misuse a compile error. Closing signals "no more values" — it is not a cancellation mechanism, and never a way to send one.
errgroup for parallel work that can fail
Hand-rolled WaitGroup-plus-error-channel code is where the bugs live. golang.org/x/sync/errgroup cancels siblings on the first failure and returns it.
g, ctx := errgroup.WithContext(ctx)
g.SetLimit(8) // bound the parallelism
for _, u := range urls {
g.Go(func() error { return fetch(ctx, u) })
}
if err := g.Wait(); err != nil {
return fmt.Errorf("fetch: %w", err)
}
Unbounded goroutine creation over an unbounded input is a resource exhaustion bug. Bound it — SetLimit, a worker pool, or a semaphore.
Share memory by communicating, or lock it
Pick one per piece of state. Channels for handing ownership between goroutines; a mutex for a value several goroutines read and write in place.
type Counter struct {
mu sync.Mutex // guards n — state it in a comment
n map[string]int
}
func (c *Counter) Inc(key string) {
c.mu.Lock()
defer c.mu.Unlock()
c.n[key]++
}
Keep the critical section small and do no I/O inside it. sync.RWMutex only when reads dominate and you have measured. A mutex must never be copied — pass *Counter, and go vet will catch the mistake.
For the common cases, reach for the primitive that already exists: sync.Once for one-time init, atomic.Int64 for a counter, errgroup for fan-out.
Loop variables
Go 1.22 changed for loops to create a fresh variable per iteration, so the classic capture bug is gone on modern toolchains. On older ones, or in any go func() capturing anything reused, shadow it explicitly.
Verify, do not reason
Races are not found by reading code. Run tests with -race in CI:
go test -race ./...
A hang means a deadlock or a leak: SIGQUIT the process for a full goroutine dump, or use goleak in tests to fail when a test leaves goroutines behind.