Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Go: panic send on closed channel and how to close safely

A sender writes to a channel another goroutine already closed. Learn the close ownership rule, fan-in patterns, and how to make shutdown deterministic.

~5 min readGo
#go#concurrency#channels#panics
Bold white headline reading CLOSED CHANNEL with a Go channel crate shut at a cyan gate while an amber sender arrives.

Introduction & Quick Summary

The program dies with a panic that names the operation, not the owner:

code
panic: send on closed channel goroutine 24 [running]: main.worker(0xc0000b4000) /app/pool.go:38 +0x2c created by main.main in goroutine 1 /app/main.go:22 +0x1d6

A channel can be closed exactly once, and sending to a closed channel panics. The goroutine in the trace is the sender. The close happened somewhere else, usually earlier and on a different goroutine, which is why the stack alone does not show the cause.

Where it appears:

  • A worker pool where a receiver closes the jobs channel when it stops.
  • A fan-in loop where several producers send and one of them closes the shared channel.
  • A cancellation path that closes a done channel while a sender still holds a reference.
  • A for loop that starts goroutines capturing the same channel and closes it inside the loop.
  • A deferred close(ch) that runs twice because the function is called twice.

Quick answer: decide which goroutine owns the channel, let only that goroutine close it, and let every other goroutine stop sending before the close happens.

Core Mechanics, Signatures & Reproducible Setup

A channel has three operations with different panic rules. close twice panics. send after close panics. receive after close returns the zero value and ok == false immediately, which is why receivers cannot detect the danger and senders cannot be warned.

go
// repro.go -- run with: go run repro.go package main import ( "fmt" "sync" ) func main() { jobs := make(chan int) var wg sync.WaitGroup wg.Add(1) go func() { defer wg.Done() for j := range jobs { fmt.Println("job", j) } }() for i := 0; i < 3; i++ { jobs <- i } close(jobs) // receiver is still ranging; a later send panics go func() { jobs <- 99 }() // panic: send on closed channel wg.Wait() }

The panic output includes every goroutine's stack, so the trace tells you what the sender was doing. The family of channel panics:

PanicMeaningWhere to look
send on closed channela send ran after closewho else holds this channel
close of closed channelclose ran twicedeferred closes and loop closes
close of nil channelclosing an uninitialized channelthe struct field was never made
all goroutines are asleep - deadlock!nobody can proceeda send with no receiver, or a receive with no sender
assignment to entry in nil mapnot a channel, but same class of shared-state panicmap initialization

The correct shape, with one owner and a bounded producer:

go
func produce(ctx context.Context) <-chan int { out := make(chan int) go func() { defer close(out) // only this goroutine closes for i := 0; ; i++ { select { case out <- i: case <-ctx.Done(): return } } }() return out }

Key Comparison Table

PatternWho closesStops producers how
Single producer, many consumersthe producerdefer close(out) when the loop ends
Many producers, one consumera separate closer goroutinesync.WaitGroup waits, then close
Fan-out worker poolthe dispatcherit closes the jobs channel after the last send
Cancellation signalthe owner of the contextcancel() instead of close(done)
Broadcast to many receiversthe owner, onceclose is the signal, never a send
Request-scoped pipelinethe handlercontext cancellation on return

Choosing the shutdown tool:

ToolGuaranteesCost
close(ch)receivers see the end immediatelypanics if closed twice
sync.WaitGroupall goroutines finishedneeds correct Add before Go
context.Contextcancellation propagates to childrenone extra parameter per function
errgroup.Groupfirst error plus cancellationan extra dependency on golang.org/x/sync
sync.Onceclose runs at most oncehides a design problem if overused

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. Find the closer from the trace

The panic names the sender and its line. The next step is to find every close on that channel and every send.

bash
grep -rn "close(.*jobs" --include=*.go . grep -rn "<- *jobs\|jobs *<-" --include=*.go .

Search the codebase with Regex to list both sites, then compare with the goroutine trace: the closer that is not the owner is the bug. In the reproduction above, the receiver's range loop does not close anything, and the extra goroutine that sends is the sender that panicked.

2. Single owner closes: dispatcher pattern

The dispatcher sends all jobs, closes the channel, and workers only receive. No worker can panic because none of them sends.

go
func dispatch(ctx context.Context, jobs []Job, workers int) error { ch := make(chan Job) var wg sync.WaitGroup wg.Add(workers) for i := 0; i < workers; i++ { go func() { defer wg.Done() for job := range ch { process(ctx, job) } }() } for _, job := range jobs { select { case ch <- job: case <-ctx.Done(): close(ch) wg.Wait() return ctx.Err() } } close(ch) wg.Wait() return nil }

Every send happens before the close in program order on one goroutine, so the close is safe. The early return path closes once and waits, which also prevents a worker leak.

3. Fan-in: a closer goroutine waits for all producers

When several goroutines produce into one channel, none of them may close it. A dedicated goroutine waits for all of them and then closes, which is the only point where the channel is known to be idle.

go
func fanIn(sources ...<-chan string) <-chan string { out := make(chan string) var wg sync.WaitGroup wg.Add(len(sources)) for _, src := range sources { go func(s <-chan string) { defer wg.Done() for v := range s { out <- v } }(src) } go func() { wg.Wait() close(out) }() return out }

Pass the channel as a parameter to the goroutine closure. Capturing the loop variable worked differently before Go 1.22, and code copied from older tutorials still closes over the last value.

4. Prefer context cancellation to a hand-rolled done channel

A done channel closed by a timer, an HTTP handler, and a shutdown hook is a double close waiting to happen. context already handles multiple cancel signals safely.

go
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() out := produce(ctx) for v := range out { use(v) }

cancel is idempotent, so every path can call it. The producer selects on ctx.Done() and returns, and its deferred close(out) runs once. This replaces both the done channel and the risk of closing it twice.

5. Stop the double close at its source

close of closed channel usually comes from a deferred close plus an explicit close, or from a method called twice.

go
type Queue struct { mu sync.Mutex ch chan Item closed bool } func (q *Queue) Close() { q.mu.Lock() if q.closed { q.mu.Unlock() return } q.closed = true q.mu.Unlock() close(q.ch) }

The boolean under a mutex documents the intent and makes Close idempotent without sync.Once hiding the state. Callers then do not need to know whether they are the first to shut down.

Common Compilation/Runtime Mistakes & Version Gotchas

Closing from the receiving side. A receiver cannot know whether senders are still active, so a receiver that closes is the most common cause of this panic. Move the close to the sender side or to a dedicated closer goroutine.

Using recover to swallow the panic. Recovering around a send leaves the pipeline in an unknown state and usually converts a clean crash into a hang or a corrupt result. Fix the ownership instead.

Sending on a nil channel. A nil channel blocks forever on send and receive, which shows up as all goroutines are asleep - deadlock! rather than a panic. Initialize channels in the constructor, not at the point of use.

Ranging over a channel that is never closed. Receivers wait forever and the goroutine leaks. Pair every range ch with a guaranteed close, or select on a context.

Closing to signal many receivers, but also sending on the same channel. Closing is the correct broadcast, but only if nobody sends afterwards. A watchdog that closes a stop channel while a producer still sends to it is the same bug with a different name.

Version differences worth knowing. Go 1.22 changed loop variable semantics, so a goroutine started in a loop now captures its own variable rather than the last one; code written for older versions may close the wrong channel after the upgrade, or work where it used to fail. Go 1.23 and later add range-over-func, which can be used to build iterators that never expose a channel at all, removing this class of bug for simple pipelines.

Testing the fix. Run the test suite with the race detector: go test -race ./... reports the concurrent access even when the timing did not hit the panic. When a refactor moves the close, review the before and after with Diff to confirm that the sending goroutine holds no reference to the closed channel. A test that sends on the channel from several goroutines with -count=100 is usually enough to catch a double close before production does.

Reference material: The Go Programming Language Specification and Effective Go.

Official references

primary documentation

The Go documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit Go work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Go guides

More in Go

All Go guides

The guides filed next to this one in Go, in library order.