standards-go-concurrency
Skill0 starsChanged 4 months agoMITView on GitHub
Use this skill when writing, modifying, or reviewing goroutines, channels, mutexes, wait groups, contexts, or other synchronization primitives in Go, even if the user does not mention concurrency. Provides safe concurrency patterns, leak prevention, and race-detection checklists. Use standards-go for general Go style and standards-go-performance for profiling concurrent code.
In this repository34 other files it gives its agents.
- AGENTS.mdAGENTS.md
- mcpSkill
- pattern-orchestration-complexSkill
- pattern-task-breakdownSkill
- role-architectSkill
- role-code-reviewSkill
- role-data-engineerSkill
- role-developerSkill
- role-orchestratorSkill
- role-product-engineerSkill
- role-qa-engineerSkill
- role-security-auditorSkill
- role-site-reliability-engineerSkill
- role-technical-writerSkill
- standards-analysisSkill
- standards-api-designSkill
- standards-codeSkill
- standards-databaseSkill
- standards-documentationSkill
- standards-go-performanceSkill
- standards-goSkill
- standards-go-testingSkill
- standards-markdownSkill
- standards-observabilitySkill
- standards-pulumi-typescriptSkill
- standards-pythonSkill
- standards-securitySkill
- standards-shellSkill
- standards-skill-authoringSkill
- standards-testingSkill
- standards-typescriptSkill
- tool-storeSkill
- workflow-debuggingSkill
- workflow-pi-extensionSkill
The file
Show its rules and text
We split this skill into the rules it gives an agent
38 rules. About 0 are common, 16 are distinctive, and 22 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈16
Distinctive · estimate
This author's own choices. Worth a look.
22
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 18
Use errgroup.WithContext for fan-out parallelism
- Very specific: line 21
Use sync.WaitGroup or errgroup to join all spawned goroutines
- Distinctive: line 22
Keep mutex critical sections minimal: no I/O under a lock
- Very specific: line 23
Prefer time.NewTimer over time.After inside loops
- Distinctive: line 24
Prefer synchronous APIs: let the caller add the goroutine
- Very specific: line 25
Use named mu sync.Mutex field, never embed a mutex in a struct
- Distinctive: line 26
Document thread-safety when read-vs-write behaviour is non-obvious
- Very specific: line 33
Use sync.RWMutex without benchmark evidence of read-heavy contention
- Very specific: line 34
Use time.After in loops (allocates a new timer each iteration)
- Distinctive: line 37
Use channel buffers > 1 without documented justification
- Distinctive: line 58
Do not store ctx in struct fields.
- Distinctive: line 87
Every goroutine must have a single owner responsible for starting, stopping, and joining it.
- Very specific: line 92
Stop time.Ticker with defer ticker.Stop() in the owning goroutine.
- Very specific: line 117
Avoid goroutines in init().
- Distinctive: line 119
Prefer synchronous over async APIs: Write functions synchronously by default: the caller can always wrap the call in a goroutine.
- Distinctive: line 121
Prefer synchronous APIs in libraries.
- Very specific: line 131
Use golang.org/x/sync/errgroup when launching parallel work where the first error should cancel everything else.
- Very specific: line 133
Create with errgroup.WithContext(parentCtx) so the derived ctx is cancelled on the first error.
- Very specific: line 159
Use g.SetLimit(n) for large/unbounded input sets.
- Very specific: line 169
Use fan-out/fan-in when parallel throughput is needed without shared mutable accumulators.
- Very specific: line 178
Use directional types at function boundaries: chan<- T for producers, <-chan T for consumers.
- Very specific: line 180
Buffer sizing rule of thumb: default to unbuffered (0) or size 1.
- Distinctive: line 192
Use mutexes only when shared mutable state cannot be confined to a single goroutine.
- Distinctive: line 194
Keep critical sections as small as possible: compute outside the lock, hold only for the read/write.
- Distinctive: line 195
Never perform I/O (network, disk, logging) while holding a lock.
- Distinctive: line 196
Document lock ordering when multiple mutexes are acquired together.
- Very specific: line 197
Prefer sync.Mutex by default.
- Very specific: line 200
Use named mutex fields (mu sync.Mutex) instead of embedding.
- Very specific: line 202
Never copy a struct that embeds sync.Mutex: pass by pointer.
- Distinctive: line 204
Keep critical sections tiny and avoid I/O while holding locks.
- Very specific: line 214
Use sync.Once to perform an action exactly once across all goroutines, regardless of how many call it concurrently.
- Very specific: line 226
Prefer sync.OnceValue/sync.OnceFunc (Go 1.21+) for cleaner one-time initialization.
- Very specific: line 239
Avoid time.After in loops.
- Very specific: line 245
Use goleak in concurrency-heavy test suites.
- Distinctive: line 251
Use worker pools to cap concurrency and apply backpressure.
- Distinctive: line 257
Use channel-based semaphores for simple bounded concurrency when a full worker pool is unnecessary.
- Very specific: line 263
Use golang.org/x/time/rate with per-tenant/per-key scope when fairness matters.
- Distinctive: line 279
Interface implementations: if an interface requires concurrent use, state it in the type or interface doc comment.
≈ “Common” is an estimate: at least 1 in 5 of the 364,980 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Go Concurrency Standards
Provides: Safe goroutine lifecycle management, context-first cancellation, channel ownership rules, mutex discipline, leak prevention patterns, and race-detection checklists.
Primary references: Effective Go, Go CodeReviewComments, and major Go style guides.
Quick Reference
Golden Rule: Own your goroutines: every goroutine you start must have a clear owner, a stop mechanism, and a join point.
✅ DO:
- Pass
ctxas the first parameter to every blocking function - Use
errgroup.WithContextfor fan-out parallelism - Close channels only from the sender; use directional channel types
defer ticker.Stop()immediately aftertime.NewTicker- Use
sync.WaitGrouporerrgroupto join all spawned goroutines - Keep mutex critical sections minimal: no I/O under a lock
- Prefer
time.NewTimerovertime.Afterinside loops - Prefer synchronous APIs: let the caller add the goroutine
- Use named
mu sync.Mutexfield, never embed a mutex in a struct - Document thread-safety when read-vs-write behaviour is non-obvious
❌ DON'T:
- Fire-and-forget goroutines in request handlers or libraries
- Close a channel from a receiver or from multiple goroutines
- Store a
context.Contextin a struct field - Derive a new goroutine's context from
context.Background()instead of the parent - Use
sync.RWMutexwithout benchmark evidence of read-heavy contention - Use
time.Afterin loops (allocates a new timer each iteration) - Copy a struct that embeds
sync.Mutexorsync.RWMutex - Spawn goroutines in
init(): use a lifecycle-managed object instead - Use channel buffers > 1 without documented justification
Key Commands:
go test -race ./... # detect data races
go test -run TestX -count=100 ./pkg # stress-test concurrency
go test -timeout 30s ./... # catch goroutine leaks via timeout
# Goroutine profile snapshot:
go tool pprof -http=:0 http://localhost:6060/debug/pprof/goroutine
go test -count=1 -run TestWorkerPool -v ./... # verify pool goroutine countContext-First Cancellation
Propagate deadlines and cancellation signals through the call graph so any blocking operation can be interrupted cleanly.
- Accept
ctx context.Contextas the first parameter of every function that may block. - In loops, add a
selectarm onctx.Done()alongside the work arm. - Derive child contexts with
context.WithTimeout/context.WithCancelfrom the caller's ctx, never fromcontext.Background(). - Do not store ctx in struct fields; pass it through the call chain instead.
// ✅ Correct: context threaded through loop
func process(ctx context.Context, jobs <-chan Job) error {
for {
select {
case <-ctx.Done():
return ctx.Err()
case j, ok := <-jobs:
if !ok {
return nil
}
if err := handle(ctx, j); err != nil {
return err
}
}
}
}Forgetting select ctx.Done() in tight inner loops; shadowing ctx with a new variable inside the loop body; deriving from context.Background() instead of the parent.
Unit tests that cancel ctx mid-flight and assert the function returns promptly; go test -race ./....
Goroutine Ownership & Lifecycle
Every goroutine must have a single owner responsible for starting, stopping, and joining it.
- Assign ownership at the call site that calls
go func(...). - Provide a stop mechanism: a cancellable
ctxor a dedicated done/quit channel. - Join with
sync.WaitGrouporerrgroupbefore the owner returns or exits. - Stop
time.Tickerwithdefer ticker.Stop()in the owning goroutine.
// ✅ Correct: owned, stoppable, joined
func startWorker(ctx context.Context, wg *sync.WaitGroup, in <-chan Item) {
wg.Add(1)
go func() {
defer wg.Done()
for {
select {
case <-ctx.Done():
return
case item, ok := <-in:
if !ok {
return
}
process(item)
}
}
}()
}- No goroutines in
init():init()must not spawn goroutines: callers have no way to stop or wait for them. Instead, expose a lifecycle-managed object with an explicitStart/Shutdownmethod:
Avoid goroutines in init(); use explicit lifecycle (Start/Shutdown) instead.
- Prefer synchronous over async APIs: Write functions synchronously by default: the caller can always wrap the call in a goroutine. Async APIs force concurrency on callers, making lifetimes harder to reason about and tests harder to write.
Prefer synchronous APIs in libraries; let callers add goroutines.
Fire-and-forget goroutines inside HTTP handlers that outlive the request; closing channels from multiple goroutines causing panics; leaking time.Ticker by only calling Stop without draining.
pprof goroutine profile stays bounded under load; tests include cancellation and timeout paths (see standards-testing).
errgroup for Fan-Out / Fan-In
Use golang.org/x/sync/errgroup when launching parallel work where the first error should cancel everything else.
- Create with
errgroup.WithContext(parentCtx)so the derived ctx is cancelled on the first error. - Pass the group's ctx into every worker so they can exit early.
- Collect results into pre-allocated slices (index by worker ID) to avoid data races on shared accumulators.
- Bound parallelism with
g.SetLimit(n)(Go 1.x/x/sync v0.1+) to cap the number of concurrent goroutines in the group: prevents unbounded goroutine creation when iterating over large inputs.
// ✅ Correct: workers respect cancellation; no shared mutable state
g, ctx := errgroup.WithContext(parentCtx)
results := make([]Result, len(inputs))
for i, inp := range inputs {
i, inp := i, inp // capture loop vars
g.Go(func() error {
r, err := fetch(ctx, inp)
if err != nil {
return err
}
results[i] = r
return nil
})
}
if err := g.Wait(); err != nil {
return nil, err
}Use g.SetLimit(n) for large/unbounded input sets.
Workers that ignore the group's ctx and never check ctx.Done(); appending to a shared slice without synchronization (data race).
go test -race ./...; deterministic tests using fakes or in-process stubs (see standards-testing).
Fan-Out / Fan-In
Use fan-out/fan-in when parallel throughput is needed without shared mutable accumulators. Keep it simple: workers read a shared input channel, merge closes output only after all workers finish, and every goroutine respects ctx.Done().
Channel Ownership Rules
Channels are owned by the sender: only the sender may close a channel.
- The goroutine that creates and writes to a channel is its owner and is the only one that closes it.
- Use directional types at function boundaries:
chan<- Tfor producers,<-chan Tfor consumers. - A nil channel blocks forever on send and receive: use this intentionally to disable a
selectarm. - Buffer sizing rule of thumb: default to unbuffered (
0) or size1. Any other size should be documented and justified.
One owner should create/write/close each channel; receivers should not close channels.
Multiple goroutines closing the same channel (panic); buffered channels that grow unboundedly under load.
Tests exercise the closed-channel path; select loops always have a ctx cancellation arm to prevent deadlock.
Mutex Discipline
Use mutexes only when shared mutable state cannot be confined to a single goroutine.
- Keep critical sections as small as possible: compute outside the lock, hold only for the read/write.
- Never perform I/O (network, disk, logging) while holding a lock.
- Document lock ordering when multiple mutexes are acquired together.
- Prefer
sync.Mutexby default; only upgrade tosync.RWMutexafter benchmark evidence of a read-heavy bottleneck. - Do not embed mutexes in structs: embedding promotes
Lock/Unlockto the public API. Use a named fieldmu sync.Mutexso the mutex stays an implementation detail:
Use named mutex fields (mu sync.Mutex) instead of embedding.
- Never copy a struct that embeds
sync.Mutex: pass by pointer.
Keep critical sections tiny and avoid I/O while holding locks.
Lock inversion (acquiring locks in different orders across goroutines causes deadlock); copying mutex-embedding structs by value; using RWMutex.RLock for write operations.
go test -race ./...; contention benchmarks (go test -bench . -benchmem); mutex profile (/debug/pprof/mutex) when a hot path is suspected (see standards-observability).
sync.Once: One-Time Initialization
Use sync.Once to perform an action exactly once across all goroutines, regardless of how many call it concurrently.
- Embed
sync.Oncein the owning struct; callonce.Do(fn)wherefncontains the initialization. - In Go 1.21+, prefer
sync.OnceFunc(fn)(returns a no-arg func you call repeatedly) orsync.OnceValue(fn)(returns a func that returns the value): they are cleaner and cache the result automatically. Dopanics iffnpanics; the panic propagates to all callers and the initialization is not retried.- Calling
once.Dowith a different function on subsequent calls has no effect: only the first call's function runs. - Holding a lock while calling
once.Doa second time in the same goroutine deadlocks. - Storing computed results requires an explicit field; use
sync.OnceValueto avoid the boilerplate.
Concurrent goroutines all receive the same initialized value; go test -race ./... passes.
Prefer sync.OnceValue/sync.OnceFunc (Go 1.21+) for cleaner one-time initialization.
Avoiding Common Leaks
Leaked goroutines, timers, and unclosed resources accumulate silently and exhaust memory or file descriptors.
time.Ticker:ticker := time.NewTicker(d); defer ticker.Stop()immediately in the same function.time.Afterin loops: replace withtime.NewTimer+defer timer.Stop()or reset the timer;time.Afterallocates a newTimerevery iteration.- HTTP response bodies:
defer resp.Body.Close()after checking the error fromhttp.Do. selectloops must always include actx.Done()or done-channel arm: a goroutine blocked on a send to a channel no one reads is a leak.
Avoid time.After in loops; reuse timers to prevent per-iteration allocations/leaks.
Forgetting defer resp.Body.Close() when an error is returned before the defer; goroutines parked on a send to a full unbuffered channel when the receiver has exited.
Assert goroutine count is bounded in tests (capture runtime.NumGoroutine() before/after); use go.uber.org/goleak in tests to detect leaked goroutines automatically; take runtime/pprof goroutine snapshots under load (see standards-observability).
Use goleak in concurrency-heavy test suites.
Worker Pool
Use worker pools to cap concurrency and apply backpressure; keep queue size and shutdown semantics explicit.
Semaphore
Use channel-based semaphores for simple bounded concurrency when a full worker pool is unnecessary.
Rate Limiting
Use golang.org/x/time/rate with per-tenant/per-key scope when fairness matters. Always handle limiter.Wait(ctx) errors.
Pipeline
For staged stream processing, make every stage context-aware, close outputs deterministically, and avoid hidden shared state.
Documenting Thread-Safety
Go callers assume read-only operations are concurrency-safe and mutating operations are not. Document concurrency behaviour when this assumption doesn't hold:
- Read-mutating mismatch: e.g., a
Lookupthat silently mutates LRU state is not safe for concurrent calls; say so. - API provides synchronization: e.g., a thread-safe client or cache; document that concurrent use is safe.
- Interface implementations: if an interface requires concurrent use, state it in the type or interface doc comment.
// Cache is safe for concurrent use by multiple goroutines.
type Cache struct { ... }
// Lookup returns the value for key, updating recency order.
// It is NOT safe to call concurrently with Set.
func (c *Cache) Lookup(key string) (string, bool) { ... }Skill Loading Triggers
| Situation | Also load |
| Reviewing concurrency code | role-code-review |
| Tracing goroutine latency | standards-observability |
| Writing concurrency tests | standards-go-testing |
Verification Checklist
For baseline formatting, vet, and go test checks see
standards-go.
- ctx passed as first parameter to all blocking functions; never stored in struct fields
- Every goroutine has an explicit owner, stop mechanism, and is joined (WaitGroup or errgroup)
- No goroutines spawned in
init(): lifecycle-managed object used instead - Only senders close channels; directional channel types used at function boundaries
- No I/O held under mutex lock; mutex is a named field (
mu sync.Mutex), not embedded - time.Ticker always deferred Stop(); time.After not used inside loops
- HTTP response bodies always closed after error check
- go test -race passes with no warnings
- go.uber.org/goleak used in test suite to catch goroutine leaks
- Channel buffers are 0 or 1 by default; larger sizes are documented
- errgroup workers respect group ctx; SetLimit used when input can grow unbounded
- sync.Once / OnceValue / OnceFunc used for one-time initialization where applicable
Note: file list is sampled.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

