Golang Concurrency
Priority: P0 (CRITICAL)
Principles
- Share Memory by Communicating: Use channels instead of shared memory.
- Context is King: Always pass
ctxto manage cancellation/timeouts. - Prevent Leaks: Never start a goroutine without knowing how it will stop.
- Race Detection: Always run tests with
go test -race.
Implementation Workflow
- Choose primitive — Channels for data passing,
sync.Mutexfor simple state protection,errgroupfor parallel tasks with error handling. - Pass context — Every goroutine that does I/O or long work must accept
context.Context. - Define exit paths — Every goroutine must have a clear shutdown mechanism (context cancellation, channel close, or WaitGroup).
- Use select for multiplexing — Handle multiple channels or timeouts with
select. - Test with race detector — Run
go test -racein CI.
See ErrGroup and concurrency patterns and context timeout examples
Anti-Patterns
- ❌ Goroutine leaks — every goroutine needs a known exit path
- ❌ Global state mutation across goroutines — use channels or sync primitives
- ❌ Bare goroutines without lifecycle management — use
errgrouporWaitGroup