Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Go Goroutines and Channels: Concurrency Patterns, Buffered Channels, and select

Go concurrency from the channel up: what an unbuffered send waits for, how select chooses, why goroutines leak, and the worker pool, timeout, and fan-in patterns that prevent it.

~5 min readGo
#Go#Concurrency#Backend
Go gopher data pipelines streaming packets into synchronized channel hubs with select switches

A goroutine is a function call with the go keyword in front of it, and a channel is a typed first-in-first-out queue that two goroutines use to hand values to each other. Almost every concurrency bug in Go comes from two properties of that pair: an unbuffered send completes only when a receiver is ready at the same moment, and a goroutine blocked on a channel never wakes up on its own, so a channel that nobody will ever read from is a permanent leak rather than an error.

Quick Summary

  • go f(x) evaluates f and its arguments in the calling goroutine, then runs the call concurrently and returns immediately. When main returns, every other goroutine is killed without cleanup.
  • make(chan T) is unbuffered: a send blocks until a receive happens, which makes the exchange a synchronization point. make(chan T, n) is buffered and blocks only when the buffer is full or empty.
  • Only the sender closes a channel, and only once. A receive from a closed channel yields the zero value with ok == false; a send on a closed channel panics.
  • select waits on several channel operations at once, picks uniformly at random among the ready ones, runs default if none is ready, and blocks if there is no default. A case on a nil channel is never ready, which makes nil a way to disable a branch.
  • Goroutines are not garbage collected. A goroutine parked on a send or receive that can never complete stays parked for the life of the process.

Basic syntax and type signatures

go
type Job struct{ ID int } // jobs is receive-only here, results is send-only: the worker cannot close // or read a channel it does not own. func worker(id int, jobs <-chan Job, results chan<- string) { for job := range jobs { results <- fmt.Sprintf("worker %d finished job %d", id, job.ID) } } func main() { jobs := make(chan Job, 5) // buffered: every send completes before a worker takes it results := make(chan string) // unbuffered: every send waits for a receive var wg sync.WaitGroup for i := 1; i <= 3; i++ { wg.Add(1) go func(id int) { defer wg.Done() worker(id, jobs, results) }(i) } go func() { wg.Wait() close(results) // the only goroutine that knows all sends are done }() for j := 1; j <= 5; j++ { jobs <- Job{ID: j} } close(jobs) // tells every worker that range jobs is finished for line := range results { fmt.Println(line) } }

chan T is bidirectional, chan<- T is send-only, and <-chan T is receive-only. A bidirectional channel is assignable to either directional type, which is why main can pass jobs to a parameter declared <-chan Job; the reverse conversion needs an explicit conversion and is almost always a design error. Two channels are identical types only when element type and direction both match.

close and range are the two operations that carry state: range ch loops until close(ch), and a two-value receive v, ok := <-ch reports whether the value came from a send or from the closed channel. cap(ch) reports the buffer size and len(ch) the number of queued values, but len is a snapshot that another goroutine can invalidate immediately.

Channel states side by side

StateSendReceive
nil channelblocks foreverblocks forever
unbuffered, receiver waitingcompletes, hands offcompletes
unbuffered, no receiverblocksblocks
buffered, not fullcompletes, copies into bufferblocks when empty
buffered, fullblockscompletes
closed, buffer emptypaniczero value, ok == false
closed, buffer holds valuespanicdrains buffered values, then zero value

The nil row costs hours. A nil channel is not an error, so a select case on an uninitialized channel never fires, and a send to it deadlocks until the runtime notices that no goroutine can make progress — deliberate behavior, but only useful when it is chosen.

Practical edge cases and deep dives

1. A pipeline that stops early leaks its senders

Closing a done channel is a broadcast to every goroutine selecting on it, which is the standard way to let a pipeline exit before it has drained. Each send becomes a two-case select, and the receive loop checks done as well:

go
func generate(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: return } } }() return out } func first(done <-chan struct{}, in <-chan int) (int, bool) { select { case v, ok := <-in: return v, ok case <-done: return 0, false } }

Without the done case, first returning after one value leaves generate blocked on out <- n with no receiver, and that goroutine holds its stack and everything it references for the rest of the process. Buffering out to the exact number of values also removes the block, but only until the downstream stage consumes one value fewer than expected.

2. First result wins needs a buffer of one

When two sources race and only the winner is read, the loser must still be able to finish its send:

go
func race(a, b <-chan string) string { select { case v := <-a: return v case v := <-b: return v } }

If a and b come from goroutines that do result <- value on an unbuffered channel, the loser blocks forever at that send. Making each result channel make(chan string, 1) gives the loser room to deliver and exit. The general rule: give a channel a buffer when the producer may finish after the consumer stops listening, and size it to the number of sends that can happen after the last receive.

3. Timeouts in a loop

A select with time.After is the shortest timeout, but the timer is created on every iteration:

go
for { select { case job := <-jobs: handle(job) case <-time.After(2 * time.Second): return errors.New("idle timeout") } }

Go 1.23 changed timer collection for modules that declare go 1.23 or later: a time.Timer no longer referenced by the program is collected immediately, even if Stop was never called, whereas earlier versions kept unstopped timers alive until they fired. For a hot loop on an older toolchain, use one time.NewTimer and call Reset on each iteration; on 1.23 and later the per-iteration version is acceptable but still allocates.

A default case is the other trap: select { case job := <-jobs: handle(job); default: } inside a for spins at full speed whenever the channel is empty, burning a core to discover the same emptiness. default is for genuinely non-blocking operations such as a metrics flush or a drop-on-full queue, not for waiting.

4. Disabling a select case with nil

A nil channel blocks forever, so assigning nil to a channel variable removes its case from a select without a flag:

go
for a != nil || b != nil { select { case v, ok := <-a: if !ok { a = nil // this case is now dead continue } consume(v) case v, ok := <-b: if !ok { b = nil continue } consume(v) } }

The loop ends when both inputs have closed, and the closed channel is never read again — which matters because a closed channel is always ready, so leaving it in place would spin on zero values. This mirror-merge is the standard way to fan in two streams without a helper package.

Common mistakes and compiler errors

SymptomCauseFix
panic: send on closed channela sender wrote after another goroutine closedclose only from the producer, and only after all sends
panic: close of closed channeltwo paths call closeguard with sync.Once, or close in one owner
fatal error: all goroutines are asleep - deadlock!every goroutine is blocked, usually a send with no receiverrun a receiver, add a buffer, or add a done case
Runtime grows without limits over hoursgoroutines parked on an unread channelcancel with done or context, and check runtime.NumGoroutine in tests
range ch never ends after the last valuethe producer never closed the channeldefer close(ch) in the producer
sync: WaitGroup is reused before previous Wait has returnedwg.Add called while another goroutine waits, or inside the goroutinecall Add before go, Done with defer
invalid operation: <-ch (receive from send-only type chan<- int)direction mismatch in the signaturereturn <-chan T from the producer, accept chan<- T in the consumer
all goroutines are asleep only under loadlen(ch) used as a readiness checkuse a non-blocking select with default
Every goroutine prints the same loop valuethe loop variable was captured, and go.mod declares a version below 1.22pass the value as a parameter, or raise the go line

The table reduces to one ownership rule that prevents most of it: the goroutine that creates a channel decides who closes it and who buffers it, and every goroutine that can outlive its consumer gets a done channel to select on. Channels are not garbage collected until they are unreachable, and a goroutine holding one is reachable by definition.

Try matching browser tools

All tools

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

All Go guides

More in Go

All Go guides

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