Skip to content

Goroutines & Channels: Unbuffered, Buffered, Directions, Closing, range ​

"Do not communicate by sharing memory; instead, share memory by communicating." — Effective Go, section "Share by communicating"

Summary: A goroutine is a function running concurrently in the same address space, scheduled by the Go runtime onto a few OS threads; a channel is a typed, synchronised FIFO that lets goroutines hand values (and ownership of them) to each other, with exact rules for blocking, closing and ranging. Focus: The go statement and argument evaluation, small growable stacks, the GMP scheduler, preemption and GOMAXPROCS, waiting with sync.WaitGroup and wg.Go, unbuffered rendezvous versus buffered capacity, len/cap, nil channels, directional types chan<- and <-chan, close and its three panics, range over a channel, ownership and lifecycle (generator, pipeline, done channel), chan struct{} signals, leaks and how to find them (goleak, goroutine profile, runtime.NumGoroutine), deadlock, the memory-model guarantees, semaphores, channels versus mutexes, and the PHP comparison. Learning goal: Predict for any channel operation whether it proceeds, blocks or panics; give every goroutine a visible exit; and choose between a channel, a mutex and a WaitGroup for a given job.

This page owns goroutines and channels as the language and runtime define them. Waiting on several channels at once, timeouts and non-blocking operations belong to select; cancellation trees and deadlines to context; Mutex, RWMutex, Cond, Once, Pool and atomics to sync & atomic; worker pools, fan-out/fan-in and errgroup to Worker Pools & Pipelines; data races and the race detector to Race Conditions & Deadlocks. Closures and per-iteration loop variables are in Functions. Queue-level flow control between services is in Backpressure & Flow Control.

Page map ​

If you are looking forGo to
Every channel operation and its outcome on one screenEverything in one minute
Why Go has goroutines and channels at allWhy it exists
CSP, Effective Go, the memory model, release notesWhere it comes from
go f(x), what runs where, when it endsGoroutines and the go statement
What a go statement evaluates immediatelyArgument evaluation
2 KB stacks, growth, "a few kilobytes"Stacks
G, M, P, M:N, preemption, GOMAXPROCSThe scheduler
wg.Add, wg.Done, wg.Wait, wg.GoWaiting: WaitGroup
Rendezvous, handoff, make(chan T)Unbuffered channels
make(chan T, n), len, capBuffered channels
chan<- T, <-chan TDirectional channels
close, v, ok := <-ch, for v := range chClosing and range
var ch chan int blocks foreverNil channels
Who closes, generator, pipeline, done channelOwnership and lifecycle
chan struct{}, broadcast by closeSignalling
Leaks, goleak, goroutine profile, NumGoroutineGoroutine leaks
fatal error: all goroutines are asleep - deadlock!Deadlock
What a send or close guarantees about memoryMemory model
Limiting concurrency, unbounded queuesSemaphores and bounded queues
Mutex or channel? Channel of channelsChannels versus mutexes
runtime.Gosched, time.After, sync.OnceGosched, timers, Once
Fibers, Swoole, queue workersFor PHP/Laravel developers
hchan, wait queues, exact messages, knobsMechanics
Fixes with codeSolving the classic problems
Which tool for which jobChoosing
Monolith to distributed systemIn architecture
Reproduce the outputsLab
Wrong beliefs, cheat sheet, termsMisconceptions, Cheat sheet, Glossary

Everything in one minute ​

Every operation, every state. The spec defines each cell; the states diagram draws them.

Operationnil channelopen, unbufferedopen, bufferedclosed
ch <- vBlocks foreverBlocks until a receiver takes itProceeds if a slot is free, else blockspanic: send on closed channel
v := <-chBlocks foreverBlocks until a sender arrivesProceeds if a value is buffered, else blocksBuffered values first, then zero value at once
v, ok := <-chBlocks foreverok == trueok == trueok == false once empty
close(ch)panic: close of nil channelAllowed once (sender side)Allowed once; buffered values still deliveredpanic: close of closed channel
for v := range chBlocks foreverRuns until closedRuns until closed and drainedDrains what is left, then ends
len(ch) / cap(ch)0 / 00 / 0Buffered count / buffer sizeRemaining count / size

Goroutines and waiting.

ThingWhat it isTiny exampleThe trap
go f(x)Start f(x) in a new goroutine; do not waitgo serve(conn)main returning kills it mid-flight
Argument evaluationf and x are evaluated now, in the callergo log(time.Now()) logs the start timeExpecting late evaluation
StackStarts at 2 KB (Go 1.4+), grows by copying100 000 goroutines in a few hundred MBThinking goroutines are free
SchedulerM:N: many G on few M through GOMAXPROCS P12 P on a 12-core laptopAssuming one goroutine = one thread
sync.WaitGroupCounter: Add, Done, Waitwg.Add(1); go func() { defer wg.Done() }()Add inside the new goroutine
wg.Go(f) (Go 1.25)Add(1) + go + defer Done() in one callwg.Go(func() { work() })Needs a go 1.25 module or file
LeakA goroutine blocked foreverA sender nobody receives fromNot garbage collected, ever

Which tool.

You needUseNot
Hand a value to another goroutineUnbuffered channelA shared variable plus a flag
Smooth a small burstBuffered channel with a deliberate sizeA huge buffer "to be safe"
Tell many goroutines "stop"close(done) or ctx.Done()One send per goroutine
Wait for N goroutinessync.WaitGroup / wg.GoCounting with a channel
Protect a map or a countersync.Mutex or atomicsA goroutine per map, unless it owns more
Limit concurrency to NBuffered chan struct{} of size N, or a worker poolUnlimited go per request
Wait on several channels or a timeoutselect (chapter)Polling with len(ch)

Why it exists ​

Servers spend most of their time waiting: for a socket, a disk, a database, another service. Threads let you write that waiting as straight-line code, but OS threads cost a megabyte-scale stack and a kernel context switch, so a thread per connection stops at thousands. Callbacks and event loops scale further but turn every function into a state machine. Go's answer is to make the thread cheap enough (a goroutine starts with a 2 KB stack and is switched in user space) that you can write blocking code for each connection, and to give goroutines a typed, synchronised pipe (a channel) so that most coordination is "hand this value over" instead of "lock, check a flag, unlock".

Shared memory with locksCommunicating with channels
Data stays put; goroutines take turns touching itData moves; only the current owner touches it
Correctness depends on every access taking the lockCorrectness follows from the handoff
Cheapest for a counter or a cache mapClearest for pipelines, events and ownership transfer
Deadlock by lock orderingDeadlock by nobody sending or nobody receiving
Tools: sync.Mutex, sync/atomicTools: chan, select, close

The analogy we reuse on this page: a kitchen pass. Cooks are goroutines. The pass (the shelf between kitchen and floor) is a channel. An unbuffered pass has no shelf: the cook holds the plate until a waiter's hands take it (a rendezvous). A buffered pass has N slots: the cook can put down N plates and go back to cooking; with all slots full, the cook waits. Ringing the bell once for "kitchen closed" is close: every waiter hears it, waiters still take the plates already on the shelf, and a cook who tries to put a plate on a closed pass has broken the rules (a panic). A cook who leaves a plate on a pass no waiter will ever visit is a leaked goroutine: they stand there forever.

Three common misunderstandings, up front ​

  1. "A buffered channel is a faster channel." The buffer changes synchronisation, not speed. With a buffer the sender no longer knows the receiver got the value, and a full buffer blocks exactly like an unbuffered channel. Pick the size for a reason (a known number of results, a semaphore limit), not for performance.
  2. "The garbage collector cleans up goroutines that are stuck." It does not. The Go blog's pipelines article: "Goroutines are not garbage collected; they must exit on their own." A goroutine blocked on a channel nobody else can reach stays in memory until the process exits.
  3. "Receivers should close channels when they are done." Only the sender knows when there will be no more values, and only one party may close. A receiver that closes makes the next send panic. Receivers signal "stop" through a separate done channel or a context.

Where it comes from ​

The Go FAQ names the source: "One of the most successful models for providing high-level linguistic support for concurrency comes from Hoare's Communicating Sequential Processes, or CSP." It also explains the cost model: goroutines "have little overhead beyond the memory for the stack, which is just a few kilobytes", the runtime "grows (and shrinks) the memory for storing the stack automatically", and "It is practical to create hundreds of thousands of goroutines in the same address space."

The language specification defines the operations exactly. "A 'go' statement starts the execution of a function call as an independent concurrent thread of control, or goroutine, within the same address space." For channels: "If the capacity is zero or absent, the channel is unbuffered and communication succeeds only when both a sender and receiver are ready", "A nil channel is never ready for communication", "A send on a closed channel proceeds by causing a run-time panic", "Closing the nil channel also causes a run-time panic", and for range, "the iteration values produced are the successive values sent on the channel until the channel is closed."

Effective Go gives the slogan quoted at the top, then adds the caveat that matters: "This approach can be taken too far. Reference counts may be best done by putting a mutex around an integer variable, for instance." It shows the buffered channel used "like a semaphore" and the "channels of channels" request/response idiom.

The Go Memory Model (revised for Go 1.19) states what a channel operation guarantees: "A send on a channel is synchronized before the completion of the corresponding receive from that channel", "The closing of a channel is synchronized before a receive that returns a zero value because the channel is closed", and "The kth receive from a channel with capacity C is synchronized before the completion of the k+Cth send on that channel", which it calls the basis of "a counting semaphore".

Release notes date the runtime behaviour: Go 1.4 reduced the starting stack "from 8192 bytes to 2048 bytes"; Go 1.5 made GOMAXPROCS default to the number of cores ("in prior releases it defaulted to 1"); Go 1.14 made goroutines "asynchronously preemptible", so "loops without function calls no longer potentially deadlock the scheduler"; Go 1.23 made unreferenced timers collectable "even if their Stop methods have not been called", which ended the classic time.After leak; Go 1.25 added WaitGroup.Go, a vet waitgroup analyzer, and container-aware GOMAXPROCS; Go 1.26 added an experimental goroutineleak profile that Go 1.27 made generally available. The Go blog articles "Go Concurrency Patterns: Pipelines and cancellation" (2014) and "Share Memory By Communicating" (2010) are the canonical pattern texts, and the Go Code Review Comments wiki has the rule this page repeats most: "When you spawn goroutines, make it clear when - or whether - they exit."

The concept catalogue ​

Every block follows the same order: plain words, the usual wrong belief, a precise definition, a timeline, real scenarios, behaviour table, and the fix in Go. The snippets live under docs/snippets/go/goroutines-channels/go/, one module with seven tested packages and one demo command; they pass go test -race.

Goroutines and the go statement Must-know ​

In plain words: put go in front of a function call and that call runs on its own, at the same time as the rest of your program. Your code does not wait for it.

Common misunderstanding: "When main waits a bit, my goroutines finish." main returning ends the program and every goroutine with it, finished or not. A time.Sleep that "usually works" is a race; wait explicitly.

Definition: go Expression where the expression is a function or method call (not parenthesised; built-ins only as allowed for expression statements). The call runs in a new goroutine in the same address space; results are discarded. "When the function terminates, its goroutine also terminates." A goroutine has no ID you can use, no handle, no way to kill it from outside, and no return value: everything it produces leaves through a channel, a shared variable protected by synchronisation, or a callback. A panic that is not recovered inside the goroutine crashes the whole process.

text
1  main:  go serve(conn1)            // returns immediately
2  main:  go serve(conn2)            // returns immediately
3  G1:    serve(conn1) reads, blocks on network      -> runtime parks G1, runs others
4  G2:    serve(conn2) runs
5  main:  return from main           -> process exits, G1 and G2 stop wherever they are

Real scenario: net/http starts one goroutine per connection ("Serve accepts incoming connections ... creating a new service goroutine for each"); a background flusher sends metrics every ten seconds; a CLI downloads twenty files in parallel; a test starts a fake server goroutine and forgets to stop it.

QuestionAnswer
Where does it run?Same process and memory as the caller
Return value?Discarded; send it on a channel
Identity?None exposed; the FAQ explains goroutine IDs were left out on purpose
Stop from outside?Impossible; it must observe a signal (done channel, ctx.Done()) and return
Unrecovered panic?Crashes the process with panic: ... and goroutine N [running]:
Ends when?When its function returns, or when main returns

Fix / how to use it: start a goroutine only when you can say how it ends. Prefer synchronous functions and let the caller add concurrency (Code Review Comments: "Prefer synchronous functions"). The spawn package waits for every goroutine it starts:

go
// Package spawn shows what a go statement evaluates, and how to wait for goroutines.
package spawn

import "sync"

// ArgsEvaluatedNow starts one goroutine per iteration. The argument x*10 is
// evaluated in the calling goroutine when the go statement runs, so each
// goroutine sees the value of x at that moment, even though x changes later.
func ArgsEvaluatedNow() []int {
	var wg sync.WaitGroup
	out := make([]int, 3)
	x := 1
	for i := range 3 {
		wg.Add(1) // Add before go, never inside the new goroutine
		go func(slot, v int) {
			defer wg.Done()
			out[slot] = v // each goroutine writes its own index: no data race
		}(i, x*10)
		x++
	}
	wg.Wait() // Wait returns after every Done; the writes above are visible here
	return out
}

// SquaresAddDone computes n squares concurrently with the classic Add/Done/Wait trio.
func SquaresAddDone(n int) []int {
	var wg sync.WaitGroup
	out := make([]int, n)
	wg.Add(n) // one Add for the whole batch is fine when n is known
	for i := range n {
		go func() {
			defer wg.Done()
			out[i] = i * i // i is per-iteration since Go 1.22
		}()
	}
	wg.Wait()
	return out
}

Argument evaluation in a go statement Must-know ​

In plain words: go f(a, b) works out f, a and b right now, in your goroutine, and only then hands them to the new goroutine.

Common misunderstanding: "The arguments are computed when the goroutine starts running." They are computed by the go statement itself. Variables captured by a closure are different: they are shared, and the goroutine reads their value whenever it gets to them.

Definition: the spec: "The function value and parameters are evaluated as usual in the calling goroutine, but unlike with a regular call, program execution does not wait for the invoked function to complete." Passing a value as an argument is a snapshot; referring to an outer variable from a function literal is a shared reference. Since Go 1.22 (a go 1.22+ line in go.mod), each for iteration has its own loop variable, so go func() { use(i) }() in a loop no longer shares one i.

text
1  x := 1
2  go func(v int) { print(v) }(x*10)   // x*10 == 10 evaluated here, copied into v
3  x = 2
4  go func() { print(x) }()            // captures x itself: may print 2, or 3 if x changes again
5  x = 3                               // data race with line 4 unless synchronised

Real scenario: go audit(user.ID, time.Now()) records the request time, not the time the audit goroutine ran; go client.Do(req) with a method value binds client now; a loop that starts a goroutine per order captured order in a pre-1.22 module and processed the last order N times.

FormWhen the value is takenShared with caller?
go f(x)At the go statementNo, f gets a copy
go obj.Method(x)Receiver and x at the go statementOnly if the receiver is a pointer
go func() { use(x) }()When the goroutine reads xYes, the variable is shared
Loop variable, go 1.22+Per iterationOne variable per iteration
Loop variable, go 1.21 or olderOne variable for the whole loopYes, the classic bug

Fix / how to use it: pass values that must be fixed at start as arguments (go func(slot, v int) {...}(i, x*10) in ArgsEvaluatedNow above); keep go 1.22 or newer in go.mod; run go test -race to catch shared captured variables.

Stacks: small at birth, grown by copying Important ​

In plain words: every goroutine gets its own stack, but a tiny one. When a function needs more room, the runtime moves the stack to a bigger block and keeps going.

Common misunderstanding: "Goroutines are free, so a million of them cost nothing." Each one costs at least its stack (2 KB, rounded up by the allocator) plus everything its stack points to, and every pointer on those stacks keeps heap data alive. A million blocked goroutines is gigabytes of memory and a slow garbage collector.

Definition: the runtime constant stackMin = 2048 (read from runtime/stack.go in Go 1.27.4) sets the starting size; Go 1.4 lowered it from 8192 bytes. On function entry, a check compares the stack pointer with a guard; if the frame does not fit, runtime.morestack allocates a stack twice as large, copies the frames and adjusts pointers into the stack (contiguous stacks, since Go 1.3/1.4; earlier versions used segmented stacks). The garbage collector shrinks stacks that use little of their space. The maximum is 1 GB on 64-bit (fatal error: stack overflow past it, see Functions). OS threads, by comparison, get a fixed stack (commonly 8 MB of reserved virtual memory on Linux).

text
1  go handle(conn)                 // new G with a 2 KB stack
2  handle -> parse -> decode       // frame does not fit: morestack
3  runtime: allocate 4 KB, copy frames, fix pointers, continue
4  decode returns, stack mostly empty
5  next GC: stack shrunk back to half its size

Real scenario: a chat server holding 200 000 idle WebSocket connections, one goroutine each; a crawler that starts a goroutine per URL and runs out of memory at 2 million; a recursive JSON decoder that grows one goroutine's stack to hundreds of KB.

ItemGoroutineOS thread (typical Linux)
Initial stack2 KB (Go 1.4+), 8 KB beforeFixed reservation, commonly 8 MB
GrowthBy copying, doublingNone; overflow is a crash
ShrinkBy the GCNo
Switch costUser-space, a few hundred ns or lessKernel context switch
Practical countHundreds of thousands (FAQ)Thousands

Fix / how to use it: count goroutines like any other resource: one per connection is fine; one per item of unbounded input needs a limit (semaphores, worker pools).

The scheduler: G, M, P, M:N and preemption Important ​

In plain words: the Go runtime runs your many goroutines on a few OS threads, like a manager assigning many small tasks to a few workers, and it keeps the number of workers that run Go code at the same time equal to GOMAXPROCS.

Common misunderstanding: "GOMAXPROCS limits how many goroutines I can have" or "limits the number of threads." It limits how many threads execute Go code at the same time. You can have millions of goroutines and more threads than GOMAXPROCS (threads blocked in system calls or cgo do not count).

Definition: the runtime source (runtime/proc.go): "G - goroutine. M - worker thread, or machine. P - processor, a resource that is required to execute Go code." runtime/HACKING.md: "There are exactly GOMAXPROCS Ps", and "When an M stops executing user Go code, for example by entering a system call, it returns its P to the idle P pool." Each P has a local run queue; there is also a global run queue; an idle P steals half of another P's queue (work stealing). Network I/O does not block an M: the netpoller parks the G and wakes it when the socket is ready. This is M:N scheduling (M goroutines on N threads). Since Go 1.14 goroutines are asynchronously preemptible (the runtime interrupts a goroutine that has run for about 10 ms with a signal), so a tight loop without calls no longer starves others. GOMAXPROCS defaults to the number of logical CPUs (Go 1.5+); Go 1.25 also respects the Linux cgroup CPU limit and updates it periodically, unless GOMAXPROCS is set by environment or runtime.GOMAXPROCS.

G (goroutines) run on M (OS threads) only while holding a P (GOMAXPROCS of them)global run queue (runnable G)GGGP0GrunningGGGlocal run queueP1GrunningGsteals when emptyP2 (idle)takes work from theglobal queue or stealsfrom P0 / P1M0 (thread)M1 (thread)GM2M2 blocked in a syscall: its P is handed to another M
text
1  P0 runs G1; G2, G3 wait in P0's local queue
2  G1 calls read() on a file -> M0 enters a syscall, hands P0 to M3
3  M3 + P0 run G2
4  P1's queue empties -> P1 steals G3 from P0
5  G1's syscall returns -> M0 needs a P; none idle -> G1 goes to the global queue, M0 parks
6  G4 spins in a loop for 10 ms -> sysmon preempts it (Go 1.14+), G5 gets the CPU

Real scenario: a container with a 2-CPU limit on a 64-core node ran with GOMAXPROCS=64 before Go 1.25 and spent its CPU quota in throttling (the reason go.uber.org/automaxprocs existed); a CPU-bound loop froze a pre-1.14 program's garbage collector; a cgo call that blocks pins one M, and the runtime starts another.

Setting or eventEffectVersion
GOMAXPROCS defaultNumber of logical CPUsGo 1.5+ (was 1)
cgroup CPU limitLower default on Linux; updated as limits changeGo 1.25+
GODEBUG=containermaxprocs=0, updatemaxprocs=0Turn those two behaviours offGo 1.25+
GOMAXPROCS=n env or runtime.GOMAXPROCS(n)Fixed value; disables the automatic updatesAll
Tight loop without callsPreempted asynchronouslyGo 1.14+ (not windows/arm)
Blocking syscallM releases its P; another M runs itAll
Network waitG parked on the netpoller; no M blockedAll

Fix / how to use it: leave GOMAXPROCS at its default on Go 1.25+; on older versions inside a CPU-limited container set it to the limit. Never tune program logic around scheduling order: the scheduler gives no fairness or ordering guarantees. Trace with go tool trace when you need to see it.

Waiting: sync.WaitGroup and wg.Go Must-know ​

In plain words: a WaitGroup is a counter of "jobs still running". Add before you start each job, mark done when it ends, and wait until the counter reaches zero.

Common misunderstanding: "I can call wg.Add(1) at the top of the goroutine." Then wg.Wait may run before the goroutine has started, see zero, and return early. Add must happen before the go statement. Go 1.25's vet reports exactly this: WaitGroup.Add called from inside new goroutine.

Definition: wg.Add(n) adds to the counter; wg.Done() is Add(-1); wg.Wait() blocks until the counter is zero. A negative counter panics with sync: negative WaitGroup counter; reusing a group before the previous Wait returned panics with sync: WaitGroup is reused before previous Wait has returned. Go 1.25 added func (wg *WaitGroup) Go(f func()), which "calls f in a new goroutine and adds that task to the WaitGroup"; f must not panic. The memory model: the return from f (or Done) is synchronised before the return of the Wait it unblocks, so results written by the goroutines are visible after Wait. A WaitGroup must not be copied after first use (vet's copylocks). It carries no errors and no cancellation: for "wait, collect the first error, cancel the rest" use errgroup (Worker Pools).

text
1  main: wg.Add(1); go A()        counter 1
2  main: wg.Add(1); go B()        counter 2
3  main: wg.Wait()                blocks
4  A:    defer wg.Done()          counter 1
5  B:    defer wg.Done()          counter 0  -> Wait returns; A's and B's writes are visible

Real scenario: resize 30 images in parallel and wait; fetch prices from three suppliers and wait for all; a graceful shutdown that waits for in-flight background jobs; a test that waits for every fake client goroutine.

APISinceUseNote
wg.Add(n)Go 1.0Before go, once per goroutine or once per batchNever inside the new goroutine
wg.Done()Go 1.0defer wg.Done() first line of the goroutineRuns even on early return
wg.Wait()Go 1.0Block until counter is zeroNo timeout; combine with select via a closed channel
wg.Go(f)Go 1.25Replaces the three lines abovef must not panic
errgroup.Group.Gox/syncFirst error plus cancellationSee Worker Pools

Fix / how to use it: the 1.25 form, behind a //go:build go1.25 tag so the module itself stays on go 1.24:

go
//go:build go1.25

package spawn

import "sync"

// SquaresWG uses sync.WaitGroup.Go (Go 1.25+), which does Add(1), go and
// defer Done in one call. The build tag lets this module keep "go 1.24"
// while this file uses the newer API.
func SquaresWG(n int) []int {
	var wg sync.WaitGroup
	out := make([]int, n)
	for i := range n {
		wg.Go(func() { out[i] = i * i })
	}
	wg.Wait()
	return out
}

Unbuffered channels: the rendezvous Must-know ​

In plain words: with make(chan T) a send and a receive must meet. Whoever arrives first waits for the other; at the moment they meet the value passes and both carry on.

Common misunderstanding: "An unbuffered channel holds one value." It holds none. That is why it is a synchronisation point: when a send completes, you know a receiver has the value.

Definition: "If the capacity is zero or absent, the channel is unbuffered and communication succeeds only when both a sender and receiver are ready." Effective Go: "If the channel is unbuffered, the sender blocks until the receiver has received the value." Channels are FIFO; "a single channel may be used in send statements, receive operations, and calls to the built-in functions cap and len by any number of goroutines without further synchronization." The memory model adds the reverse edge for unbuffered channels only: "A receive from an unbuffered channel is synchronized before the completion of the corresponding send on that channel."

Unbuffered: every send is a meeting. Buffered: the buffer absorbs bursts until fullmake(chan T)senderreceiversend 1 blockssend 2 blocksrecv 1: both proceedrecv 2: both proceedmake(chan T, 2)senderreceiversend 1, send 2: no waitsend 3 blocks: fullbuffer, 2 slotsrecv 1 frees a slotsend 3 completes
text
     sender G1                         receiver G2
1    msg = "ready"
2    done <- struct{}{}   blocks...
3                                      <-done        rendezvous: both proceed
4    continues                         print(msg)    guaranteed "ready"

Real scenario: a worker reports "finished" and you need to know the report was taken; a handoff of a connection from an acceptor to a handler; a test that must not continue until a background goroutine has reached a checkpoint; ping-pong between two goroutines.

PropertyUnbufferedBuffered (cap n)
Send completes whenA receiver took the valueThe value is in the buffer
Sender knows receiver got itYesNo
Memory-model edgesSend before receive completes, and receive before send completesSend before receive; kth receive before (k+C)th send
Typical useHandoff, signal, synchronisationBurst absorption, known result count, semaphore
len / capAlways 0 / 0Current count / n

Fix / how to use it: default to unbuffered; add a buffer only for a reason you can write in a comment. Handoff and PingPong show the guarantees, and TrySend shows the blocking rule without blocking:

go
// Package rendezvous shows the blocking rules of unbuffered and buffered channels.
package rendezvous

// TrySend attempts a send without blocking. It reports whether the value was
// accepted: by a waiting receiver (unbuffered) or by free buffer space (buffered).
func TrySend(ch chan<- int, v int) bool {
	select {
	case ch <- v:
		return true
	default:
		return false
	}
}

// Handoff publishes a value to another goroutine through an unbuffered
// channel. The write to msg happens before the send, and the send is
// synchronized before the receive completes, so the reader sees "ready".
func Handoff() string {
	var msg string
	done := make(chan struct{})
	go func() {
		msg = "ready"      // 1. write
		done <- struct{}{} // 2. send: blocks until main receives
	}()
	<-done     // 3. receive completes after the send
	return msg // 4. guaranteed to read "ready"
}

// PingPong bounces a counter between two goroutines n times over unbuffered
// channels. Each send waits for the matching receive, so the two goroutines
// strictly alternate and the log shows the order.
func PingPong(n int) []string {
	ping, pong := make(chan int), make(chan int)
	var log []string
	go func() {
		for v := range ping {
			pong <- v + 1
		}
		close(pong)
	}()
	v := 0
	for range n {
		ping <- v
		v = <-pong
		log = append(log, "ping", "pong")
	}
	close(ping)
	<-pong // wait for the partner to close pong: it has exited
	return log
}

Buffered channels: capacity, len and cap Must-know ​

In plain words: make(chan T, 3) gives the pass a shelf with three slots. Senders do not wait while there is room; receivers do not wait while there is something on the shelf.

Common misunderstanding: "len(ch) > 0 means my next receive will not block." Another goroutine may take the value between your check and your receive. len and cap are for metrics and debugging, not control flow; use select with default for a non-blocking attempt.

Definition: "Otherwise, the channel is buffered and communication succeeds without blocking if the buffer is not full (sends) or not empty (receives)." cap(ch) is the buffer size set by make; len(ch) is the number of queued elements. The capacity is fixed for the channel's life. Buffered values remain receivable after close. A buffer of size 1 is common for "one result, sender must never block" (as in FirstBuffered below and the reply channel in reqresp).

text
1  ch := make(chan string, 3)    len 0 cap 3
2  ch <- "a"; ch <- "b"          len 2 cap 3   no goroutine needed
3  ch <- "c"                     len 3 cap 3   full
4  ch <- "d"                     blocks until someone receives
5  <-ch                          "a" (FIFO)    len 2

Real scenario: a log shipper buffers 1 000 lines so a slow network does not stall request handlers for a short burst; a fan-out of 5 lookups collects results in a chan Result of size 5 so no worker blocks after the caller returns; a signal channel make(chan os.Signal, 1) for signal.Notify, which the docs require to be buffered.

Buffer sizeMeaningGood forRisk
0RendezvousHandoff, synchronisationSender blocks if receiver is slow
1One pending itemSignal notification, single result, "latest" slotHides a missing receiver for one send
Known NExactly the number of sendsFan-out results, leak preventionWrong N brings the leak back
Large, arbitrary"Queue"Short bursts with a measured boundLatency, memory, hides backpressure

Fix / how to use it: Fill records len/cap after each step (the test asserts {make 0 3} {2 sends 2 3} {full 3 3} {1 receive 2 3}):

go
// Package buffered shows buffer capacity, len/cap and a channel used as a semaphore.
package buffered

import (
	"sync"
	"sync/atomic"
)

// Snapshot records len and cap of a channel after each step.
type Snapshot struct {
	Step     string
	Len, Cap int
}

// Fill sends into a buffered channel and receives one value, recording len
// and cap after each operation. No goroutine is needed while the buffer has room.
func Fill() []Snapshot {
	ch := make(chan string, 3)
	var s []Snapshot
	rec := func(step string) { s = append(s, Snapshot{step, len(ch), cap(ch)}) }
	rec("make")
	ch <- "a"
	ch <- "b"
	rec("2 sends")
	ch <- "c"
	rec("full")
	<-ch // FIFO: receives "a"
	rec("1 receive")
	return s
}

// Semaphore limits how many goroutines run a section at once. The capacity
// is the limit; a send acquires a slot and a receive releases it.
type Semaphore chan struct{}

// NewSemaphore returns a semaphore with n slots.
func NewSemaphore(n int) Semaphore { return make(Semaphore, n) }

// Acquire blocks while all slots are taken.
func (s Semaphore) Acquire() { s <- struct{}{} }

// Release frees one slot.
func (s Semaphore) Release() { <-s }

// RunLimited runs tasks goroutines but lets at most limit of them inside the
// critical section at once. It returns the highest concurrency observed.
func RunLimited(tasks, limit int, work func()) int {
	sem := NewSemaphore(limit)
	var wg sync.WaitGroup
	var cur, peak atomic.Int64
	for range tasks {
		wg.Add(1)
		go func() {
			defer wg.Done()
			sem.Acquire()
			defer sem.Release()
			n := cur.Add(1)
			for {
				p := peak.Load()
				if n <= p || peak.CompareAndSwap(p, n) {
					break
				}
			}
			work()
			cur.Add(-1)
		}()
	}
	wg.Wait()
	return int(peak.Load())
}

Directional channels: chan<- and <-chan Must-know ​

In plain words: you can give someone a channel they can only send on, or only receive from. The compiler then stops them from doing the other thing, including closing a channel they only read.

Common misunderstanding: "Directional channels are different channels." They are views of the same channel. A bidirectional chan T converts implicitly to chan<- T or <-chan T; the reverse conversion is not allowed.

Definition: chan T sends and receives; chan<- T "can only be used to send"; <-chan T "can only be used to receive". "The <- operator associates with the leftmost chan possible": chan<- chan int is a send-only channel of chan int. close on a receive-only channel is a compile error ("It is an error if ch is a receive-only channel"). The exact compiler messages (Go 1.27.4):

text
1  ch <- 1        on <-chan int  -> invalid operation: cannot send to receive-only channel <-chan int ch (variable of type <-chan int)
2  close(ch)      on <-chan int  -> invalid operation: cannot close receive-only channel ch (variable of type <-chan int)
3  <-ch           on chan<- int  -> invalid operation: cannot receive from send-only channel chan<- int ch (variable of type chan<- int)
4  return ro      as chan int    -> cannot use ro (variable of type <-chan int) as chan int value in return statement
5  for range ch   on chan<- int  -> cannot range over ch (variable of type chan<- int): receive from send-only channel chan<- int

Real scenario: a generator returns <-chan Event so callers cannot close or send into it; a worker takes jobs <-chan Job, results chan<- Result and the signature documents the data flow; time.After returns <-chan Time; context.Context.Done() returns <-chan struct{}.

TypeSendReceivecloseConverts to
chan TYesYesYeschan<- T, <-chan T
chan<- TYesNoYes (the sender may close)Nothing narrower
<-chan TNoYesNo (compile error)Nothing narrower

Fix / how to use it: return <-chan T from the function that owns a channel, accept chan<- T in functions that only produce, and <-chan T in functions that only consume. Produce, Fill and Drain below do exactly that.

Closing, receive from closed, and range Must-know ​

In plain words: close(ch) means "no more values will come". Receivers still get whatever was already sent; after that, every receive returns immediately with the zero value, and the two-value form tells you it was closed. A for range loop over the channel ends by itself.

Common misunderstanding: "You must close every channel to free it." A channel is garbage collected like any other value once unreachable, closed or not. Close only to tell receivers that the stream has ended (which range needs). And never close to "stop a sender": the sender's next send panics.

Definition: "For a channel ch, the built-in function close(ch) records that no more values will be sent on the channel." "Sending to or closing a closed channel causes a run-time panic. Closing the nil channel also causes a run-time panic." "After calling close, and after any previously sent values have been received, receive operations will return the zero value for the channel's type without blocking." In x, ok := <-ch, "The value of ok is true if the value received was delivered by a successful send operation to the channel, or false if it is a zero value generated because the channel is closed and empty." for v := range ch produces "the successive values sent on the channel until the channel is closed"; on a nil channel it "blocks forever". There is no isClosed(ch) function: any answer would be stale the moment you got it.

Three states, three operationsmake(chan T)close(ch)nil (var ch chan T)openclosedch <- v : blocks forever<-ch : blocks foreverclose(ch) : panic"close of nil channel"select: case never readych <- v : proceeds, or blocksuntil receiver / free slot<-ch : proceeds, or blocksuntil a value arrivesclose(ch) : once, by the senderlen / cap : buffered count / sizech <- v : panic"send on closed channel"<-ch : buffered values first,then zero value, ok == falseclose(ch) : panic"close of closed channel"range: loop endsA nil channel is useful only inside select, to switch a case off.
text
1  ch := make(chan int, 2); ch <- 7; ch <- 8
2  close(ch)
3  v, ok := <-ch     // 7 true    buffered values survive close
4  v, ok := <-ch     // 8 true
5  v, ok := <-ch     // 0 false   closed and empty: zero value, never blocks
6  ch <- 9           // panic: send on closed channel
7  close(ch)         // panic: close of closed channel

Real scenario: a CSV reader goroutine closes its rows channel at EOF so the consumer's range loop ends; a server's Shutdown closes a quit channel that 40 goroutines watch; a bug where both a timeout path and a normal path call close(results) and the second panics under load; a receiver that does v := <-ch without ok and processes forty zero-valued orders after the producer closed.

SituationOutcomeFix
Receiver needs end-of-streamfor v := range chSender closes after the last send
Distinguish "zero value sent" from "closed"v, ok := <-chCheck ok
Several sendersNobody can close safely aloneWaitGroup for senders, then one closer goroutine
Receiver wants to stop earlyDo not close the data channelClose a done channel / cancel a context
Two code paths may closeSecond close panicsOne owner; or sync.Once around close
Close of nil channelpanic: close of nil channelInitialise with make

Fix / how to use it: the sender closes, once, with defer close(out); the receiver ranges. PanicText turns the three panics into strings so the test can assert their exact text:

go
// Package closing shows close semantics, range over a channel, directional
// channel types, and the three run-time panics close can cause.
package closing

import "fmt"

// Produce owns the channel it returns: it creates it, is the only sender, and
// closes it when done. Callers get a receive-only view and cannot close it.
func Produce(n int) <-chan int {
	out := make(chan int)
	go func() {
		defer close(out) // the sender closes, exactly once
		for i := range n {
			out <- i
		}
	}()
	return out
}

// Fill takes a send-only channel: it may send, but it cannot receive.
func Fill(out chan<- int, vals ...int) {
	for _, v := range vals {
		out <- v
	}
}

// Drain receives until the channel is closed and empty, then returns.
func Drain(in <-chan int) []int {
	var got []int
	for v := range in { // ends when in is closed and drained
		got = append(got, v)
	}
	return got
}

// Recv is one result of the comma-ok receive form.
type Recv struct {
	V  int
	OK bool
}

// AfterClose shows that buffered values survive close and that a receive on a
// closed, empty channel returns the zero value and false without blocking.
func AfterClose() []Recv {
	ch := make(chan int, 2)
	ch <- 7
	ch <- 8
	close(ch)
	var out []Recv
	for range 4 {
		v, ok := <-ch
		out = append(out, Recv{v, ok})
	}
	return out
}

// PanicText runs f and returns the text of the panic it raised, or "".
func PanicText(f func()) (msg string) {
	defer func() {
		if r := recover(); r != nil {
			msg = fmt.Sprint(r)
		}
	}()
	f()
	return ""
}

// SendOnClosed panics with "send on closed channel".
func SendOnClosed() {
	ch := make(chan int, 1)
	close(ch)
	ch <- 1
}

// DoubleClose panics with "close of closed channel".
func DoubleClose() {
	ch := make(chan int)
	close(ch)
	close(ch)
}

// CloseNil panics with "close of nil channel".
func CloseNil() {
	var ch chan int
	close(ch)
}

Nil channels: never ready Important ​

In plain words: a channel variable you declared but never maked is nil. Sending to it or receiving from it waits forever; closing it panics.

Common misunderstanding: "A nil channel is a bug, nothing more." Inside select it is a tool: setting a channel variable to nil disables that case, which is how a merge loop stops reading from an input that has closed (select owns the pattern).

Definition: "The value of an uninitialized channel is nil." "A nil channel is never ready for communication." "Receiving from a nil channel blocks forever." "A send on a nil channel blocks forever." len and cap of a nil channel are 0. The goroutine dump shows the wait reason chan receive (nil chan) or chan send (nil chan) (constants in runtime/runtime2.go).

text
1  type Server struct{ events chan Event }   // field never initialised
2  s := &Server{}
3  go s.produce()       // s.events <- e  -> blocks forever, wait reason "chan send (nil chan)"
4  for e := range s.events { ... }           // blocks forever too
5  if only main is left -> fatal error: all goroutines are asleep - deadlock!

Real scenario: a struct literal that forgot make(chan ...) in its constructor; a zero-value config passed to a library that expects a channel; deliberately setting in1 = nil after it closes so a two-input merge keeps reading only in2.

Operation on nilResult
SendBlocks forever
ReceiveBlocks forever
rangeBlocks forever
closepanic: close of nil channel
len, cap0
In selectThe case is never chosen

Fix / how to use it: create channels in constructors (New... functions), never rely on a zero value having a usable channel, and use nil on purpose only inside select.

Ownership and lifecycle: generator, pipeline, done channel Must-know ​

In plain words: every channel should have one owner: the goroutine that creates it, sends on it and closes it. Everyone else only reads. Readers who want to stop early say so on a separate channel.

Common misunderstanding: "If the consumer stops reading, the producer will notice." It will not. A producer blocked on out <- v waits forever; the pipeline article: "if a stage fails to consume all the inbound values, the goroutines attempting to send those values will block indefinitely."

Definition: a generator is a function that returns <-chan T and starts a goroutine that sends values and closes the channel. A pipeline is, in the Go blog's words, "a series of stages connected by channels, where each stage is a group of goroutines running the same function"; each stage receives from upstream, sends downstream, and "stages close their outbound channels when all the send operations are done." For early exit, the consumer closes a done channel (chan struct{}); every stage sends inside a select with case <-done: return. Because "a receive operation on a closed channel can always proceed immediately", closing done is "effectively a broadcast signal" to all of them. A context.Context is the standard library's packaged done channel: ctx.Done() returns a <-chan struct{} that is closed on cancel or deadline (context).

Each stage owns (creates, sends on, closes) its output; done is closed by the consumerGendefer close(out)Sqrange in; defer close(out)consumertakes 2, then stops<-chan int<-chan intclose(done)done chan struct{}: closing it wakes every select on <-done at once (broadcast)case <-done: returncase <-done: return
text
1  consumer: done := make(chan struct{}); defer close(done)
2  consumer: for v := range Sq(done, Gen(done, 1,2,3,4,5))
3  Gen:      out <- 1  -> Sq: out <- 1  -> consumer gets 1
4  Gen:      out <- 2  -> Sq: out <- 4  -> consumer gets 4, has 2 values, breaks
5  Gen:      blocked in select on out <- 3 ... Sq blocked on out <- 9
6  consumer: returns -> deferred close(done)
7  Gen, Sq:  case <-done: return; deferred close(out) runs; both goroutines exit

Real scenario: a file walker emits paths, a hashing stage computes SHA-256, a writer stage saves results; the HTTP handler that reads the first 10 search hits and returns while the search goroutines are still producing; an event stream adapter that must stop when the WebSocket client disconnects.

PatternOwner closesStop signalLeak risk if missing
GeneratorThe generator goroutine (defer close(out))done / ctx.Done()Generator blocked on send forever
Pipeline stageEach stage, its own outputShared doneEvery upstream stage blocked
Fan-in (merge)A closer goroutine after wg.Wait()Shared doneOutput never closed, range never ends
Request with timeoutThe worker sends at most once into a cap-1 channelctxWorker blocked after caller left
Iterator alternativeNo channel: iter.Seqyield returns falseNone (no goroutine)

Fix / how to use it: the pipeline package; its tests run under goleak.VerifyTestMain, so a stage that fails to exit fails the package:

go
// Package pipeline builds a generator and a pipeline stage that both stop
// when the consumer closes a done channel or cancels a context.
package pipeline

import "context"

// Gen is a generator: it emits nums on a channel it owns and closes. It also
// returns early when done is closed, so an impatient consumer cannot leak it.
func Gen(done <-chan struct{}, nums ...int) <-chan int {
	out := make(chan int)
	go func() {
		defer close(out)
		for _, n := range nums {
			select {
			case out <- n:
			case <-done: // the consumer gave up: stop sending and exit
				return
			}
		}
	}()
	return out
}

// Sq is a pipeline stage: it receives from in, squares, and sends on its own
// output channel, which it closes when in is closed or done is closed.
func Sq(done <-chan struct{}, in <-chan int) <-chan int {
	out := make(chan int)
	go func() {
		defer close(out)
		for n := range in {
			select {
			case out <- n * n:
			case <-done:
				return
			}
		}
	}()
	return out
}

// FirstSquares reads only k results and then closes done. Every upstream
// goroutine sees the close (a broadcast) and exits.
func FirstSquares(k int, nums ...int) []int {
	done := make(chan struct{})
	defer close(done)
	var got []int
	for v := range Sq(done, Gen(done, nums...)) {
		got = append(got, v)
		if len(got) == k {
			break
		}
	}
	return got
}

// GenCtx is the same generator with a context: ctx.Done() is a receive-only
// channel that is closed on cancel or deadline, exactly like done above.
func GenCtx(ctx context.Context, nums ...int) <-chan int {
	out := make(chan int)
	go func() {
		defer close(out)
		for _, n := range nums {
			select {
			case out <- n:
			case <-ctx.Done():
				return
			}
		}
	}()
	return out
}

Signalling with chan struct{} Important ​

In plain words: sometimes there is no value to send, only an event: "ready", "done", "stop". A chan struct{} carries such events without carrying data.

Common misunderstanding: "chan bool is the same." It works, but true versus false invites a meaning that is not there, and readers wonder whether false is ever sent. struct{} has size zero and says "this is a signal".

Definition: struct{} is the empty struct type, zero bytes. A one-to-one signal is a send of struct{}{} (or a close). A one-to-many broadcast is close(ch): every current and future receiver proceeds at once. A closed channel cannot be reopened, so a broadcast happens once; repeated events need a new channel or a sync.Cond (sync & atomic).

text
1  ready := make(chan struct{})
2  G1..G40: <-ready                 // all 40 park
3  main:   load config
4  main:   close(ready)             // one statement wakes all 40
5  G41 (late): <-ready              // proceeds at once: closed channels are always ready

Real scenario: "server is listening" signal for a test; a shutdown broadcast to all workers; ctx.Done() itself; a "first result wins, stop the others" race.

NeedMechanismRepeatable?
Tell one goroutine oncech <- struct{}{} on unbufferedYes, per send
Tell all goroutines onceclose(ch)No, once
Tell all, possibly repeatedlysync.Cond.Broadcast or new channel per roundYes
Cancellation treecontext.WithCancelOnce per context

Fix / how to use it: Handoff in the unbuffered snippet uses chan struct{}; the pipeline's done is the broadcast form.

Goroutine leaks and how to find them Must-know ​

In plain words: a leaked goroutine is one that will never finish, usually because it waits on a channel that nobody will ever use again. It holds its stack and whatever it references until the process dies.

Common misunderstanding: "A leak is a big bug I would notice." Leaks are small and constant: four goroutines per request that returned early. At 500 requests per second that is 2 000 new goroutines a second; memory climbs for hours, then the pod is killed.

Definition: Code Review Comments: "Goroutines can leak by blocking on channel sends or receives: the garbage collector will not terminate a goroutine even if the channels it is blocked on are unreachable." Typical causes: an early return leaves senders blocked on an unbuffered channel; a receiver waits on a channel nobody closes; a range over a channel whose producer never closes; a goroutine waiting on a mutex or WaitGroup that never completes; a loop that never checks done. Detection tools:

ToolWhat it doesWhen
runtime.NumGoroutine()"returns the number of goroutines that currently exist"Metric on a dashboard; before/after assertions in tests
Goroutine profilepprof.Lookup("goroutine"), /debug/pprof/goroutine?debug=1 groups identical stacks with countsProduction triage: "9 @ ... main.first.func1"
debug=2 dump / SIGQUIT / GOTRACEBACK=allEvery goroutine with its wait reason (chan send, chan receive) and minutes blockedFind who is stuck where
go.uber.org/goleakgoleak.VerifyNone(t) / goleak.VerifyTestMain(m) fail a test that leaves goroutinesCI, every package with concurrency
goroutineleak profileGC-based detection of goroutines blocked on unreachable primitives; /debug/pprof/goroutineleakGo 1.26 experiment, Go 1.27 generally available
testing/synctestsynctest.Test runs a test in a "bubble" with fake time, "waits for all goroutines in the bubble to exit", and fails the test if they deadlockGo 1.25+ tests of timing code
text
1  FirstLeaky(5, work): ch := make(chan int)    // unbuffered
2  G1..G5: ch <- work(i)                       // all five finish work and try to send
3  caller: v := <-ch; return v                  // takes one
4  G2..G5: blocked on "chan send" forever       // ch unreachable from the caller
5  NumGoroutine: +4 per call;  goroutine profile: "4 @ ... leak.FirstLeaky.func1"

Real scenario: a "fastest replica wins" query that leaks the slower replicas' goroutines; a handler that reads one message from a subscription goroutine and returns; a ticker goroutine started in a constructor with no Close; a test suite that passes but leaves goroutines that later interfere with other tests.

Fix / how to use it: give every worker a slot (make(chan int, n)) or a way to give up (select with ctx.Done()), and assert it in tests:

go
// Package leak shows the most common goroutine leak (an early return leaves
// senders blocked on an unbuffered channel) and two fixes.
package leak

import "context"

// FirstLeaky asks n workers and returns the first answer. The other n-1
// goroutines block forever on "ch <- ..." because nobody receives again.
func FirstLeaky(n int, work func(i int) int) int {
	ch := make(chan int) // unbuffered: each send needs a receiver
	for i := range n {
		go func() { ch <- work(i) }()
	}
	return <-ch // returns after one receive; n-1 senders are stuck
}

// FirstBuffered fixes the leak by giving every worker a slot: sends never
// block, the late results are dropped with the channel, and every goroutine exits.
func FirstBuffered(n int, work func(i int) int) int {
	ch := make(chan int, n)
	for i := range n {
		go func() { ch <- work(i) }()
	}
	return <-ch
}

// FirstCtx fixes it with cancellation: losers stop sending when ctx is done.
// Use this when work itself can also observe ctx and stop early.
func FirstCtx(ctx context.Context, n int, work func(ctx context.Context, i int) int) int {
	ctx, cancel := context.WithCancel(ctx)
	defer cancel() // runs on return: tells the losers to give up
	ch := make(chan int)
	for i := range n {
		go func() {
			v := work(ctx, i)
			select {
			case ch <- v:
			case <-ctx.Done():
			}
		}()
	}
	return <-ch
}
go
package leak

import (
	"context"
	"runtime"
	"testing"
	"time"

	"go.uber.org/goleak"
)

// settle polls runtime.NumGoroutine until it stops changing.
func settle() int {
	prev := -1
	for range 50 {
		n := runtime.NumGoroutine()
		if n == prev {
			return n
		}
		prev = n
		time.Sleep(10 * time.Millisecond)
	}
	return prev
}

func TestFirstLeakyLeaks(t *testing.T) {
	before := settle()
	FirstLeaky(5, func(i int) int { return i })
	if leaked := settle() - before; leaked != 4 {
		t.Fatalf("leaked %d goroutines; want 4", leaked)
	}
	// goleak sees them too; they stay blocked until the test binary exits.
	if err := goleak.Find(); err == nil {
		t.Fatal("goleak.Find found no leak")
	}
}

func TestFirstBufferedNoLeak(t *testing.T) {
	defer goleak.VerifyNone(t, goleak.IgnoreCurrent()) // ignore the leaky test's goroutines
	FirstBuffered(5, func(i int) int { return i })
}

func TestFirstCtxNoLeak(t *testing.T) {
	defer goleak.VerifyNone(t, goleak.IgnoreCurrent())
	FirstCtx(context.Background(), 5, func(_ context.Context, i int) int { return i })
}

Deadlock: all goroutines are asleep Must-know ​

In plain words: if every goroutine is waiting for something only another waiting goroutine could do, nothing can ever move. When the runtime can see that this is true for the whole program, it stops it.

Common misunderstanding: "The runtime detects deadlocks." It detects only the case where no goroutine can run and none is waiting on the network, timers or system calls. Two goroutines stuck on each other while an HTTP server keeps running is a partial deadlock: no error, just a leak.

Definition: when the scheduler finds no runnable goroutine and nothing that could wake one, runtime.checkdead calls fatal("all goroutines are asleep - deadlock!"). The process prints fatal error: all goroutines are asleep - deadlock!, a dump of every goroutine with its wait reason, and exits with status 2. It is a fatal error, not a panic: recover cannot catch it.

text
1  main: ch := make(chan int)
2  main: ch <- 1                 // unbuffered, no receiver goroutine exists
3  runtime: no G runnable, no timers, no netpoll waiters
4  fatal error: all goroutines are asleep - deadlock!
5  goroutine 1 [chan send]:      // the wait reason names the operation

Real scenario: sending on an unbuffered channel in main before starting the receiver; wg.Wait() with a forgotten Done; range over a channel that is never closed in a small program; two goroutines each waiting to receive from the other.

FormDetected by runtime?How you see it
Every goroutine blocked on channels/locksYesfatal error: all goroutines are asleep - deadlock!
Some goroutines blocked, others serving HTTPNoGrowing goroutine count, stuck requests
Blocked on nil channel onlyYes, if nothing else runsgoroutine 1 [chan receive (nil chan)]
Mutex lock-order deadlockYes only if whole program stalls[sync.Mutex.Lock] in the dump
Waiting on a timer that will fireNo, not a deadlockProgram resumes when it fires

Fix / how to use it: start receivers before sending on unbuffered channels; make sure every range has a closer and every Wait has its Dones. The lab runs cmd/crash for each failure; lock-order deadlocks are taught in Race Conditions & Deadlocks.

go
// Command crash reproduces the channel failures this chapter quotes.
// Usage: go run ./cmd/crash deadlock|nil-recv|send-closed|close-closed|close-nil|leakcount
package main

import (
	"fmt"
	"os"
	"runtime"
	"time"
)

func main() {
	if len(os.Args) < 2 {
		fmt.Println("usage: crash deadlock|nil-recv|send-closed|close-closed|close-nil|leakcount")
		os.Exit(2)
	}
	switch os.Args[1] {
	case "deadlock":
		ch := make(chan int)
		ch <- 1 // no receiver exists: main blocks, no other goroutine can run
	case "nil-recv":
		var ch chan int
		<-ch // a nil channel is never ready
	case "send-closed":
		ch := make(chan int, 1)
		close(ch)
		ch <- 1
	case "close-closed":
		ch := make(chan int)
		close(ch)
		close(ch)
	case "close-nil":
		var ch chan int
		close(ch)
	case "leakcount":
		fmt.Println("before:", runtime.NumGoroutine())
		ch := make(chan int)
		for i := range 100 {
			go func() { ch <- i }() // nobody will receive 99 of these
		}
		<-ch
		time.Sleep(50 * time.Millisecond)
		fmt.Println("after: ", runtime.NumGoroutine())
	}
}

What channels guarantee: the memory model Important ​

In plain words: when you receive a value from a channel, you also see everything the sender wrote before it sent. That is why channels can safely hand over a pointer to a big struct.

Common misunderstanding: "Any channel operation orders everything." The guarantee is per pair of operations: the write must happen before the send in the sender, and the read must happen after the receive in the receiver. A write after the send is a data race, even though a channel is involved (the lab reproduces WARNING: DATA RACE for exactly that).

Definition: the Go Memory Model's channel rules: (1) "A send on a channel is synchronized before the completion of the corresponding receive from that channel." (2) "The closing of a channel is synchronized before a receive that returns a zero value because the channel is closed." (3) "A receive from an unbuffered channel is synchronized before the completion of the corresponding send on that channel." (4) "The kth receive from a channel with capacity C is synchronized before the completion of the k+Cth send on that channel." Also: "The go statement that starts a new goroutine is synchronized before the start of the goroutine's execution", while the exit of a goroutine is not synchronised with anything. With a buffered channel, rule (3) does not apply: the memory-model document notes the swapped example "would not be guaranteed to print" with make(chan int, 1). Its advice: "If you must read the rest of this document to understand the behavior of your program, you are being too clever. Don't be clever."

text
     G1 (sender)                              G2 (receiver)
1    order.Total = 120          (write)
2    ch <- order                (send)  ----> synchronized before
3                                             o := <-ch     (receive completes)
4                                             print(o.Total) // guaranteed 120
5    order.Total = 0            (write after send: RACE with line 4)

Real scenario: a parser goroutine fills a *Batch and sends the pointer to a writer goroutine, then must never touch it again (ownership moved); a config reloader closes a loaded channel after writing a package variable, and readers wait on <-loaded first; a semaphore channel bounding concurrent work (rule 4).

RuleLets youDoes not give you
Send before receive completesPass data with the messageSafety for writes after the send
Close before zero receivePublish state then broadcast "ready"A way to send further updates
Unbuffered receive before send completesSender knows receiver has started using itSame with a buffer
kth receive before (k+C)th sendCounting semaphore with cap slotsFairness or ordering among waiters
go before goroutine startArguments and prior writes visible to the new goroutineVisibility of its writes to you without sync

Fix / how to use it: treat a send as "I give this away"; after sending a pointer, stop using it. If both sides must keep using a value, protect it with a mutex instead.

Semaphores and bounded queues Important ​

In plain words: a buffered channel of size N is a bowl with N tokens. Take a token before you start, put it back when you finish; when the bowl is empty, you wait. That limits how many goroutines do something at once.

Common misunderstanding: "An unbounded queue would be more robust: nothing ever blocks." Something always fills up. If the producer is faster than the consumer, an unbounded buffer turns "slow" into "out of memory", and the latency of every queued item grows without limit. Blocking is the signal that tells the producer to slow down (backpressure).

Definition: Effective Go: "A buffered channel can be used like a semaphore, for instance to limit throughput." The memory model rule (4) makes it correct: "the number of items in the channel corresponds to the number of active uses, the capacity of the channel corresponds to the maximum number of simultaneous uses, sending an item acquires the semaphore, and receiving an item releases the semaphore." golang.org/x/sync/semaphore offers a weighted version with context support. A bounded queue is a buffered channel whose size you chose and whose full state you handle (block, drop, or reject with an error); an unbounded queue in Go is usually a slice that grows behind a goroutine, an anti-pattern unless something else bounds it.

text
1  sem := make(chan struct{}, 4)          // 4 tokens
2  G1..G4: sem <- struct{}{}              // acquired, run
3  G5:     sem <- struct{}{}              // blocks: bowl empty
4  G2:     <-sem                          // release
5  G5:     acquired, runs                 // never more than 4 inside

Real scenario: at most 10 concurrent calls to a payment provider that rate-limits; at most 20 concurrent queries so the database connection pool (SetMaxOpenConns(20)) is not exceeded; an image service that would exhaust memory decoding 500 uploads at once; a log channel of 10 000 entries that drops (and counts) entries when full instead of blocking requests.

Strategy when fullBehaviourUse when
Block (plain send)Producer slows down: backpressureProducer can wait (batch jobs, pipelines)
Drop (select with default)Item discarded, count itTelemetry, best-effort logs
Reject (return an error, HTTP 503/429)Caller decidesRequest handling, load shedding
Grow without boundMemory and latency growNever, unless another limit exists

Fix / how to use it: Semaphore and RunLimited in the buffered snippet; the test asserts the observed peak never exceeds the limit. Queue-level backpressure between services is in Backpressure & Flow Control; rate limits over time (not just concurrency) are in Rate Limiting in Go.

Channels versus mutexes, and channels of channels Important ​

In plain words: use a channel when you are passing work or ownership from one goroutine to another; use a mutex when several goroutines just need to take turns touching the same small piece of state.

Common misunderstanding: "Idiomatic Go never uses mutexes." The standard library is full of them. Effective Go itself says the slogan "can be taken too far" and that reference counts may be "best done by putting a mutex around an integer variable". The Go wiki page "Use a sync.Mutex or a channel?" says the same: "Use whichever is most expressive and/or most simple."

Definition: the owner goroutine pattern keeps state inside one goroutine and serves requests that arrive on a channel; each request carries its own reply channel, a channel of channels (Effective Go's example: type Request struct { args []int; f func([]int) int; resultChan chan int }). The mutex pattern keeps state in a struct with a sync.Mutex and locks in each method. Both are race-free; they differ in cost and in what else they can express (the owner can also batch, time out, or run a state machine).

text
     caller G1                        owner goroutine                 caller G2
1    reply := make(chan int, 1)
2    reqs <- {k, +1, reply} ------->  counts[k]++                    reply2 := make(chan int, 1)
3                                     reply <- counts[k]             reqs <- {k, +1, reply2}  (waits its turn)
4    v := <-reply                     counts[k]++ ; reply2 <- ...
5                                                                     v2 := <-reply2

Real scenario: a connection manager goroutine that owns the map of live sessions and also handles timeouts and broadcasts (owner wins); a per-process cache map read by every handler (mutex or sync.Map wins); a rate-limiter state machine (owner or mutex, both fine); a request/response over channels inside one process, the in-process cousin of request-reply messaging.

CriterionChannel / owner goroutineMutex
Uncontended cost per operation (this machine, see lab)~231 ns (two channel ops and a goroutine switch)~23 ns
ExpressesTransfer of ownership, events, pipelines, timeouts via selectExclusive access to shared state
LifecycleOwner goroutine must be started and stoppedNone
Failure modeLeak or deadlock if owner exitsForgotten Unlock, lock ordering
Best forWork queues, event loops, stateful protocolsCounters, caches, small structs

Fix / how to use it: both versions with the same API, hammered by 8 goroutines under -race:

go
// Package reqresp compares two ways to protect a map of counters: one
// goroutine that owns the map and answers requests carrying a reply channel
// (a channel of channels), and a plain mutex.
package reqresp

import "sync"

type request struct {
	key   string
	delta int
	reply chan int // the owner answers here: request/response over channels
}

// Owner keeps the map inside one goroutine; nobody else touches it.
type Owner struct {
	reqs chan request
	done chan struct{}
}

// NewOwner starts the owning goroutine.
func NewOwner() *Owner {
	o := &Owner{reqs: make(chan request), done: make(chan struct{})}
	go o.loop()
	return o
}

func (o *Owner) loop() {
	defer close(o.done)
	counts := map[string]int{} // only this goroutine reads or writes it
	for r := range o.reqs {
		counts[r.key] += r.delta
		r.reply <- counts[r.key]
	}
}

// Add adds delta to key and returns the new value.
func (o *Owner) Add(key string, delta int) int {
	reply := make(chan int, 1) // buffered: the owner never blocks on a slow caller
	o.reqs <- request{key, delta, reply}
	return <-reply
}

// Close stops the owner and waits for it to exit. Call it once, after the
// last Add: closing reqs while an Add is sending would panic.
func (o *Owner) Close() {
	close(o.reqs)
	<-o.done
}

// Locked is the mutex version of the same API.
type Locked struct {
	mu     sync.Mutex
	counts map[string]int
}

// NewLocked returns an empty Locked counter.
func NewLocked() *Locked { return &Locked{counts: map[string]int{}} }

// Add adds delta to key and returns the new value.
func (l *Locked) Add(key string, delta int) int {
	l.mu.Lock()
	defer l.mu.Unlock()
	l.counts[key] += delta
	return l.counts[key]
}

runtime.Gosched, time.After leaks and sync.Once Good to know ​

In plain words: three small tools that come up next to goroutines. runtime.Gosched lets other goroutines run; time.After gives you a channel that fires once; sync.Once runs something exactly once even if many goroutines ask.

Common misunderstanding: "runtime.Gosched() makes my goroutines take turns, so I can rely on it for ordering." It is a hint that yields the processor; it provides no happens-before edge and no ordering. And "time.After in a loop leaks timers": true before Go 1.23, no longer true when the module says go 1.23 or later.

Definition: runtime.Gosched "yields the processor, allowing other goroutines to run. It does not suspend the current goroutine, so execution resumes automatically." Since Go 1.14's asynchronous preemption it is almost never needed. time.After(d) "is equivalent to NewTimer(d).C". Before Go 1.23 an unstopped timer was not collected until it fired, so select { case <-ch: case <-time.After(time.Minute): } in a busy loop kept one live timer per iteration for a minute; Go 1.23 made unreferenced timers collectable and timer channels unbuffered, enabled "only when the main Go program is in a module with a go.mod go line using Go 1.23.0 or later" (GODEBUG=asynctimerchan=1 reverts). The time.After doc now says "There is no reason to prefer NewTimer when After will do." sync.Once (and sync.OnceFunc/OnceValue, Go 1.21) runs a function once; it is the safe way to make a Close idempotent when it must close a channel. All three are taught in their own chapters: select for timers in select, sync & atomic for Once.

text
1  for { select { case m := <-msgs: handle(m); case <-time.After(time.Minute): idle() } }
2  go 1.22 module: each iteration creates a timer that lives ~1 minute -> 10k msgs/s = 600k live timers
3  go 1.23+ module: an iteration's timer is unreferenced after select returns -> collectable
4  either version: a fresh 1-minute timer per message; reset semantics = "1 minute since the last message"

Real scenario: an idle-timeout loop on a message consumer; a Close method called by both a signal handler and a deferred cleanup; a CPU-bound loop someone "fixed" with Gosched in 2015 that no longer needs it.

ToolSinceUseDo not use for
runtime.Gosched()Go 1.0Rare: tests of scheduler behaviour, very long spin loopsOrdering or synchronisation
time.After(d)Go 1.0, GC-friendly since 1.23One-off timeout in selectHot loops in pre-1.23 modules
time.NewTimer + Stop/ResetGo 1.0Reusable timer in a loopCode where After is enough
sync.Once / OnceFuncGo 1.0 / 1.21Idempotent close, lazy initRepeated events

Fix / how to use it: keep go 1.23+ in go.mod (this module's go 1.24 qualifies), use time.NewTimer with Reset when one timer should be reused, and wrap close in sync.Once when several paths may call it.

Go ​

Example ​

The snippets under docs/snippets/go/goroutines-channels/go/ are one module with seven tested packages and one demo command. The only dependency is go.uber.org/goleak v1.3.0, used by the leak and pipeline tests. A single run checks them all:

bash
cd docs/snippets/go/goroutines-channels/go
gofmt -l . && go vet ./... && go test -race ./...
mod
module academy/goroutines-channels

go 1.24

require go.uber.org/goleak v1.3.0

The concept blocks above import spawn, rendezvous, buffered, closing, pipeline, leak, reqresp and cmd/crash. Each package's _test.go file is the executable specification: closing_test.go asserts the three exact panic strings, buffered_test.go asserts len/cap after each step, leak_test.go asserts that FirstLeaky leaves exactly 4 goroutines and that the fixed versions leave none.

The Go angle ​

Go puts concurrency in the language (go, chan, select, <-) and everything else in the standard library: sync for WaitGroup, Mutex, Once; context for cancellation; runtime for NumGoroutine, GOMAXPROCS, Gosched; runtime/pprof and net/http/pprof for goroutine and leak profiles; testing/synctest (Go 1.25) for deterministic tests with fake time. The race detector (-race) and vet analyzers (copylocks, lostcancel, waitgroup) catch the common mistakes mechanically. The standard library follows the ownership rule: functions return receive-only channels (time.After, ctx.Done(), signal.Notify takes a send-only channel you own), and most APIs are synchronous, leaving concurrency to the caller. Third-party code in this chapter is limited to go.uber.org/goleak.

For PHP/Laravel developers ​

PHP has no goroutines and no preemptive in-process concurrency in the default runtime. Concurrency in a Laravel application comes from many processes (PHP-FPM workers, queue:work workers, Horizon supervisors), and coordination goes through Redis, a database or a broker.

NeedPHP / LaravelGo
Handle many requests at oncePHP-FPM pool of processes, one request per processOne process, one goroutine per connection
Background jobdispatch(new Job) to Redis/SQS/database queue, queue:work processgo f() in-process, or a durable queue when it must survive restarts
Wait for parallel tasksBus::batch([...])->then(...), Concurrency::run([...]) (separate processes)sync.WaitGroup, errgroup
Cooperative coroutinesFibers (PHP 8.1): "full-stack, interruptible functions" suspended with Fiber::suspend(); you schedule them yourselfGoroutines, scheduled and preempted by the runtime
Coroutines with I/O hooksSwoole / Open Swoole: coroutines, Coroutine\Channel, WaitGroup (extension, not core PHP)Built in
Message passingQueue payloads, Redis pub/subChannels
Leak symptomA stuck worker process (killed by --timeout/--max-jobs)A stuck goroutine inside a long-lived process
php
<?php
// Fiber: cooperative, single-threaded, explicitly resumed. Nothing runs in parallel.
$fiber = new Fiber(function (string $x): string {
    $y = Fiber::suspend($x . ' suspended');  // gives control back to the caller
    return $y . ' finished';
});
echo $fiber->start('job'), PHP_EOL;          // "job suspended"
$fiber->resume('job');
echo $fiber->getReturn(), PHP_EOL;           // "job finished"

The big difference for a Laravel developer: in PHP-FPM every request starts with empty memory and ends by throwing it away, so a "leaked" coroutine dies with the request. A Go server lives for weeks; a goroutine that never exits accumulates. Laravel's queue worker options (--timeout, --max-jobs, --max-time) exist because long-lived PHP processes have the same problem in a coarser form. Swoole's channels and WaitGroup look like Go's but live in an extension with its own scheduler hooks; they are not part of PHP itself.

Mechanics ​

What a channel is in memory ​

make(chan T, n) allocates a runtime.hchan (Go 1.27.4 runtime/chan.go): qcount (current elements), dataqsiz (capacity), buf (circular buffer of dataqsiz elements), elemsize, closed, sendx/recvx (ring indexes), recvq/sendq (queues of waiting goroutines, as sudog records) and a lock. A channel value is a pointer to this struct, which is why copying a channel variable shares the channel.

OperationRuntime path (simplified)
Send, receiver waiting in recvqCopy the value directly to the receiver's stack, mark it runnable (no buffer touched)
Send, buffer has roomCopy into buf[sendx], advance sendx, qcount++
Send, no room and no receiverEnqueue a sudog on sendq, park with wait reason chan send
Receive, sender waiting, unbufferedCopy directly from the sender, wake it
Receive, buffer non-emptyTake buf[recvx]; if a sender waits, move its value into the freed slot and wake it
Receive, empty, closedReturn zero value, ok = false
closeSet closed, wake every waiting receiver (zero values) and every waiting sender (they panic)
nil channelPark forever with chan send (nil chan) / chan receive (nil chan)

Exact messages ​

SituationMessage (Go 1.27.4)
Whole program blockedfatal error: all goroutines are asleep - deadlock! then goroutine 1 [chan send]:
Same, on a nil channelgoroutine 1 [chan receive (nil chan)]:
Send on closed channelpanic: send on closed channel
Close twicepanic: close of closed channel
Close nilpanic: close of nil channel
Negative WaitGrouppanic: sync: negative WaitGroup counter
WaitGroup reusepanic: sync: WaitGroup is reused before previous Wait has returned
vet, Add in goroutine (Go 1.25+)WaitGroup.Add called from inside new goroutine
Send on receive-onlyinvalid operation: cannot send to receive-only channel <-chan int ch (variable of type <-chan int)
Close receive-onlyinvalid operation: cannot close receive-only channel ch (variable of type <-chan int)
Receive on send-onlyinvalid operation: cannot receive from send-only channel chan<- int ch (variable of type chan<- int)
Race detectorWARNING: DATA RACE then Read at ... by main goroutine: / Previous write at ... by goroutine 7:; exit status 66
goleak failurefound unexpected goroutines: followed by the stacks
Unrecovered panic in a goroutinepanic: ... then goroutine N [running]:; the whole process exits with status 2

Knobs and settings ​

KnobEffect
GOMAXPROCS=nNumber of P; disables Go 1.25's automatic cgroup updates
runtime.GOMAXPROCS(0)Read the current value without changing it
GODEBUG=containermaxprocs=0 / updatemaxprocs=0Go 1.25: ignore cgroup limit / stop periodic updates
GODEBUG=asynctimerchan=1Go 1.23+: old buffered timer channels
GODEBUG=asyncpreemptoff=1Disable asynchronous preemption (debugging)
GOTRACEBACK=all / crashPrint every goroutine on a fatal error / also dump core
GODEBUG=schedtrace=1000Print scheduler state every 1000 ms
kill -QUIT pidDump all goroutine stacks and exit
/debug/pprof/goroutine?debug=2Full goroutine dump over HTTP (net/http/pprof)
/debug/pprof/goroutineleakLeak profile (Go 1.27; Go 1.26 behind GOEXPERIMENT=goroutineleakprofile)
debug.SetMaxThreads(n)Cap on OS threads (default 10 000); exceeding it crashes
go test -raceRace detector; required for every package on this page

Solving the classic problems ​

ProblemSolutionHowAdvantageCost or limit
main exits before goroutines finishWait explicitlyWaitGroup / wg.GoDeterministicNo error propagation (use errgroup)
Early return leaks sendersBuffer for every sender, or cancelmake(chan T, n) or select with ctx.Done()No leakMust know n; ctx needs plumbing
Consumer stops early in a pipelineDone channel / contextcase <-done: return in each stageBroadcast to all stagesEvery send needs a select
Several senders, who closes?Closer goroutinewg.Wait(); close(out)One closerOne extra goroutine
Double close in two pathsSingle owner, or sync.Onceonce.Do(func() { close(ch) })No panicHides a design smell if overused
Unbounded goroutines per inputSemaphore or worker poolsem := make(chan struct{}, N)Bounded memory, bounded load downstreamThroughput capped at N
Producer outruns consumerBounded buffer with a full policyBlock, drop, or rejectBackpressure visibleMust choose a policy
Shared map under concurrencyMutex (or owner goroutine)sync.MutexSimple, fastContention at high core counts
Goroutine must stop on shutdownContext from mainsignal.NotifyContext → ctx.Done()One cancellation treeEvery loop must check it
Leak in testsgoleakgoleak.VerifyTestMain(m)Fails CI on leaksThird-party dependency
Leak in productionMetrics + profilesNumGoroutine gauge, /debug/pprof/goroutine, goroutineleakEarly warningProfiles need an admin port

Bounding goroutines that hit the database ​

A semaphore or worker pool is also how you protect a database from your own concurrency. If 500 goroutines each run a query and the pool allows 20 connections, 480 wait inside database/sql (see Connection Pooling and database/sql & pgx); with an explicit sem := make(chan struct{}, 20) the waiting is visible in your code and can be bounded with a context. Check on the PostgreSQL side what your goroutines are doing:

sql
-- How many connections does each application hold, and what are they doing?
SELECT application_name, state, count(*) AS conns,
       max(now() - state_change) AS longest_in_state
FROM pg_stat_activity
WHERE datname = current_database()
GROUP BY application_name, state
ORDER BY conns DESC;

If idle in transaction dominates, goroutines are holding transactions open while blocked on a channel or an outbound call: move the channel operation outside the transaction.

Closing a channel that several goroutines send on ​

go
func merge(done <-chan struct{}, inputs ...<-chan int) <-chan int {
	out := make(chan int)
	var wg sync.WaitGroup
	for _, in := range inputs {
		wg.Add(1)
		go func() {
			defer wg.Done()
			for v := range in {
				select {
				case out <- v:
				case <-done:
					return
				}
			}
		}()
	}
	go func() { wg.Wait(); close(out) }() // the only closer: after every sender is done
	return out
}

The full fan-in/fan-out treatment, with errgroup and bounded worker pools, is in Worker Pools & Pipelines.

Choosing ​

NeedUseWhyAvoid
Run something concurrently and waitwg.Go (1.25+) or Add/Done/WaitSimple, no allocation per resulttime.Sleep
Run, wait, first error cancels the resterrgroup.WithContextError + cancellationHand-rolled error channels
Pass a result from one goroutineUnbuffered, or cap-1 if the sender must not blockClear handoffShared variable with a flag
Results from N workers, caller may leave earlymake(chan T, N)No leakUnbuffered
Stream of values with an endGenerator returning <-chan T that closesrange ends naturallySentinel values
Lazy sequence in one goroutineiter.Seq (Functions)No goroutine, no leakA channel generator for pure computation
Stop many goroutinesclose(done) or ctx cancelBroadcastSending N stop messages
Limit concurrencyBuffered chan struct{} or worker poolBackpressureUnlimited go
Counter, cache, small shared structsync.Mutex / atomics10x cheaper than a channel round trip hereAn owner goroutine
Stateful protocol, event loop, timeoutsOwner goroutine with selectOne goroutine owns all transitionsMany locks
Several channels or a timeoutselectBuilt for itlen(ch) polling

In architecture: from a single process to a distributed system ​

Monolith (one process, one database) ​

Inside one Go binary, goroutines are the unit of concurrency and channels the in-process pipes. net/http gives each connection a goroutine; your handlers stay synchronous. Background work (email, thumbnails, cache warm-up) runs in goroutines started from main and stopped through one root context created by signal.NotifyContext (OS Processes & Signals). Example: main starts an http.Server, a metrics flusher and an outbox poller; on SIGTERM it cancels the context, calls srv.Shutdown, and waits on a WaitGroup for the flusher and poller before closing the database pool. The one rule that keeps a monolith healthy: every go statement is in code that also knows how that goroutine ends.

Modular monolith / multiple databases ​

Modules communicate through function calls, not channels, at their public boundary: exposing a chan in a module API couples both sides to its buffer size, its closing rules and its lifecycle. Inside a module, an owner goroutine can serialise access to module state (an in-process event bus, a cache with refresh). If modules exchange events in-process, give the bus a bounded buffer per subscriber and a policy for slow subscribers (drop with a metric, or block the publisher); an unbounded in-memory bus is a memory leak waiting for a slow consumer. Each module gets its own semaphore for its own database so one module cannot take every connection.

Microservices ​

A channel does not cross a process boundary. Its guarantees (handoff, happens-before, close as "end of stream") have to be rebuilt with a network protocol: a request/response becomes HTTP or gRPC with a deadline; a buffered channel becomes a broker queue (Event-Driven Go); close becomes an explicit end-of-stream message or a stream termination in gRPC; backpressure becomes broker prefetch limits, HTTP 429/503 and client retries with jitter (Timeouts, Retries & Jitter). Example flow: an orders service handler gets a request, starts three goroutines (inventory, pricing, fraud) with errgroup.WithContext and a 300 ms deadline, each makes a gRPC call that carries the deadline; the first error cancels the context, the other two calls are abandoned on the server side too. A worker service consuming a RabbitMQ queue uses a fixed pool of goroutines equal to the prefetch count (Competing Consumers), so in-process concurrency matches what the broker will deliver.

Distributed data (replicas, caches, multi-region) ​

Fan-out reads against replicas or cache shards are the classic leak site: "ask three replicas, take the fastest" must buffer the results channel to three or cancel the losers, otherwise every request leaks two goroutines and two connections. Hedged requests (send a second request after the p95 latency) are a select over a timer and two result channels (select). Per-shard goroutines that stream changes (CDC readers, Redis keyspace subscriptions) are long-lived owners: each needs a restart policy and a stop signal, and a slow downstream must not grow an unbounded buffer. Ordering guarantees end at the channel: two goroutines writing to two replicas through two channels give no order between them; if order matters, one owner goroutine per key or partition preserves it.

Scaling path ​

ScaleWhat changes for goroutines and channelsExample
1x: a few requests per secondClarity first; synchronous handlers; a few background goroutines with a stop signalOne flusher goroutine, WaitGroup on shutdown
10x: hundreds per secondLeaks and unbounded fan-out show up; add limits and metricsNumGoroutine gauge, semaphores around outbound calls, goleak in CI
100x: thousands per second per instanceChannel contention and goroutine churn in profiles; batch and shardPer-core sharded owners, batching sends, mutex instead of owner where state is small
Many instancesIn-process channels become broker queues; concurrency limits per instance multiplyGlobal limit = per-instance limit × replicas; set it from the database's capacity
Containers with CPU limitsGOMAXPROCS must match the limitGo 1.25+ does it automatically; older: set GOMAXPROCS

Lab ​

All commands run on a laptop with Go installed; no network or Docker is needed. The outputs below were produced with Go 1.27.4 on macOS (darwin/arm64, 12 logical CPUs); file paths in stack traces are shortened to the module-relative part.

Setup

bash
cd docs/snippets/go/goroutines-channels/go
go version
gofmt -l . && go vet ./... && go test -race ./...

Output (verified):

text
go version go1.27.4 darwin/arm64
ok  	academy/goroutines-channels/buffered
ok  	academy/goroutines-channels/closing
?   	academy/goroutines-channels/cmd/crash	[no test files]
ok  	academy/goroutines-channels/leak
ok  	academy/goroutines-channels/pipeline
ok  	academy/goroutines-channels/rendezvous
ok  	academy/goroutines-channels/reqresp
ok  	academy/goroutines-channels/spawn

Experiment 1: the deadlock detector

bash
go run ./cmd/crash deadlock; echo "exit $?"
go run ./cmd/crash nil-recv
text
fatal error: all goroutines are asleep - deadlock!

goroutine 1 [chan send]:
main.main()
	.../cmd/crash/main.go:20 +0x198
exit status 2
-- nil-recv --
fatal error: all goroutines are asleep - deadlock!

goroutine 1 [chan receive (nil chan)]:

The wait reason in brackets names the operation. The binary built with go build exits with status 2.

Experiment 2: the three close panics

bash
go run ./cmd/crash send-closed
go run ./cmd/crash close-closed
go run ./cmd/crash close-nil
text
panic: send on closed channel
goroutine 1 [running]:
panic: close of closed channel
goroutine 1 [running]:
panic: close of nil channel
goroutine 1 [running]:

Experiment 3: watch a leak grow

bash
go run ./cmd/crash leakcount
text
before: 1
after:  100

One goroutine received; 99 senders are blocked on chan send forever. Then write the goroutine profile in a scratch program that calls the same leaky function with 10 workers and pprof.Lookup("goroutine").WriteTo(os.Stdout, 1):

text
goroutine profile: total 10
9 @ 0x102ac3f78 0x102a5e224 0x102a5de38 0x102b175c4 0x102aca084
#	0x102b175c3	main.first.func1+0x23	.../prof/main.go:13

Nine identical stacks grouped with a count is what a leak looks like in production profiles. On the same host the goroutineleak profile (Go 1.27) reported total 0 for this tiny program; the release notes describe it as detecting "a large class of such leaks", not all of them, so treat it as an extra signal, not proof of absence.

Experiment 4: a race through a channel

go
var msg string
done := make(chan bool, 1)
go func() {
	done <- true
	msg = "ready" // written after the send: not ordered before main's read
}()
<-done
fmt.Println(msg)
bash
go run -race ./race
text
==================
WARNING: DATA RACE
Read at 0x00c0001a2020 by main goroutine:
  main.main()
      .../race/main.go:13 +0x118

Previous write at 0x00c0001a2020 by goroutine 7:
  main.main.func1()
      .../race/main.go:10 +0x44
==================
ready
Found 1 data race(s)
exit status 66

It printed ready, and it is still a bug: only writes before the send are guaranteed visible after the receive.

Experiment 5: vet catches Add inside the goroutine

go
for range 3 {
	go func() {
		wg.Add(1)
		defer wg.Done()
	}()
}
wg.Wait()
text
wg/main.go:9:10: WaitGroup.Add called from inside new goroutine

Experiment 6: owner goroutine versus mutex

bash
go test -run x -bench . ./reqresp
text
cpu: Apple M4 Pro
BenchmarkOwner-12     	 4943558	       230.9 ns/op
BenchmarkLocked-12    	52332996	        22.83 ns/op

A single uncontended caller: the channel round trip (send request, owner switch, send reply) costs about 10x a lock/unlock. The numbers are for this machine and this pattern only; under heavy contention both change, and the owner pattern earns its cost when the owner does more than one map update.

Experiment 7 (expected, not run): GOMAXPROCS in a CPU-limited container

bash
# ./gmp is a three-line program that prints runtime.GOMAXPROCS(0)
docker run --rm --cpus=2 -v "$PWD":/src -w /src golang:1.25 go run ./gmp
text
2      # Go 1.25+: honours the cgroup CPU limit
12     # Go 1.24 on the same 12-CPU host: logical CPU count

Common misconceptions ​

BeliefReality
Goroutines are threadsThey are multiplexed onto GOMAXPROCS P and any number of OS threads (M:N)
The GC frees stuck goroutines"Goroutines are not garbage collected; they must exit on their own"
A buffered channel is fasterIt changes synchronisation; a full buffer blocks like unbuffered
len(ch) > 0 means a receive won't blockAnother goroutine may take the value first; use select with default
Receivers should close channelsOnly the (single) sender closes; receivers signal stop on a done channel
Every channel must be closedClose only to signal end of stream; unreachable channels are collected
Receiving from a closed channel blocks or panicsIt returns buffered values, then the zero value with ok == false, immediately
GOMAXPROCS caps the number of goroutinesIt caps threads running Go code simultaneously
wg.Add(1) can go inside the goroutineIt must happen before go; vet (1.25+) reports it
The runtime detects every deadlockOnly when no goroutine at all can run
Any channel operation orders all memoryOnly writes before the send are visible after the receive
runtime.Gosched gives orderingIt is a yield hint with no synchronisation
time.After in a loop always leaksNot since Go 1.23 with a go 1.23+ module
Idiomatic Go avoids mutexesEffective Go: the slogan "can be taken too far"; mutexes are idiomatic for shared state

Cheat sheet ​

TopicRemember
go f(x)f and x evaluated now; caller does not wait; main returning ends all
Exit ruleNever start a goroutine without knowing how it stops
Stack2 KB start, grows by copying, 1 GB max on 64-bit
SchedulerG on M via P; GOMAXPROCS P; preemptive since 1.14; cgroup-aware since 1.25
WaitGroupAdd before go, defer Done(), Wait; or wg.Go (1.25)
UnbufferedRendezvous; sender knows the receiver has it
BufferedBlocks only when full/empty; size it for a reason
nil channelSend/receive block forever; close panics; useful in select
CloseSender only, once; send on closed channel, close of closed channel, close of nil channel
Receive after closeBuffered values, then zero and ok == false
range chEnds at close; blocks forever on nil
DirectionsReturn <-chan T, accept chan<- T for producers
Signalschan struct{}; close broadcasts once
LeaksBuffer N, or cancel; goleak in tests; goroutine profile and NumGoroutine in prod
Deadlockfatal error: all goroutines are asleep - deadlock!, exit 2, not recoverable
Memory modelSend before receive completes; close before zero receive; kth receive before (k+C)th send
Semaphoremake(chan struct{}, N); send acquires, receive releases
Mutex vs channelState: mutex. Ownership and flow: channel

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — A function starts five goroutines that each send a result on an unbuffered channel, reads the first result and returns. What happens to the other four, and give two fixes. Must-know ​

Answer

Answer: They block forever on the send: four leaked goroutines per call, never collected. Fix with make(chan T, 5) so every send has a slot, or have each sender select on ctx.Done() and cancel the context on return. See Goroutine leaks.

2 — What does v, ok := <-ch return on a closed channel that still has two buffered values? Must-know ​

Answer

Answer: The two buffered values with ok == true, one per receive; after that, the zero value with ok == false, without blocking. See Closing and range.

3 — Why is wg.Add(1) inside the goroutine wrong, and what reports it? Must-know ​

Answer

Answer: Wait may run before the goroutine starts, see a zero counter and return early. Add before the go statement, or use wg.Go. Go 1.25's vet waitgroup analyzer reports WaitGroup.Add called from inside new goroutine. See WaitGroup.

4 — go log(time.Now()) runs 200 ms later. Which time does it log? Important ​

Answer

Answer: The time the go statement ran: arguments are evaluated in the calling goroutine. See Argument evaluation.

5 — Your program prints fatal error: all goroutines are asleep - deadlock! with goroutine 1 [chan receive (nil chan)]. What is the likely bug? Must-know ​

Answer

Answer: A channel variable or struct field was never initialised with make, so it is nil, and receiving from a nil channel blocks forever. See Nil channels.

6 — Who should close a channel that three worker goroutines send on? Must-know ​

Answer

Answer: None of the workers individually. A separate goroutine waits on a WaitGroup covering the three workers and then closes the channel once. See the closer pattern.

7 — A sender does ch <- p and then modifies p.Total. The receiver reads p.Total after receiving. Is this safe? Important ​

Answer

Answer: No. Only writes before the send are synchronised with the receive. The write after the send races with the receiver's read; -race reports it. See Memory model.

8 — You need at most 10 concurrent calls to a provider. Show the smallest mechanism. Must-know ​

Answer

Answer: sem := make(chan struct{}, 10); before each call sem <- struct{}{}, after it <-sem (in a defer). See Semaphores.

9 — What does GOMAXPROCS control, and what changed in Go 1.25? Important ​

Answer

Answer: The number of P, that is how many threads execute Go code at the same time. Go 1.25 lowers the default to the Linux cgroup CPU limit when it is smaller than the CPU count and updates it periodically, unless set manually. See The scheduler.

10 — When is a mutex a better choice than an owner goroutine with a request channel? Important ​

Answer

Answer: When the job is just exclusive access to small shared state (a counter, a map). On the lab machine the uncontended mutex path was about 10x cheaper, and it needs no goroutine lifecycle. See Channels versus mutexes.

11 — Does time.After inside a for/select loop leak? Important ​

Answer

Answer: Not in a module whose go.mod says go 1.23 or later: unreferenced timers are collected even if not stopped. In older modules each iteration's timer lived until it fired. See Gosched, timers, Once.

Glossary ​

TermMeaning
GoroutineA function executing concurrently in the same address space, managed by the Go runtime
go statementgo f(x): start f(x) in a new goroutine without waiting
Stack growthThe runtime copying a goroutine stack to a larger block when a frame does not fit
SchedulerThe runtime component that assigns runnable goroutines to threads
GMPG (goroutine), M (OS thread), P (processor: the right to run Go code)
M:N schedulingMany goroutines multiplexed onto fewer OS threads
Work stealingAn idle P taking runnable goroutines from another P's queue
PreemptionThe runtime interrupting a running goroutine; asynchronous since Go 1.14
GOMAXPROCSNumber of P; default logical CPUs, cgroup-aware since Go 1.25
NetpollerRuntime integration with epoll/kqueue that parks goroutines waiting on sockets
sync.WaitGroupA counter with Add, Done, Wait for waiting on goroutines
wg.GoGo 1.25 method: Add(1), start f in a goroutine, Done when it returns
errgroupgolang.org/x/sync/errgroup: wait plus first error plus cancellation
ChannelA typed, synchronised FIFO for communication between goroutines
Unbuffered channelCapacity 0; send and receive must meet
RendezvousThe meeting point of a send and a receive on an unbuffered channel
Buffered channelCapacity n > 0; blocks only when full (send) or empty (receive)
Capacitycap(ch): buffer size, fixed at make
lenlen(ch): number of queued elements; for metrics only
nil channelUninitialised channel; never ready; close panics
Directional channelchan<- T (send-only) or <-chan T (receive-only) view of a channel
closeBuilt-in that records "no more values"; only the sender, only once
Send on closed channelRun-time panic send on closed channel
Double closeRun-time panic close of closed channel
Close nil channelRun-time panic close of nil channel
Receive from closed channelReturns remaining buffered values, then the zero value at once with ok == false
Comma-ok receivev, ok := <-ch; ok false means closed and empty, zero value false
range over channelLoop that receives until the channel is closed
Channel ownershipThe rule that one goroutine creates, sends on and closes a channel
GeneratorFunction returning <-chan T fed by its own goroutine
PipelineStages connected by channels, each closing its own output
Done channelA chan struct{} closed to tell goroutines to stop
chan struct{}Zero-size element type used for signalling
SignallingUsing a channel to announce an event rather than send data
Broadcastclose(ch) waking every receiver at once
Share memory by communicatingGo's slogan: pass ownership over channels instead of locking shared data
Owner goroutineOne goroutine that holds state and serves requests over a channel
Request/response channelA request that carries its own reply channel (channel of channels)
Goroutine leakA goroutine that can never finish; holds memory until exit
goleakgo.uber.org/goleak, fails tests that leave goroutines running
Goroutine profilepprof profile of all current goroutine stacks
goroutineleak profileGo 1.27 pprof profile of goroutines blocked on unreachable primitives
runtime.NumGoroutineFunction returning the current number of goroutines
DeadlockNo goroutine can proceed; runtime reports all goroutines are asleep
Happens-beforeThe ordering the memory model guarantees between synchronised operations
Memory modelThe Go document defining which writes a read may observe
Semaphore channelBuffered channel used as N tokens to bound concurrency
Unbounded queueA buffer with no size limit; hides overload until memory runs out
BackpressureSlowing producers when consumers fall behind, by blocking or rejecting
selectStatement that waits on several channel operations (chapter)
runtime.GoschedYield the processor; no ordering guarantee
time.After leakPre-Go 1.23 retention of unstopped timers until they fired
sync.OnceRuns a function exactly once across goroutines
hchanThe runtime struct behind a channel: buffer, indexes, wait queues, lock
Fiber (PHP)PHP 8.1 cooperative full-stack coroutine, resumed explicitly
Swoole coroutineCoroutines provided by the Swoole/Open Swoole extension, with their own channels

References ​

Read for Go 1.24 to 1.27 behaviour; pages fetched and saved on 2026-11-26. pkg.go.dev refused automated fetches (HTTP 403), so package APIs were read with go doc from the local Go 1.27.4 toolchain and verified by the tests.

Built by Morteza Negahi