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.

Introduction & Quick Summary
The program dies with a panic that names the operation, not the owner:
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 +0x1d6A 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
donechannel while a sender still holds a reference. - A
forloop 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.
// 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:
| Panic | Meaning | Where to look |
|---|---|---|
send on closed channel | a send ran after close | who else holds this channel |
close of closed channel | close ran twice | deferred closes and loop closes |
close of nil channel | closing an uninitialized channel | the struct field was never made |
all goroutines are asleep - deadlock! | nobody can proceed | a send with no receiver, or a receive with no sender |
assignment to entry in nil map | not a channel, but same class of shared-state panic | map initialization |
The correct shape, with one owner and a bounded producer:
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
| Pattern | Who closes | Stops producers how |
|---|---|---|
| Single producer, many consumers | the producer | defer close(out) when the loop ends |
| Many producers, one consumer | a separate closer goroutine | sync.WaitGroup waits, then close |
| Fan-out worker pool | the dispatcher | it closes the jobs channel after the last send |
| Cancellation signal | the owner of the context | cancel() instead of close(done) |
| Broadcast to many receivers | the owner, once | close is the signal, never a send |
| Request-scoped pipeline | the handler | context cancellation on return |
Choosing the shutdown tool:
| Tool | Guarantees | Cost |
|---|---|---|
close(ch) | receivers see the end immediately | panics if closed twice |
sync.WaitGroup | all goroutines finished | needs correct Add before Go |
context.Context | cancellation propagates to children | one extra parameter per function |
errgroup.Group | first error plus cancellation | an extra dependency on golang.org/x/sync |
sync.Once | close runs at most once | hides 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.
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.
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.
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.
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.
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 documentationThe Go documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit Go work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Go guides
All Go guidesGo: x509 certificate signed by unknown authority
Go cannot build a chain to a trusted root: no CA bundle in the image, a private CA, or a missing intermediate. Install roots or set RootCAs.
Go: fatal error: concurrent map writes in goroutines
The runtime catches two writes to one map and stops the process. Guard access with a mutex, use sync.Map for caches, or give one owner.
Go: import cycle not allowed
Go forbids cycles in the package import graph. Break them by extracting shared types, declaring interfaces where consumed, or inverting init registration.
Go: http: superfluous response.WriteHeader call
net/http logs this when a handler writes the status twice. It almost always marks a later status write that was silently ignored, or no return.
More in Go
All Go guidesThe guides filed next to this one in Go, in library order.