Cursor rules for safe Go concurrency with exit plans for goroutines, errgroup limits, cancellable worker pools, deliberate channel or lock choice and race-detector tests.
.cursor/rules/go-concurrency-patterns.mdc. Downloaded files need to be placed in that repository path.---
description: "Cursor rules for safe Go concurrency with exit plans for goroutines, errgroup limits, cancellable worker pools, deliberate channel or lock choice and race-detector tests."
globs: "**/*"
alwaysApply: false
---
# Go Concurrency Patterns
Applies to: Go code that starts goroutines, uses channels, `sync` primitives or `context`, and its tests.
Version baseline: checked against Go 1.27 (per-iteration loop variables since 1.22, `sync.WaitGroup.Go` since 1.25). Read `go.mod` and do not use features newer than its `go` directive. Snippets omit import blocks.
## 1. Start goroutines only with an exit plan
- Before writing `go f()`, decide who waits for it and how it stops: work finishes, the context is cancelled, or an input channel is closed.
- Use goroutines for independent blocking work (I/O, RPCs) or CPU work you have measured; do not wrap fast synchronous code in goroutines.
- Never start a goroutine from a library function without letting the caller wait for or cancel it.
## 2. Wait for groups of goroutines
- No error to collect: `sync.WaitGroup`. On Go 1.25+, `wg.Go(f)` replaces the `Add(1)`/`defer Done()` pair.
- Errors, and stop on the first one: `golang.org/x/sync/errgroup` with `errgroup.WithContext`; bound parallelism with `g.SetLimit(n)`.
```go
func FetchAll(ctx context.Context, urls []string) ([][]byte, error) {
results := make([][]byte, len(urls))
g, ctx := errgroup.WithContext(ctx)
g.SetLimit(4)
for i, u := range urls {
g.Go(func() error {
body, err := fetch(ctx, u) // must honor ctx
if err != nil {
return fmt.Errorf("fetch %s: %w", u, err)
}
results[i] = body // each goroutine writes its own index: no lock needed
return nil
})
}
if err := g.Wait(); err != nil {
return nil, err
}
return results, nil
}
```
## 3. Honor context cancellation
- Take `ctx context.Context` as the first parameter of any function that blocks.
- Every blocking channel send or receive in a long-lived goroutine sits in a `select` with `<-ctx.Done()`.
- Set deadlines at the edge (`context.WithTimeout`) and always call the returned `cancel`.
## 4. Worker pools
Use a pool when you need a fixed number of long-lived workers consuming a stream; for a known slice of tasks, `errgroup` with `SetLimit` is simpler.
```go
func Pool(ctx context.Context, workers int, jobs <-chan Job, handle func(context.Context, Job) Result) <-chan Result {
out := make(chan Result)
var wg sync.WaitGroup
for range workers {
wg.Go(func() {
for {
select {
case <-ctx.Done():
return
case job, ok := <-jobs:
if !ok {
return
}
select {
case out <- handle(ctx, job):
case <-ctx.Done():
return
}
}
}
})
}
go func() { wg.Wait(); close(out) }()
return out
}
```
- The sender closes a channel, never the receiver; close it exactly once.
- Return receive-only (`<-chan`) and accept send-only (`chan<-`) channel types to document direction.
## 5. Choose channels or locks deliberately
- Channels for handing off ownership of data or signaling events; `sync.Mutex`/`RWMutex` for protecting a shared structure; `sync/atomic` types for single counters and flags.
- Keep critical sections short, use `defer mu.Unlock()`, and never hold a lock while blocking on a channel or network call.
- Use `sync.Once` (or `sync.OnceValue`) for lazy initialization.
## 6. Avoid goroutine leaks
Common causes: a send on an unbuffered channel nobody receives (for example after the receiver returned early on error), a `range` over a channel that is never closed, and a missing `cancel()`. Give result channels a buffer equal to the number of senders when the receiver may stop early, or select on `ctx.Done()` when sending.
## 7. Test concurrent code
- Run tests with the race detector: `go test -race ./...`.
- Test cancellation paths: cancel the context and assert the function returns promptly with `context.Canceled`.
- For time-based code, use `testing/synctest` (Go 1.25+) or injectable clocks instead of `time.Sleep` in tests.
- Use `go.uber.org/goleak` in `TestMain` if the project already depends on it, to fail tests that leave goroutines running.
## Verify before finishing
Run these when they are available in the project:
- `go vet ./...` (reports copied locks and other misuse)
- `go test -race ./...`
- `staticcheck ./...` or `golangci-lint run`, if configured
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.
Cursor
language
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
A Go 1.27 service has this rule attached while a developer asks Cursor to fetch many URLs in parallel and to add a background worker pool.
Write FetchAll(ctx, urls) that fetches at most 4 URLs at a time, returns results in input order and stops on the first failure. Also add a 3-worker pool that consumes jobs from a channel until it is closed or ctx is cancelled.
Illustrative; not a recorded model run. FetchAll using errgroup.WithContext with SetLimit(4), writing each result to its own slice index without a lock, wrapping errors with the URL and passing the derived ctx to fetch; a Pool returning <-chan Result that uses WaitGroup.Go (or Add/Done before 1.25), selects on ctx.Done() for both receive and send, and closes the output channel once after all workers exit; tests run with -race, including a cancellation test.
Cursor applies project rules stored as .mdc files in .cursor/rules. Each rule's frontmatter (description, globs, alwaysApply) decides whether it is always included, attached to matching files, chosen by the agent from its description, or only used when you @-mention it. Cursor also reads AGENTS.md in the project root and subdirectories for plain-Markdown instructions.
.cursor/rules/go-concurrency-patterns.mdcStarting point, not a tested configuration for your repository. Attached when files matching the globs are in context (alwaysApply: false with globs). Review the instructions, adapt the file paths and run your project's existing checks.
---
description: "Go Concurrency Patterns: errgroup, Worker Pools, Context and Leak-Free Goroutines project conventions"
globs: "**/*"
alwaysApply: false
---
# Go Concurrency Patterns
Applies to: Go code that starts goroutines, uses channels, `sync` primitives or `context`, and its tests.
Version baseline: checked against Go 1.27 (per-iteration loop variables since 1.22, `sync.WaitGroup.Go` since 1.25). Read `go.mod` and do not use features newer than its `go` directive. Snippets omit import blocks.
## 1. Start goroutines only with an exit plan
- Before writing `go f()`, decide who waits for it and how it stops: work finishes, the context is cancelled, or an input channel is closed.
- Use goroutines for independent blocking work (I/O, RPCs) or CPU work you have measured; do not wrap fast synchronous code in goroutines.
- Never start a goroutine from a library function without letting the caller wait for or cancel it.
## 2. Wait for groups of goroutines
- No error to collect: `sync.WaitGroup`. On Go 1.25+, `wg.Go(f)` replaces the `Add(1)`/`defer Done()` pair.
- Errors, and stop on the first one: `golang.org/x/sync/errgroup` with `errgroup.WithContext`; bound parallelism with `g.SetLimit(n)`.
```go
func FetchAll(ctx context.Context, urls []string) ([][]byte, error) {
results := make([][]byte, len(urls))
g, ctx := errgroup.WithContext(ctx)
g.SetLimit(4)
for i, u := range urls {
g.Go(func() error {
body, err := fetch(ctx, u) // must honor ctx
if err != nil {
return fmt.Errorf("fetch %s: %w", u, err)
}
results[i] = body // each goroutine writes its own index: no lock needed
return nil
})
}
if err := g.Wait(); err != nil {
return nil, err
}
return results, nil
}
```
## 3. Honor context cancellation
- Take `ctx context.Context` as the first parameter of any function that blocks.
- Every blocking channel send or receive in a long-lived goroutine sits in a `select` with `<-ctx.Done()`.
- Set deadlines at the edge (`context.WithTimeout`) and always call the returned `cancel`.
## 4. Worker pools
Use a pool when you need a fixed number of long-lived workers consuming a stream; for a known slice of tasks, `errgroup` with `SetLimit` is simpler.
```go
func Pool(ctx context.Context, workers int, jobs <-chan Job, handle func(context.Context, Job) Result) <-chan Result {
out := make(chan Result)
var wg sync.WaitGroup
for range workers {
wg.Go(func() {
for {
select {
case <-ctx.Done():
return
case job, ok := <-jobs:
if !ok {
return
}
select {
case out <- handle(ctx, job):
case <-ctx.Done():
return
}
}
}
})
}
go func() { wg.Wait(); close(out) }()
return out
}
```
- The sender closes a channel, never the receiver; close it exactly once.
- Return receive-only (`<-chan`) and accept send-only (`chan<-`) channel types to document direction.
## 5. Choose channels or locks deliberately
- Channels for handing off ownership of data or signaling events; `sync.Mutex`/`RWMutex` for protecting a shared structure; `sync/atomic` types for single counters and flags.
- Keep critical sections short, use `defer mu.Unlock()`, and never hold a lock while blocking on a channel or network call.
- Use `sync.Once` (or `sync.OnceValue`) for lazy initialization.
## 6. Avoid goroutine leaks
Common causes: a send on an unbuffered channel nobody receives (for example after the receiver returned early on error), a `range` over a channel that is never closed, and a missing `cancel()`. Give result channels a buffer equal to the number of senders when the receiver may stop early, or select on `ctx.Done()` when sending.
## 7. Test concurrent code
- Run tests with the race detector: `go test -race ./...`.
- Test cancellation paths: cancel the context and assert the function returns promptly with `context.Canceled`.
- For time-based code, use `testing/synctest` (Go 1.25+) or injectable clocks instead of `time.Sleep` in tests.
- Use `go.uber.org/goleak` in `TestMain` if the project already depends on it, to fail tests that leave goroutines running.
## Verify before finishing
Run these when they are available in the project:
- `go vet ./...` (reports copied locks and other misuse)
- `go test -race ./...`
- `staticcheck ./...` or `golangci-lint run`, if configured
Ask for a small change to one matching file. Check the tool's loaded context or instruction view, inspect the diff for the requested convention, and run the relevant build or test. A well-formatted file does not guarantee the model follows every instruction.
Cursor's docs recommend keeping individual rules under 500 lines and splitting large rules into composable ones. Cursor's documentation states that it supports AGENTS.md in the project root and in subdirectories. Use AGENTS.md for plain-Markdown instructions you also want other tools to read, and .mdc rules when you need Cursor's scoping options (globs, description-based selection, always-apply).
Documentation checked 2026-11-05: Cursor docs: Rules
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.