Go: fatal error: all goroutines are asleep - deadlock!
The runtime proved every goroutine is blocked. Use the dump's state lines to find the channel or mutex with no counterpart, then fix the ownership.

Introduction & Quick Summary
A Go program stops with a runtime fatal error, not a compile error:
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan receive]:
main.main()
/tmp/x.go:9 +0x2e
exit status 2The runtime decided that no goroutine could ever make progress: every goroutine is blocked on a channel, a mutex, a WaitGroup, or a select with no ready case. Because the Go runtime knows the state of all goroutines, it can prove the program is stuck and abort instead of hanging forever — which is a feature, and the dump it prints is the whole diagnosis.
Quick answer: read the blocked state of each goroutine in the dump, then find the counterpart that should have unblocked it.
goroutine 1 [chan receive]: <- waiting for a value
goroutine 18 [chan send]: <- waiting for a receiver
goroutine 5 [sync.WaitGroup.Wait]: <- waiting for Done()
goroutine 7 [semacquire]: <- waiting for a mutexThe smallest reproducible case, an unbuffered channel with no receiver:
func main() {
ch := make(chan int)
ch <- 1 // blocks forever: nobody receives
}Either receive it (go func() { <-ch }()), buffer it (make(chan int, 1)), or restructure so the send happens where the receiver already waits.
Core Mechanics, Signatures & Reproducible Setup
Channels are synchronous rendezvous points when unbuffered: a send completes only when a receiver is ready, and vice versa. Buffered channels decouple the two up to the buffer size, then block again. WaitGroup.Wait blocks until the counter reaches zero, and a sync.Mutex blocks a second Lock until the first Unlock.
The runtime's deadlock detector has one important limitation: it fires only when every goroutine is blocked with no timer, no network poller, and no signal — that is, when nothing external can wake anything up. A program with a live HTTP server or a time.After pending will never be declared deadlocked; it hangs instead, which is why "all goroutines are asleep" is a diagnosis you get in tests and small programs far more often than in servers.
Reproduce the four classic shapes:
// 1. unbuffered send with no receiver
ch := make(chan int); ch <- 1
// 2. WaitGroup waiting for a Done that was never called
var wg sync.WaitGroup
wg.Add(1)
wg.Wait()
// 3. mutex locked twice in one goroutine (sync.Mutex is not reentrant)
var mu sync.Mutex
mu.Lock(); mu.Lock()
// 4. receive from a channel nobody writes to
ch := make(chan int)
<-chEach of these prints the same first line and a different goroutine state, so the dump identifies which one you have without a debugger.
Key Comparison Table
The dump's state line is the classification:
| Dump state | Blocked on | Usual mistake | Fix |
|---|---|---|---|
[chan send] | a send with no ready receiver | unbuffered channel, receiver never started | buffer, or start the receiver first |
[chan receive] | a receive with no sender | sender exited early, or channel never written | close the channel, or send |
[sync.WaitGroup.Wait] | counter never reaches zero | Add after Wait, or missing Done | defer wg.Done() next to Add |
[semacquire] | mutex or sync.Cond | double Lock, or Unlock missing | defer mu.Unlock() |
[select (no cases)] | select {} forever | placeholder left in code | remove, or add a blocking case |
[IO wait] | network or file descriptor | not a deadlock | investigate the peer or timeout |
Errors that look similar and are not deadlocks:
| Symptom | Meaning | Difference |
|---|---|---|
fatal error: all goroutines are asleep - deadlock! | proven stuck | runtime aborts |
panic: send on closed channel | write after close | a bug, not a block |
fatal error: concurrent map writes | data race | needs -race to find earlier |
| program hangs with no output | blocked, but not provably | a live timer or server hides it |
context deadline exceeded | a timeout fired | expected control flow |
Channel operations in one view:
| Operation | Unbuffered | Buffered (full) | Buffered (space) | Nil channel |
|---|---|---|---|---|
| send | blocks until receive | blocks | succeeds | blocks forever |
| receive | blocks until send | succeeds | blocks | blocks forever |
| close | ok | ok | ok | panics |
| len/cap | 0 | cap | 0 to cap | 0 |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
1. Start the consumer before the producer
// deadlock: the send happens before any goroutine can receive
func main() {
ch := make(chan int)
ch <- 1
go func() { fmt.Println(<-ch) }()
}
// fixed: buffer of 1, or start the receiver first
func main() {
ch := make(chan int, 1)
ch <- 1
close(ch)
for v := range ch { fmt.Println(v) }
}A buffer of size 1 is enough for a single value and is the smallest change; a buffer sized to the expected burst is the better one when the producer runs ahead.
2. WaitGroup.Add must happen before Wait
var wg sync.WaitGroup
for _, u := range urls {
wg.Add(1) // before the goroutine starts
go func(u string) {
defer wg.Done()
fetch(u)
}(u)
}
wg.Wait()Calling Add inside the goroutine is a race: Wait can observe a zero counter and return, and a later Add on a completed WaitGroup panics with sync: WaitGroup is reused before previous Wait has returned. Go 1.22 changed loop variable scoping so the u parameter is no longer required for correctness, but keeping it makes the capture explicit.
3. A mutex locked twice in one goroutine
type Counter struct {
mu sync.Mutex
n int
}
func (c *Counter) Inc() { c.mu.Lock(); defer c.mu.Unlock(); c.n++ }
func (c *Counter) AddTwice() {
c.mu.Lock()
defer c.mu.Unlock()
c.Inc() // deadlock: same goroutine, same mutex
}sync.Mutex is not reentrant, and the runtime's dump shows [semacquire] on the same goroutine that holds the lock. The fix is to split the unlocked core from the locked wrapper:
func (c *Counter) inc() { c.n++ } // caller holds the lock
func (c *Counter) Inc() { c.mu.Lock(); defer c.mu.Unlock(); c.inc() }
func (c *Counter) AddTwice() { c.mu.Lock(); defer c.mu.Unlock(); c.inc(); c.inc() }4. Worker pools that exit early
jobs := make(chan Job)
results := make(chan Result)
for i := 0; i < 4; i++ {
go func() {
for j := range jobs {
results <- process(j) // blocks when nobody reads results
}
}()
}If the collector returns early on an error, workers block forever on results <-. Give the send a way out:
select {
case results <- process(j):
case <-ctx.Done():
return
}A select with a ctx.Done() case converts a permanent block into a controlled shutdown, and the dump then shows [select] rather than a deadlock.
5. Reading a dump you already have
GOTRACEBACK=all ./app # every goroutine, not just the running one
GOTRACEBACK=system ./app # runtime goroutines includedIn tests, go test -timeout 30s prints a full goroutine dump on timeout instead of hanging the CI job. Search the dump for the goroutine that is not waiting — the one at the top of a send chain is usually the culprit:
go test ./... -timeout 20s 2>&1 | grep -E '^goroutine|\[chan|\[semacquire|\.go:[0-9]+'The regular expression tester is a quick way to iterate on such a filter before putting it in a script, and printing monotonic timings around the suspect call with the Unix timestamp converter settles whether a stall is seconds or hours.
6. When the detector never fires
A server with an idle HTTP listener keeps the network poller alive, so a stuck handler hangs rather than aborting. Add a watchdog for those:
go func() {
pprof.Lookup("goroutine").WriteTo(os.Stderr, 2)
}()or expose net/http/pprof and pull debug/pprof/goroutine?debug=2 while it is stuck. Both give the same information the fatal error would have given.
Common Compilation/Runtime Mistakes & Version Gotchas
Making the buffer large to "fix" the deadlock. A buffer of 1000 delays the block until traffic exceeds it, at which point the same bug returns under load. Buffering is a throughput decision, not a synchronisation fix.
Closing a channel from the receiver. close belongs to the sender, and only one sender may do it. Closing from the consumer side races with in-flight sends and produces send on closed channel instead of a deadlock — a worse failure because it loses data.
Assuming the detector covers production. It fires only when nothing can ever wake the program. In a service, a missing Unlock shows up as a latency spike and a growing goroutine count, which runtime.NumGoroutine() in a metrics endpoint exposes long before a dump is needed.
Nil channels in a select. A nil channel blocks forever on both send and receive, which is deliberate in the "disable this case" idiom:
var out chan int // nil: the case is disabled
if ready { out = real }
select {
case out <- v:
case <-ctx.Done():
}Replacing out with a nil by accident — an uninitialised struct field, a failed constructor — produces a permanent block with no error.
Version differences. Go 1.22 changed for loop variables to be per-iteration, which removed a class of closure bugs but not this one. Go 1.23 made time.Timer and time.Ticker channels unbuffered and stopped sending stale values, so code that relied on a buffered timer channel sending once during a long gap now blocks differently. sync.OnceFunc and sync.OnceValue (1.21) replace hand-rolled once-and-wait patterns that used to deadlock when the initialiser re-entered itself.
Reference material: The Go Programming Language Specification: channel types and Effective Go: concurrency.
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: go.mod file not found in current directory
Go 1.16 and later build in module mode. Run commands inside the module root, create a go.mod with go mod init, or set GO111MODULE and GOWORK deliberately.
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.
More in Go
All Go guidesThe guides filed next to this one in Go, in library order.