You ship a Go service on Friday. On Monday the pager goes off: memory climbs, the process gets OOM-killed, and pprof shows forty thousand goroutines where you expected forty. Or worse — nothing crashes at all. The race detector never ran in CI, the bug only fires under load, and the corrupted counter surfaces weeks later as a wrong invoice.
If you have ever stared at a select that "shouldn't" be blocking, or a context.WithTimeout that somehow leaks a goroutine per request, you already know the real problem: concurrency in Go is easy to write and hard to read. Documentation tells you what sync.Mutex does, not why your specific function deadlocks.
This roundup is a working set of prompts that make an LLM read your Go code the way a senior reviewer would — decompose the goroutine graph, trace every context path, find the leak and the race, and explain why select misbehaves. Organized by difficulty: basic prompts that build the mental model, advanced ones that hunt production bugs, expert ones that make the LLM argue against itself. Each prompt comes with a real task, the exact text to paste, and what a good result looks like.
Stage 1: Before you trust any answer — make the LLM draw the goroutine graph
Most bad concurrency advice starts with the LLM answering a question you didn't ask. Before it diagnoses anything, force it to map your code: which goroutines start, who owns them, who waits on them, and what closes the channel.
This prompt works on a single file or a whole package. The point is that you get a written ownership model you can check against your own understanding before the model starts suggesting fixes.
Task: get an ownership map of every goroutine and channel in a function or file.
Prompt:
You are a Go concurrency reviewer. I will paste a file. Do not suggest any fixes yet.
Produce only this:
1. A table of every goroutine: where it is started (file:line), what it owns, how it is expected to exit, and what would prevent that exit.
2. A table of every channel: buffered or unbuffered, size, who sends, who receives, who closes it, and what happens to senders if the receiver exits first.
3. A list of every context.Context value passed in, and which goroutines observe its Done() channel.
4. One sentence per goroutine stating the ownership rule: "X owns Y and must close it before returning."
If something is ambiguous from the code alone, list it under "Unclear from this file" instead of guessing.
CODE:
<paste file>
What a good result looks like: a table where every goroutine has a named exit condition. If the model writes "exits when done" for a goroutine that reads from a channel nobody closes, that is your leak — the answer itself is the diagnostic.
A realistic output for a worker pool looks like this:
| Goroutine | Started at | Owns | Exits when | Blocked by |
|---|---|---|---|---|
| producer | main.go:41 |
jobs channel |
finishes sending and closes jobs |
never — no early return |
| worker ×4 | main.go:47 |
nothing | jobs is closed and drained |
a send to results when nobody reads |
| collector | main.go:52 |
results channel |
receives len(jobs) items |
never gets the last item |
The third row is the classic shape: workers block on results <- r because the collector returned early on an error. The graph makes it visible in one line.
Stage 2: Find the leak before the load test does
A goroutine leak is not a crash; it is a slow tax. Each leaked goroutine keeps its stack alive (2 KB minimum at start, growing as it runs), and a service handling 500 requests per second with one leaked goroutine per request accumulates 30,000 stacks a minute. Memory grows, the scheduler gets slower, and GOMAXPROCS has to juggle more runnable work.
The basic prompt from Stage 1 tells you where goroutines start. This one tells you which ones never die.
Task: audit a function for goroutines that outlive their caller.
Prompt:
Audit this Go code for goroutine leaks. For each goroutine started, answer:
- What is the ONLY way this goroutine can exit?
- If the caller returns early (error path, panic recovered, ctx cancelled), does that exit condition still get reached?
- Is the exit guaranteed by a defer, by a channel close, or by nothing at all?
Then rank the leaks by how often they would fire in production: every request, only on error, only on shutdown.
For each confirmed leak, write the minimal fix as a unified diff, not prose.
CODE:
<paste>
Example result. Given this common pattern:
func (s *Service) Fetch(ctx context.Context, id string) (Result, error) {
ch := make(chan Result) // unbuffered
go func() {
r, err := s.client.Get(ctx, id)
if err != nil {
return // nobody sends — the caller waits forever
}
ch <- r
}()
select {
case r := <-ch:
return r, nil
case <-ctx.Done():
return Result{}, ctx.Err()
}
}
the model should flag the error path: the goroutine returns without sending, the caller blocks on <-ch until the context expires, and meanwhile the goroutine stack is gone but the caller is stuck. The fix is a buffered channel of size 1 — the goroutine can always send and exit:
ch := make(chan Result, 1)
That one-line change is the difference between a leak on every failed request and a clean exit. The prompt earns its keep by making the LLM show the early-return path explicitly instead of praising the happy path.
Stage 3: Data races — make the LLM prove the race, not guess it
Asking "is there a race in this code?" gets you a confident yes or no with no evidence. The better move is to force the model to construct the interleaving: two goroutines, the exact line order that produces the bad value, and the shared variable between them.
Task: turn a suspected race into a reproducible interleaving.
Prompt:
Here is a Go snippet. Do not answer yes/no. Instead:
1. List every variable written by more than one goroutine without synchronization, and the two goroutine names that touch it.
2. Write the exact interleaving (A reads, B writes, A writes) that produces a wrong result, with line numbers.
3. State whether `go test -race` would catch it deterministically, probabilistically, or not at all — and why.
4. Give a minimal reproducer test that runs the interleaving in a loop and would fail under -race most runs.
CODE:
<paste>
Why the third point matters. The race detector is not a proof. It flags races it actually observes at runtime, so a race that fires once in ten million requests can slip through a green CI run. If the model tells you "-race would catch this every time," it is wrong — and that tells you to distrust the rest of the answer.
A typical finding: a map written from two goroutines. Go's runtime detects concurrent map writes and panics with "concurrent map writes" — but only sometimes, and the panic is not a race report. The prompt forces the model to separate "would panic" from "would be caught by -race" from "would silently corrupt."
For the deeper mechanics of reading race reports and pprof output, the platform has a dedicated breakdown.
More on the topic: “Your Goroutines Don't Leak — Your Assumptions Do: 12 LLM Prompts That Turn pprof Output and Race Reports Into an Actual Diagnosis”.
Stage 4: Context with timeouts that actually cancel the right thing
context.WithTimeout is one of the most pasted, least understood lines in Go. The trap is not the timeout itself — it is that a context passed into a goroutine that ignores it cancels nothing. You get a timeout that returns an error to the caller while the worker keeps hammering the database.
Task: verify that a context actually reaches every blocking operation.
Prompt:
For this function, build a context propagation map:
- Where is the context created, and with what deadline?
- Which calls inside the function take the context, and which blocking calls (channel ops, DB queries, HTTP calls, sleeps) do NOT?
- For each call that ignores the context, name what would keep running after the deadline fires.
Then rewrite the function so every blocking operation observes ctx.Done(), and list every place where you had to choose between a timeout and a cancellation.
CODE:
<paste>
Example result. A function that does time.Sleep(2 * time.Second) inside a worker, with a context that has a 500 ms timeout, will return context.DeadlineExceeded to the caller at 500 ms — but the worker sleeps the full 2 seconds. The prompt should surface this as "the deadline fires, the work does not stop," which is the most common false sense of safety in Go services.
The rewrite usually looks like this:
select {
case <-time.After(2 * time.Second):
// work done
case <-ctx.Done():
return ctx.Err()
}
That is a real change, not a cosmetic one: the goroutine now exits at the deadline instead of holding a stack for 1.5 extra seconds under load.
Stage 5: Why select behaves the way it does
select is where Go concurrency stops being intuitive. Two ready cases, and Go picks one at random — not the first, not the oldest. A default branch turns a blocking select into a spinning busy loop. A closed channel is always ready to receive, which can starve the other cases.
Task: explain the runtime behavior of a specific select statement and predict failures under load.
Prompt:
I have a select statement that behaves unexpectedly under load. Do not rewrite it yet.
1. For each case, state the exact runtime condition that makes it ready.
2. If two or more cases are ready simultaneously, explain which one Go picks and why (be precise about the runtime rule).
3. Identify any case that becomes permanently ready (closed channel, default branch) and describe the starvation it causes.
4. Give a scenario — number of goroutines, timing — where this select drops work or spins the CPU.
5. Only then propose a fix.
CODE:
<paste>
Example result. For a select with a closed done channel and a default branch, the model should tell you the loop spins at 100% CPU because done is always ready and default fires the moment nothing else is — and that the fix is to break out of the loop on done rather than fall through to default.
Another frequent case: a worker reading from two channels where one is closed first. The closed channel is always ready, so the select keeps picking it and the other channel's work starves. The prompt's value is making the model state the runtime rule (random choice among ready cases) before it explains your specific bug — that ordering is what separates a real diagnosis from a lucky guess.
For a full prompt stack on context, timeouts, and graceful shutdown in Go microservices, there is a companion piece.
More on the topic: “Go, LLM, and the Race Against Races: How to Prompt for Idiomatic Concurrency, Explicit Errors, and Context-Aware Code”.
Stage 6: Make the LLM argue against its own fix
By now the model has proposed fixes. The expert move is to make it defend them. This is where most hallucinated "fixes" collapse: the model suggests a mutex, you ask whether the lock is held across a channel send, and it discovers its own deadlock.
Task: adversarial review of a proposed concurrency fix.
Prompt:
You proposed this fix earlier. Now argue against it as a hostile reviewer.
- Does the fix hold a lock across a channel send, a network call, or a blocking operation? Show the exact line.
- Can the fix introduce a deadlock if two goroutines acquire the same locks in different orders? Write the two orderings.
- Does the fix change the goroutine's exit condition? If yes, prove it still exits on every path, including panic.
- If the fix uses sync.Map or atomic, explain what consistency guarantee it actually gives and what it does NOT.
If you cannot refute your own fix, say so explicitly and name the one assumption the fix depends on.
FIX:
<paste the diff>
Why this works. A locked mutex held across a channel send is the single most common deadlock source in Go codebases, and it is invisible unless someone traces the lock's lifetime across the send. Forcing the model to write both lock orderings makes the deadlock concrete. If it cannot, the fix is probably sound — and you have a reason to trust it beyond "the LLM said so."
Stage 7: End-to-end — a checklist that survives code review
Single prompts catch single bugs. The last stage is a review checklist you can run on every PR that touches concurrency. This is the prompt that turns the whole stack into a habit.
Task: a repeatable pre-merge review for concurrent Go code.
Prompt:
Review this diff for concurrency safety as a merge gate. Answer each line PASS, FAIL, or N/A with the reason and the file:line.
1. Every goroutine has a named exit condition reachable on all paths, including error and panic.
2. Every channel has exactly one owner that closes it, and no sender can block forever.
3. Every context is either passed to all blocking calls or explicitly documented as intentionally detached.
4. No mutex is held across a channel send, network call, or unbounded loop.
5. No shared variable is written by two goroutines without a lock, atomic, or channel handoff.
6. Every select has a defined behavior when two cases are ready, and no case is permanently ready.
If any line is FAIL, do not approve. Output a table, then the minimal diff for each FAIL.
DIFF:
<paste>
Example result. A table with six rows, four PASS and two FAIL — say, line 3 (a context.Background() used inside a request handler that should inherit the request context) and line 5 (a counter incremented from a goroutine without atomic). The minimal diffs are the deliverable, and they slot straight into the PR.
Run this on the diff, not the whole repository — the checklist is about what changed, and a whole-repo run buries the new race under old noise.
For the broader Go pair-programming angle — idiomatic style, error handling, and race hunting in one workflow — there is a related collection.
More on the topic: “From Idiomatic Go to Data Race Hunting: 12 Prompts That Turn an LLM Into a Go Pair Programmer”.
What changes when you prompt this way
The difference is not the model — it is the shape of the question. "Find the race" gets a confident guess. "Write the interleaving and prove -race would catch it" gets a diagnosis you can verify line by line. The seven stages above are not a library to collect; they are one workflow: map the goroutines, hunt the leak, prove the race, verify the context, explain the select, attack the fix, gate the merge.
Start with Stage 1 on the file that scares you most. If the ownership table comes back with a goroutine that has no exit condition, you have found your next production incident before it happens — and that is the whole point of prompting for concurrency.