Skills DirectorySkills Directory
SkillsLearnSecurityCategoriesDocsBlogPro
Sign InSubmit Skill
Skills Directory

Security-tested agent skills for Claude, coding agents, and AI workflows.

Directory

  • Browse Skills
  • All Skills A–Z
  • Claude Skills
  • Claude Code Skills
  • Agent Skills
  • Categories
  • Authors
  • Submit a Skill

Learn

  • Learn Hub
  • Install Claude Skills
  • Write SKILL.md
  • Skills vs MCP
  • Directories Compared

Security

  • Security
  • Methodology
  • Secure Claude Skills
  • Security Badges
  • Chrome Extension
  • Skill Manager

Company

  • About
  • Community
  • Blog
  • API Docs
  • Advertise

2026 Skills Directory. All rights reserved.

ProTermsPrivacyRefunds
Back to skills

Go Concurrency

ASecurity

Enforces safe Go concurrency — every goroutine has a known stop condition, context propagates cancellation, channel ownership and direction are explicit, and shared state is protected or not shared. Use when writing or reviewing Go that starts goroutines, uses channels, sync primitives, or context, and when the user mentions goroutine leaks, deadlock, data race, WaitGroup, errgroup, select, mutex, worker pool, "-race", or asks "is this concurrent code safe", "why does this hang".

2 stars
0 votes
0 copies
1 views
Added 9/19/2026
developmentgoapi

Works with

api

Security Analysis

A100/100

Scanned 9/19/2026

$npx -y skills add CasLubbers/code-design-skills --skill go-concurrency --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Go Concurrency?

Add the live security badge to your README — it updates automatically with every re-scan.

Security grade badge for Go Concurrency
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/caslubbers-go-concurrency/badge)](https://www.skillsdirectory.com/skills/caslubbers-go-concurrency)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
Files
SKILL.md
---
name: go-concurrency
description: Enforces safe Go concurrency — every goroutine has a known stop condition, context propagates cancellation, channel ownership and direction are explicit, and shared state is protected or not shared. Use when writing or reviewing Go that starts goroutines, uses channels, sync primitives, or context, and when the user mentions goroutine leaks, deadlock, data race, WaitGroup, errgroup, select, mutex, worker pool, "-race", or asks "is this concurrent code safe", "why does this hang".
---

# 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.

```go
// 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.

```go
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.

```go
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.

```go
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.

```go
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.

Attribution

CasLubbersCasLubbers
View sourceSee grades on GitHubMore from CasLubbers →
SSkills DirectorySkills Directory

Ship a skill? Prove it's safe.

Free 120-pattern security scan, letter grade, and an embeddable README badge.

Submit a skill

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

Comments (0)

No comments yet. Be the first to comment!

SSkills DirectorySkills Directory

Ship a skill? Prove it's safe.

Free 120-pattern security scan, letter grade, and an embeddable README badge.

Submit a skill

Related Skills

Clean Code

Pragmatic coding standards - concise, direct, no over-engineering, no unnecessary comments

304955 votes

Browser Extension Developer

Use this skill when developing or maintaining browser extension code in the `browser/` directory, including Chrome/Firefox/Edge compatibility, content scripts, background scripts, or i18n updates.

285172 votes

Seo Optimizer

SEO optimization with keyword analysis, readability assessment, technical validation, content quality. Use for search rankings, blog posts, content audits, or encountering keyword density, readability scores, meta tags, schema markup errors.

2222 votes

Google Official Seo Guide

Official Google SEO guide covering search optimization, best practices, Search Console, crawling, indexing, and improving website search visibility based on official Google documentation

1862 votes

Tanstack Start

Build a full-stack TanStack Start app on Cloudflare Workers from scratch — SSR, file-based routing, server functions, D1+Drizzle, better-auth, Tailwind v4+shadcn/ui. Use whenever the user mentions TanStack Start, asks to scaffold a full-stack Cloudflare app with SSR, wants an SSR dashboard, or asks for a React 19 + Cloudflare Workers app with file-based routing and server functions — even if they don't name TanStack Start specifically. No template repo — Claude generates every file fresh per ...

10341 votes
View all in development →