Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~5 min readGo
#go#goroutines#channels#deadlock
Bold white headline reading GOROUTINE DEADLOCK with a Go scheduler crate holding an amber send card and a cyan receive card that never meet.

Introduction & Quick Summary

A Go program stops with a runtime fatal error, not a compile error:

code
fatal error: all goroutines are asleep - deadlock! goroutine 1 [chan receive]: main.main() /tmp/x.go:9 +0x2e exit status 2

The 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.

code
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 mutex

The smallest reproducible case, an unbuffered channel with no receiver:

go
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:

go
// 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) <-ch

Each 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 stateBlocked onUsual mistakeFix
[chan send]a send with no ready receiverunbuffered channel, receiver never startedbuffer, or start the receiver first
[chan receive]a receive with no sendersender exited early, or channel never writtenclose the channel, or send
[sync.WaitGroup.Wait]counter never reaches zeroAdd after Wait, or missing Donedefer wg.Done() next to Add
[semacquire]mutex or sync.Conddouble Lock, or Unlock missingdefer mu.Unlock()
[select (no cases)]select {} foreverplaceholder left in coderemove, or add a blocking case
[IO wait]network or file descriptornot a deadlockinvestigate the peer or timeout

Errors that look similar and are not deadlocks:

SymptomMeaningDifference
fatal error: all goroutines are asleep - deadlock!proven stuckruntime aborts
panic: send on closed channelwrite after closea bug, not a block
fatal error: concurrent map writesdata raceneeds -race to find earlier
program hangs with no outputblocked, but not provablya live timer or server hides it
context deadline exceededa timeout firedexpected control flow

Channel operations in one view:

OperationUnbufferedBuffered (full)Buffered (space)Nil channel
sendblocks until receiveblockssucceedsblocks forever
receiveblocks until sendsucceedsblocksblocks forever
closeokokokpanics
len/cap0cap0 to cap0

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. Start the consumer before the producer

go
// 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

go
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

go
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:

go
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

go
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:

go
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 included

In 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:

bash
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
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:

go
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 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.