go-concurrency
Skill1 starsChanged 2 months agoMITView on GitHub
Write Go concurrency that does not leak, deadlock, or race - goroutines as ownership, channels as hand-off, select, context cancellation and propagation, errgroup, worker pools, mutex vs RWMutex vs sync.Map, and precise loop-variable capture rules across Go versions. Use when a service hangs, grows goroutines unboundedly, deadlocks, trips the race detector, or when someone asks how to bound concurrency, fan out work, or cancel a request. Triggers on "goroutine leak", "data race", "deadlock", "context", "errgroup", "WaitGroup", "semaphore", "all goroutines are asleep".
11 other projects use a version of this.
Adopted by
Most recently taken up by
- hishamkaram/delegation-layertheir own version, first seen Nov 29, 2026
- inference-gateway/skillstheir own version, first seen Nov 23, 2026
- lengrufeng2008/dsh-skill-librarytheir own version, first seen Nov 15, 2026
- h0rn3t/golang-skillstheir own version, first seen Nov 12, 2026
- Lu1sDV/skillsmdtheir own version, first seen Nov 1, 2026
- hishamkaram/claude-code-routertheir own version, first seen Oct 27, 2026
Used with
Projects with it also use go-testing.
Other files people use alongside this one.
Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
alex-ilgayevSkillgo-testing
Handles all Golang testing tasks including running tests, writing new tests, and fixing test failures. Follows MCPSpy testing conventions with require for critical assertions and assert for non-critical ones.
Also in 4 projects that use this
Other versions11 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 11
- hishamkaram/claude-code-router★ 12same name
- wpank/ai★ 11same name
- h0rn3t/golang-skills★ 8same name
- inference-gateway/skills★ 3same name
- CasLubbers/code-design-skills★ 2same name
- hishamkaram/delegation-layer★ 2same name
- Lu1sDV/skillsmd★ 2same name
- AllThingsSmitty/proven-skills★ 1same name
- Cadasto/go-coding-plugin★ 0same name
- Dankosik/golang-backend-skills★ 0same name
1 more not listed
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository126 other files it gives its agents.
- eu-data-backend-job-hunterSkill
- job-application-matcherSkill
- llm-agents-and-tool-useSkill
- llm-application-architectureSkill
- llm-cost-and-latency-optimizationSkill
- llm-evaluationSkill
- llm-fine-tuning-and-adaptersSkill
- llm-privacy-and-safetySkill
- llm-prompt-engineeringSkill
- llm-rag-systemsSkill
- structured-output-and-jsonSkill
- graphql-api-designSkill
- pagination-and-filteringSkill
- rest-api-designSkill
- webhooks-and-integrationsSkill
- caching-architecture-multi-layerSkill
- resilience-patternsSkill
- service-boundaries-and-monolithsSkill
- system-design-interviewSkill
- go-error-handlingSkill
- java-spring-patternsSkill
- nodejs-server-performanceSkill
- python-async-patternsSkill
- python-data-modelingSkill
- python-packaging-and-toolingSkill
- python-performanceSkill
- rest-api-implementationSkill
- rust-error-handlingSkill
- rust-ownership-patternsSkill
- typescript-type-safetySkill
- ci-caching-and-speedupSkill
- ci-pipeline-designSkill
- deployment-strategiesSkill
- github-actions-hardeningSkill
- release-versioning-and-changelogsSkill
- reproducible-buildsSkill
- aws-iam-and-securitySkill
- aws-serverless-architectureSkill
- azure-fundamentalsSkill
- cloud-cost-optimizationSkill
- cloud-networking-and-vpcSkill
- gcp-cloud-architectureSkill
- code-review-skillsSkill
- design-review-and-refactoring-architectureSkill
- refactoring-techniqueSkill
- understanding-unknown-codebaseSkill
- buildkit-and-cacheSkill
- container-image-debuggingSkill
- container-runtime-securitySkill
- docker-compose-workflowsSkill
- dockerfile-authoringSkill
- docker-image-optimizationSkill
- database-connection-managementSkill
- database-transactionsSkill
- distributed-databasesSkill
- nosql-data-modelingSkill
- postgres-query-tuningSkill
- redis-and-cachingSkill
- schema-migrationsSkill
- data-modeling-for-analyticsSkill
- The first 60 shown.
The file
We split this skill into the rules it gives an agent
6 rules. 0 are common, 1 is distinctive, and 5 are very specific to this project.
0
Common
Most of the 10 edited versions we read keep these.
1
Distinctive
This author's own choices. Worth a look.
5
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 41
Nothing stops a goroutine automatically: When the function that spawned it returns, the goroutine keeps running against whatever it …
- Very specific: line 64
Check your module's language version: go.mod's go 1.22 line (not the toolchain you happen to have installed) is what selects this behaviour.
- Very specific: line 101
When a context is cancelled, functions doing blocking work should return ctx.Err() (context.Canceled or context.DeadlineExceeded).
- Very specific: line 187
Use a buffered channel of size 1 as a one-shot signal (a done channel) to mean "close, not send", so the receiver's <-done unblocks without …
- Very specific: line 286
If workers only ever range jobs without a ctx.Done() case, the pool cannot be cancelled: a ctx cancel leaves them blocked on <-jobs until …
- Very specific: line 346
Look for goroutines all parked chan receive on the same channel.
“Common” is measured: kept by at least 6 in 10 of the 10 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Go Concurrency
A goroutine is a stack, not a thread, and it is the cheapest resource in the program. That is exactly why concurrency bugs in Go are about lifetime and ownership, not about performance. A goroutine that is started and never stopped is a leak; a goroutine that outlives the data it references is a data race waiting to happen. Design for who cancels and who closes.
Workflow
- 1. Decide what terminates every goroutine (usually: the request
context) - 2. Pass
ctxas the first parameter of anything that blocks, and store it, nevercontext.Background()in library code - 3. Use
errgroupfor fan-out;WaitGrouponly when you genuinely have no error and no early exit - 4. Bound concurrency with a semaphore or a worker pool; never
for { go f() }over an unbounded source - 5. Make every channel's owner and closer explicit
- 6. Run
go test -race ./...andGODEBUGleak checks before you call it done
Goroutines: cheap, and that is the problem
go handle(conn) // returns immediately, conn must be captured by value- Goroutines start with a ~2-8 KB stack and grow. Starting 10,000 is fine; starting them per request without a limit is a leak, not a feature.
- The scheduler multiplexes goroutines onto OS threads, so blocking on a channel is not a thread block.
- Nothing stops a goroutine automatically. When the function that spawned it returns, the goroutine keeps running against whatever it captured. If those are stack variables, it is reading freed-looking memory; if they are a request struct, it is a use-after-free in spirit.
Loop variable capture — the version rule
This is the most-copied Go gotcha, and the fix landed in Go 1.22. Be precise:
- Go 1.22+: each iteration of a
forloop creates a new variable for the loop variable. Capturingiorvin a goroutine or a closure gives each iteration its own copy. The classicfor _, v := range xs { go func() { use(v) }() }bug is fixed. The loop variables are per-iteration. - Go 1.21 and earlier: the loop variable is a single variable shared by
all iterations. Every closure/goroutine that captures it sees whatever value
it has when it eventually runs (usually the last one), or worse, a torn
value under
-race. You had to shadow it:v := vinside the loop. - The old
v := vshadow trick is now unnecessary on 1.22+ and is harmless. It is also misleading. If yourgo.modsaysgo 1.22or later, you can drop it; if you support older toolchains, keep it.
Check your module's language version: go.mod's go 1.22 line (not the
toolchain you happen to have installed) is what selects this behaviour. A go
1.21 line in go.mod under a Go 1.24 toolchain still uses the old
per-loop-variable semantics. This is the trap: the fix keys off the language
version in go.mod, not the compiler version.
Capturing a named return or a variable you then mutate is still a race on every version; the 1.22 fix is only about the loop variable. A pointer to a struct you keep mutating is a race regardless.
context: cancellation and values
context.Context is how cancellation, deadlines, and request-scoped values
flow down a call tree.
func Fetch(ctx context.Context, id string) (User, error) {
// FIRST parameter, named ctx, never stored in a struct.
}- Pass the parent's
ctxdown, derive a child when you add a deadline or cancel:ctx, cancel := context.WithTimeout(ctx, 2*time.Second); defer cancel(). Thedefer cancel()is not optional — a missing one leaks the timer and the parent's child list until the parent dies. - In library code, never create a fresh
context.Background()for a caller's work; that detaches the work from the caller's cancellation and is the root of most goroutine leaks. The main function and test setup are the only correct places forcontext.Background()/context.TODO(). - Do not put required data in a
context.Value.ctx.Valueis for request-scoped, optional, cross-cutting data (a trace id, a logger, an authenticated principal) that a deep callee may need but that is not part of the function's job. If the function needs the data to do its work, it is a parameter. A value in a context is invisible in the function signature, untypeable, impossible to require, and the compiler will not help you. Usecontext.WithValuewith an unexported custom key type (type ctxKey struct{}) to avoid collisions. - When a context is cancelled, functions doing blocking work should return
ctx.Err()(context.Canceledorcontext.DeadlineExceeded).context.DeadlineExceededis a timeout and may be retryable;context.Canceledusually means the caller went away and is not. http.NewRequestWithContext(ctx, ...)is mandatory for outgoing HTTP. The barehttp.NewRequestgives you a request you cannot cancel, and the connection outlives the request.
Fan-out: errgroup
errgroup.Group runs a set of goroutines, collects the first error,
cancels a shared context when any one fails, and Wait()s for all. This is
almost always what you want.
import (
"context"
"fmt"
"golang.org/x/sync/errgroup"
)
func FetchAll(ctx context.Context, ids []string) ([]User, error) {
g, ctx := errgroup.WithContext(ctx) // ctx is cancelled on first error
users := make([]User, len(ids)) // each goroutine writes its own index
for i, id := range ids {
i, id := i, id // needed only for go.mod < 1.22
g.Go(func() error {
u, err := Fetch(ctx, id)
if err != nil {
return fmt.Errorf("fetch %q: %w", id, err)
}
users[i] = u // disjoint indices: no race
return nil
})
}
if err := g.Wait(); err != nil {
return nil, err // siblings already cancelled
}
return users, nil
}g.Wait()returns the first non-nil error; becauseWithContextcancelled the sharedctx, the other operations abort promptly. Without the shared ctx,Waitstill waits for all goroutines to finish, so a slow sibling defeats your timeout.g.SetLimit(n)(fromx/sync) caps concurrency without a separate semaphore — blocks when the limit is reached. Use it beforeg.Go; the errorTryGovariant returnsfalseinstead of blocking.errgroupis ingolang.org/x/sync, not the stdlib. It is the de-facto choice;sync.WaitGroupis the stdlib alternative when you have no error and no cancellation.
WaitGroup — when you actually want it
var wg sync.WaitGroup
for _, item := range items {
wg.Add(1)
go func() {
defer wg.Done()
process(item) // no error path, no cancellation
}()
}
wg.Wait()wg.Add(1)must happen before thego, not inside it, orWaitcan return before the goroutine is counted.Waitwith a zero counter returns immediately — a common bug where you conditionallyAddin a branch and some iterations do not.- Note:
go vet'slostcanceland thesync.WaitGroup.Gomethod (Go 1.25+,wg.Go(func(){...})which doesAdd/Donefor you) reduce the foot-guns. Verifywg.Goexists for your toolchain (go doc sync.WaitGroup.Go); do not use it on older versions.
Channels, and who closes them
A channel is a hand-off and a synchronisation point, and the discipline is:
- The sender closes, and only the sender, exactly once. A receiver never
closes. Double-close is a
panic: close of closed channel; closing a nil channel panics. - Closing signals "no more values will be sent". Receivers detect it as the
comma-ok zero value (
v, ok := <-ch;ok == falsemeans closed), or by a range loop ending. - Use a buffered channel of size 1 as a one-shot signal (a
donechannel) to mean "close, not send", so the receiver's<-doneunblocks without a send. This is the idiomatic shutdown/close signal — do notclose(ch)to wake a receiver when you mean "signal once"; closing is for "no more ever".
done := make(chan struct{}) // closed to broadcast
go func() { defer close(done); work() }()
<-done // unblocks every receiver- A send on a full channel blocks; a send on a closed channel panics;
a receive on a nil channel blocks forever; a close of a nil channel
panics. A nil channel is sometimes useful — a
nilcase in aselectis simply never ready, which disables that branch. - Unbuffered by default (
make(chan T)) is a synchronisation point: the send blocks until a receiver takes it. Buffered (make(chan T, n)decouples producer and consumer by up ton. A buffer of 1 or a small value smooths a pipeline; a huge buffer hides backpressure and just moves the memory spike. Buffer to smooth bursts, not to avoid blocking. - Never close a channel you did not create, and never return an
unexported channel a caller might close. Signal with the channel being
closed by you in a
deferinside the constructor/owner, or return a receive-only channel (<-chan T) to prevent the caller from closing it.
select: multiplexing and cancellation
for {
select {
case <-ctx.Done():
return ctx.Err() // the ONLY way a goroutine stops on cancel
case v, ok := <-results:
if !ok {
return nil // producer closed the channel: done
}
consume(v)
case out <- v:
// send case
}
}selectchooses randomly among ready cases. Two cases ready → coin flip, every time. Never write aselectwhose correctness depends on which branch wins.- A
selectwith no default blocks until a case is ready. With adefault:it is a non-blocking poll that runs the default when nothing is ready. Use thedefaultform for a "drain what's ready" loop. - Always include a
case <-ctx.Done()in aselectinside a long-running goroutine, or it will never notice cancellation. This is the single most important habit. - A send in a
selectfires only if a receiver is already waiting (for an unbuffered channel); otherwise that case is not ready. So a "writer goroutine + reader that starts later" can deadlock unless the channel is buffered.
Full pattern cookbook (fan-in, fan-out, the complete cancellable worker pool,
pipeline stages, done/broadcast, timers, nil-channel trick, select + default
polling, non-blocking send attempt, semaphore bounding):
references/channel-select-cheatsheet.md.
Worker pools and bounded concurrency
Unbounded go f() over an unbounded source is how you OOM a service. The
worker template — every worker does a two-case select (ctx.Done() or
jobs) so cancellation is honoured, and the producer close(jobs) on every
path — is in references/channel-select-cheatsheet.md.
The essentials:
for w := 0; w < workers; w++ { // workers = GOMAXPROCS(0)*2, tune it
wg.Add(1)
go func() {
defer wg.Done()
for {
select {
case <-ctx.Done():
return // workers must be cancellable
case j, ok := <-jobs:
if !ok {
return // producer closed jobs: done
}
handle(ctx, j)
}
}
}()
}
defer close(jobs) // exactly once, on every path- Bound the fan-out. Either a fixed worker pool, or
errgroup.SetLimit(n), or a counting semaphore (sem := make(chan struct{}, n),sem <- struct{}{}before,<-semafter) for a fixed number of goroutines over a dynamic stream. close(jobs)must happen exactly once, on every path (including the cancellation path above) — usedefer close(jobs)if the producer is a single function.- If workers only ever
range jobswithout actx.Done()case, the pool cannot be cancelled: actxcancel leaves them blocked on<-jobsuntil the producer closes the channel. That is why the two-caseselectis the template.
Mutex vs RWMutex vs sync.Map
| Tool | Protects | Use when |
sync.Mutex | Any state, one holder at a time | Default. Write-heavy or mixed |
sync.RWMutex | Any state, many readers or one writer | Read-mostly and the critical section is long enough that the extra atomic ops pay off |
sync.Map | A specific map[K]V | See below — rarely the right choice |
type Cache struct {
mu sync.RWMutex
m map[string]Entry
}
func (c *Cache) Get(k string) (Entry, bool) {
c.mu.RLock(); defer c.mu.RUnlock()
e, ok := c.m[k] // map reads are safe under RLock
return e, ok
}
func (c *Cache) Set(k string, e Entry) {
c.mu.Lock(); defer c.mu.Unlock()
c.m[k] = e
}- A plain
mapis not safe for concurrent use; concurrent read+write causes a runtimefatal error: concurrent map writes(which is not recoverable and kills the process) or a silent race. Always guard it, or make it per-goroutine. RWMutexis not always faster thanMutex. It has higher per-operation cost; it only wins when reads dominate and the read section is non-trivial. Under mixed load it can be slower. Measure. Also: a writer waiting blocks new readers, so a long-heldRLockcan starve writers — never do I/O or channel sends while holding any lock.defer mu.Unlock()immediately afterLock. It is correct under early returns and panics, and theUnlockcost is negligible.- Never copy a
sync.Mutex/RWMutex. Copying the struct (passing by value) copies the lock and breaks mutual exclusion. Keep it as a zero field and pass the struct by pointer. sync.Mapis a specialised, mostly-append-only map optimised for two cases: (1) keys written once and read many times (e.g. a cache that mostly misses and is only ever added to), or (2) disjoint key sets across goroutines. The type issync.Mapwithanykeys/values, so you lose static typing. It is not a general replacement formap+Mutex; the doc explicitly says aMutex-protectedmapis better for a write-once/read-many or type-safe map. Default tomap+RWMutex.
Goroutine leaks — how to find them
- A leak is a goroutine blocked forever on a channel send/receive, a
select, or aWaitthat nobody will satisfy. Every spawned goroutine must have a path to return. - Diagnostic:
runtime.NumGoroutine()at a point in time; if it grows monotonically over a soak test, you are leaking. - Dumps: send
SIGQUIT(kill -QUIT <pid>) to a Go process to get a full goroutine stack dump, orgo tool pprof http://localhost:6060/debug/pprof/goroutine?debug=2. Look for goroutines all parkedchan receiveon the same channel. go.uber.org/goleak(a test-only dependency) fails aTestMainif goroutines outlive the test — the best defence.- The
GODEBUGschedtraceisn't the leak tool; use the pprof goroutine endpoint.
Race detector and atomics
- Always run tests with
-race:go test -race ./.... It finds real races that pass without it and are rare in production. CI must run it. - A data race means undefined behaviour — not "probably fine". Even if it looks atomic on x86, it is not on ARM.
sync/atomic(atomic.Int64,atomic.Bool,atomic.Pointer[T],Add,Load,CompareAndSwap) for simple counters and flags.atomic.Int64has the typed API (Go 1.19+); the oldatomic.AddInt64(&x, 1)is legacy. A mutex is still fine and often clearer; reach for atomics only when a profiler says the lock is contended.- Passing a value through a channel, or protecting it with a mutex, is the normal way to share; an atomic is for a single scalar.
copyof a slice header while another goroutine appends to the backing array is a classic race that-racemay or may not catch depending on timing. Pass slices by value and treat the backing array as immutable, or lock.
Gotchas
- Loop variable capture is fixed only in Go 1.22+ and only if
go.modsaysgo 1.22or higher. Key off the language version, not the toolchain. ctxmust be the first parameter of a blocking function, and passed, not stored in a struct — storing freezes a request context on a long-lived object and cancellation stops working.- A missing
defer cancel()on aWithTimeout/WithCancelleaks the timer and keeps the parent alive.go vetflags this; CI must rungo vet. selectwith two ready cases is nondeterministic. Design so it does not matter, or handle both.- A
forloop with noctx.Done()case, or arangeover a channel that is never closed, is a hang. Every channel a consumer ranges over must be closed by its producer on every path. sync.Mutexmust not be copied by value after first use.time.Tickermust be stopped (defer t.Stop()) or it leaks a runtime timer.time.Afterin a loop allocates a timer per iteration that lives until it fires — prefer a reusedTickerorNewTimerin long loops.- Goroutines leak silently. There is no runtime error, just growing memory
and goroutine count. Test for them (
goleak), do not wait for production. errgroup.Waitreturns only the first error; if you need to know about several failures, collect them explicitly (e.g.errors.Join).- Closing a channel does not stop a goroutine blocked sending on it. The sender panics; the receiver drains. A cancellation that closes the wrong direction is a panic, not a shutdown.
panicin a goroutine you spawned kills the whole process unless yourecoverinside that goroutine (not in the parent). Seego-error-handling.recoveronly works in a deferred function directly in the panicking goroutine; it does not propagate to the parent goroutine.
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.

