Channels or Mutexes? How to Prompt an LLM to Pick the Right Go Concurrency Tool — and Prove It Won't Deadlock

You've got a select that's been stuck for three days. Or a WaitGroup that panics with "negative counter". Or a goroutine that's been quietly leaking since the last deploy. You ask an LLM to "fix the concurrency" and it hands you back a beautiful, idiomatic-looking chunk of code that compiles, passes go vet, and deadlocks in production.

The problem isn't the model. It's the prompt. Asking for "concurrent code" gets you a plausible pattern. Asking for a decision — channels or mutexes, select or errgroup — and then demanding the model prove the choice against races, leaks, and stuck selects gets you something you can actually ship.

This is a roundup of prompts for Go developers who want the second thing. Each prompt targets a specific decision point in concurrent Go, and each one is built to make the LLM reason about why a primitive fits, not just generate boilerplate.

First, the fork in the road: event stream or shared state?

Before you write a single prompt, you need to know which side of the fence you're on. The Go community's advice — "use channels for communication, mutexes for state" — is right, but it's too abstract to act on. Here's the concrete version I use:

Your situation Reach for Why
A stream of events arriving from outside (HTTP requests, queue messages, sensor readings) Channels + select You need backpressure: a full channel blocks the producer, which is exactly what you want when downstream is slow
A piece of state read and written by many goroutines (a cache, a counter, a connection pool) sync.Mutex / sync.RWMutex You want to guard access, not pass ownership. Channels here add ceremony without benefit
A fan-out of N tasks where you need to wait for all of them and collect the first error errgroup.Group It bundles WaitGroup semantics with context cancellation and error propagation
A single background job that must stop when the request is cancelled context.Context + one goroutine The context is the cancellation signal; no channel needed

The trap is mixing them. A Mutex guarding a channel. A select with a default branch that busy-loops. An errgroup whose ctx is never checked inside the goroutine. Each of these looks fine in isolation and breaks under load.

The one question that picks the primitive Ask yourself: am I moving data, or protecting data? Moving → channels and select. Protecting → mutexes and errgroup. If you can't answer in one sentence, you don't understand the problem yet, and neither will the LLM.

Prompt 1: Make the LLM choose the primitive, not the pattern

Most prompts say "write a concurrent function that does X." That invites the model to pick whatever pattern is most common in its training data — usually channels, because Go tutorials love them. This prompt flips it: you give the situation, and the model has to justify the choice.

When to use it: at design time, before you write code. Especially when you're unsure whether a channel is overkill.

Prompt:

You are a Go concurrency reviewer. I will describe a problem. Do NOT write code yet.

Problem: [describe your situation — e.g., "I have an HTTP handler that reads from a shared in-memory cache of user sessions. Multiple goroutines read and occasionally write. Writes are rare (maybe once per minute per user). Reads are frequent."]

Do the following, in order:

1. Classify the problem as either "event stream / data movement" or "shared state / data protection". State which one and why in one sentence.
2. Based on that classification, recommend ONE primary primitive: channels+select, sync.Mutex, sync.RWMutex, errgroup, or context alone. Do not hedge — pick one.
3. Name the single biggest failure mode of your choice in this specific scenario (deadlock, race, leak, or starvation).
4. Tell me what would have to change in my problem description for your recommendation to flip to a different primitive.

Keep the whole answer under 200 words. No code.

Example output you should expect (for the cache case above):

Classification: shared state. Multiple goroutines access the same map; there is no stream of events to move between them.
Recommendation: sync.RWMutex. Reads dominate, so RLock lets them proceed in parallel; writes take the exclusive lock.
Biggest failure mode: lock contention under a write storm — if writes become frequent, RWMutex degrades and a plain Mutex or a sharded map may be faster.
What would flip it: if sessions arrived as a stream from a queue and each goroutine owned a disjoint set, channels would fit better.

That last line — "what would flip it" — is the part most prompts miss. It forces the model to articulate the boundary, which is exactly the boundary you'll hit in six months when requirements change.

Prompt 2: Stress-test a select before it hangs

A select that hangs is one of the nastiest bugs in Go because it doesn't crash — it just stops. The goroutine sits there, the request times out upstream, and you get a 504 with no stack trace pointing at the culprit.

This prompt makes the LLM walk through every branch of your select and name the condition under which the whole thing blocks forever.

When to use it: any time you have a select with more than two cases, or any select inside a loop.

Prompt:

Here is a Go function containing a select statement:

```go
[paste your function]

```

Analyze the select for deadlock and starvation. For each case in the select, answer:

- Under what condition is this case never ready?
- If ALL cases are simultaneously not ready, what happens? (block forever / proceed via default / panic)
- Is there a `default` branch? If yes, does it busy-loop (i.e., can the loop spin without blocking)?

Then answer these three questions:

1. Can this select block forever if the context is cancelled? Trace the path.
2. Is there a send on a channel that could have no receiver? Name the line.
3. If this select is inside a `for` loop, does the loop have a termination condition that is reachable when all channels are closed?

Output a numbered list of findings, each with the line number and a one-sentence fix. If you find no issues, say "no issues found" and explain what you checked.

Why this works: the model can't hand-wave. "Under what condition is this case never ready" forces it to reason about channel state, not pattern-match. In my experience, the third question — loop termination when all channels close — catches the most real bugs, because it's the one humans forget when they add a new channel to an existing select.

The `default` branch is a lie A `select` with `default` never blocks, which sounds safe. But inside a `for` loop it becomes a busy-wait that pegs a CPU core. If you need non-blocking behavior, ask the LLM to add a `time.Sleep` or a `time.After` — or better, remove the `default` and let the select block as intended.

Prompt 3: Find the race the compiler won't

go test -race catches races that actually execute during the test. It does not catch races in code paths your tests don't hit. The LLM can read the code and reason about potential races statically — not as well as a formal analyzer, but well enough to flag the obvious ones before they reach CI.

When to use it: on any struct that has both a sync.Mutex and exported methods, and on any goroutine that captures a loop variable.

Prompt:

Review this Go code for data races. I will paste a struct and its methods.

```go
[paste struct and methods]

```

For each field in the struct, tell me:

- Is it read or written outside a lock anywhere in this code? Quote the line.
- Is it captured by a goroutine or closure? If yes, is the capture by value or by reference?

Then check specifically for these three classic Go race patterns:

1. A loop variable captured by a goroutine launched inside the loop (pre-Go 1.22 semantics — note if the code relies on the old behavior).
2. A method that reads a field under `RLock` but a sibling method writes it under `Lock` — is the lock type consistent?
3. A `sync.WaitGroup` where `Add` is called inside the goroutine instead of before it.

For each finding, give: the line, the race, and a minimal fix. Do not rewrite the whole file — show only the changed lines.

Example: suppose you have a Cache struct with a map[string]string and a sync.Mutex. One method, Get, does c.mu.Lock() then reads the map. Another, Snapshot, iterates the map without locking at all. The model should flag Snapshot line by line and suggest wrapping the iteration in c.mu.Lock(). If it doesn't, your prompt was too vague — add "quote the line" explicitly, as above.

If you want a deeper walkthrough of turning race detector output into an actual diagnosis, there's a separate piece on that: Your Goroutines Don't Leak — Your Assumptions Do: 12 LLM Prompts That Turn pprof Output and Race Reports Into an Actual Diagnosis.

Prompt 4: Decide between errgroup and a hand-rolled WaitGroup

errgroup.Group is not just a WaitGroup with error handling. It also cancels the context when the first goroutine returns an error, which changes the semantics of everything downstream. Teams often reach for WaitGroup because it's simpler, then bolt on error collection with a mutex-guarded slice, and end up with a race on the slice and no cancellation.

This prompt makes the LLM compare the two for your specific case and commit to one.

When to use it: any fan-out where you spawn more than two goroutines and need to wait for all of them.

Prompt:

I need to run N tasks concurrently and wait for all of them. Here is my current code:

```go
[paste your WaitGroup-based code]

```

Answer these questions:

1. Does my code collect errors from the goroutines? If yes, how — and is that collection itself race-free?
2. If one goroutine fails, do the others keep running to completion, or should they be cancelled? (State the desired behavior for my use case: [describe — e.g., "if one task fails, the rest are pointless and should stop"].)
3. Given the answer to (2), is `errgroup.Group` a better fit than `sync.WaitGroup`? Justify in two sentences.
4. If `errgroup` is better, rewrite the code using `errgroup.WithContext`. If not, explain why `WaitGroup` is correct here.

Do not use `errgroup` just because it's newer. If `WaitGroup` is correct, say so.

The non-obvious part: errgroup.WithContext cancels the context on the first error, but the goroutines must check that context to actually stop. If your task is a tight CPU loop with no ctx.Done() check, errgroup gives you cancellation semantics that don't cancel anything. The prompt above forces the model to surface that gap — if it rewrites to errgroup without adding a select { case <-ctx.Done(): return ctx.Err()... } inside the goroutine, the rewrite is cosmetic.

Prompt 5: The leak audit — who owns this goroutine?

A goroutine leak is a goroutine that never exits. It doesn't crash; it just accumulates. After a week, you have 40,000 goroutines and the scheduler spends more time context-switching than working.

The only reliable way to prevent leaks is to answer, for every go func(), the question: what makes this goroutine return? This prompt makes the LLM answer that for every launch site in a file.

When to use it: as a pre-merge check on any file that contains go (the keyword). Also useful when runtime.NumGoroutine() keeps climbing in staging.

Prompt:

Here is a Go file. Find every `go` statement (goroutine launch).

```go
[paste file]

```

For each launch, produce a table row with these columns:

| Line | Goroutine does | Exits when | Can it leak? | Fix if leaky |

"Exits when" must name a concrete condition — a channel close, a context cancellation, a return from a bounded loop, or "never" (which is a leak by definition).

"Can it leak?" is Yes/No. Mark Yes if any of these is true:

- The goroutine sends on an unbuffered channel with no guaranteed receiver.
- The goroutine waits on a channel that is never closed.
- The goroutine loops on `for { }` with no `return` or `break` reachable from a cancellation signal.

After the table, give me the total count of goroutines and the count of leaky ones. If the leaky count is zero, say so explicitly.

Why a table: the model is much less likely to skip a launch site when it has to fill a row. In practice, a file with five go statements often yields one or two "Yes" rows — usually a fire-and-forget goroutine that sends on a result channel with a buffer of 1 but no default case, so if the caller has already returned, the send blocks forever.

If the audit turns up leaks that only show under load, pprof is the next step. The prompt kit for reading pprof output through an LLM is here: Goroutines, Mutexes and Context: The LLM Prompt Stack That Keeps Data Races Out of Production.

Prompt 6: Make the LLM explain why select depends on context

This is the prompt I use when I'm onboarding someone to a Go codebase and they ask, "why does every function take a ctx?" It's also the prompt that finally made select click for me — not as a language feature, but as the mechanism that ties cancellation to I/O.

When to use it: when you're reviewing code that mixes context and select and you want to confirm the author understood the interaction, not just copied it. Or when you're the author and you're not sure.

Prompt:

Explain the relationship between `context.Context` and `select` in Go, using this function as the example:

```go
[paste a function that does select on ctx.Done() and another channel]

```

Answer in this order:

1. What does `ctx.Done()` return, and what is its state before cancellation vs after?
2. In the select, which case fires when the context is cancelled? What does the function do then?
3. If the other channel in the select is also ready at the same moment as `ctx.Done()`, which case wins? (Be precise about Go's select semantics.)
4. What would happen if this function did NOT select on `ctx.Done()` — trace the behavior when the caller cancels.

Then give me one sentence I can put in a code comment explaining why the select is there.

The answer to (3) matters more than it looks. Go's select chooses uniformly at random among ready cases. So if ctx.Done() and your data channel are both ready, the function might process one more item after cancellation — or might not. That non-determinism is fine if your handler is idempotent, and a bug if it isn't. The prompt forces the model to say this out loud, which is the difference between "I copied the pattern" and "I know what it does."

Where this breaks: the limits of LLM concurrency review

These prompts are good at structural problems: a missing lock, a select with no exit, a goroutine with no owner. They are bad at timing problems — races that only manifest under specific interleavings, deadlocks that require three goroutines to hit a particular order, and performance issues where the lock is correct but contended.

Here's how to tell which case you're in:

  • The LLM found it by reading the code → trust it, verify with a test. Structural issues are visible in the source. Write a test that exercises the path, run go test -race, and confirm the fix.
  • The LLM says "this looks fine" → do not trust it. "Looks fine" from a model means "I didn't find a pattern I recognize." Run go test -race -count=100 on the relevant package, and if you have a staging environment, run a load test. The race detector only catches races that execute, so more iterations = more coverage.
  • The bug only appears in production → the LLM is the wrong tool. Go to pprof and runtime/trace first. A goroutine dump at the moment of the hang tells you more than any prompt. Once you have the dump, then bring it to the LLM with Prompt 5 or the pprof-specific prompts linked above.
The prompt is a reviewer, not a proof An LLM can tell you where a race could happen. It cannot prove one won't. Treat every "no issues found" as a hypothesis to test with -race and a load test, not as a clean bill of health.

The short version

If you remember nothing else: the choice between channels and mutexes is not a style preference, it's a statement about whether you're moving data or protecting it. Channels and select are for streams and backpressure. Mutexes and errgroup are for shared state and group coordination. context is the thread that ties cancellation to both.

The prompts above are built to make the LLM reason about that choice — and then attack its own reasoning. Prompt 1 picks the primitive. Prompt 2 stress-tests the select. Prompt 3 hunts races. Prompt 4 settles errgroup vs WaitGroup. Prompt 5 audits for leaks. Prompt 6 explains the context-select link so you can defend it in a code review.

Run them before the merge, not after the incident. And when the LLM says "looks fine," run go test -race -count=100 anyway — the model is a second pair of eyes, not a substitute for the race detector.

For a broader stack of Go-specific prompts — context timeouts, graceful shutdown, and idiomatic error handling — see Go, LLM, and the Race Against Races: How to Prompt for Idiomatic Concurrency, Explicit Errors, and Context-Aware Code.

AssetMaterials for this article

A document from this article — download and apply it.

  • XLSXGo Concurrency Primitive Decision Worksheet.xlsxXLSX · 6.9 KBDownload
← All posts

Ask AI about this article

Ask a question about this article — ASI Biont will answer based on its text and the attached files.