The Analogy: Handing Over the Pager
Picture two staff on different shifts who must hand over a single pager. An unbuffered channel is that handover done in person: the outgoing nurse stands there holding the pager until the incoming nurse takes it, and the incoming nurse stands there empty-handed until it arrives. Neither can walk away. ch <- v on an unbuffered channel does not "put the value somewhere" -- it waits for a receiver, and the two goroutines meet at that instant. That meeting is the point; the data is almost a side effect.
A buffered channel is a row of pigeonholes behind the desk. make(chan int, 3) gives three slots, and the sender only has to wait when all three are full; the receiver only has to wait when all three are empty. This decouples the two sides in time, which is occasionally what you want and frequently a way to hide a design problem. A buffer of 3 does not make anything faster -- it makes the sender able to get 3 items ahead before it feels the receiver's pace.
Closing a channel is the announcement that the shift is over and no more pages will come. It is a broadcast: every current and future receiver learns about it, not just one. v, ok := <-ch reports ok == false, and for range ch simply ends. Crucially, only the side that sends may close, because closing means "I am done sending" -- and any value already in the buffer is still delivered before the close is observed.
Where the analogy stops: a channel is not a queue you poll. It is a synchronisation primitive that happens to carry a payload, and the language gives it three sharp edges to prove it -- sending on a closed channel panics, closing a channel twice panics, and every operation on a nil channel blocks forever. That last one sounds like a pure bug, and in the next lesson it turns into the standard way to switch a select case off. Hence the Go proverb: do not communicate by sharing memory; share memory by communicating.
Syntax or Core Structure
package main
import "fmt"
// Returning <-chan int tells the caller: receive only, and I will close it.
func gen(n int) <-chan int {
out := make(chan int)
go func() {
defer close(out) // the sender closes, always
for i := 1; i <= n; i++ {
out <- i
}
}()
return out
}
func sum(in <-chan int) int { // asks for the narrowest thing it can use
t := 0
for v := range in { // ends when in is closed and drained
t += v
}
return t
}
func main() {
// Unbuffered: the send blocks until this goroutine receives.
done := make(chan string)
go func() { done <- "worker finished" }()
fmt.Println(<-done)
// Buffered: two sends complete with no receiver in sight.
buf := make(chan int, 2)
buf <- 10
buf <- 20
fmt.Println("len:", len(buf), "cap:", cap(buf))
fmt.Println("first:", <-buf)
fmt.Println("second:", <-buf)
// Buffered values survive the close; range drains, then stops.
nums := make(chan int, 3)
for i := 1; i <= 3; i++ {
nums <- i * i
}
close(nums)
var squares []int
for n := range nums {
squares = append(squares, n)
}
fmt.Println("squares:", squares)
// Receiving from a drained, closed channel never blocks.
v, ok := <-nums
fmt.Printf("closed: v=%d ok=%t\n", v, ok)
fmt.Println("sum:", sum(gen(4)))
}
Output:
worker finished
len: 2 cap: 2
first: 10
second: 20
squares: [1 4 9]
closed: v=0 ok=false
sum: 10
Three things worth naming. gen returns <-chan int although it created a bidirectional chan int -- the conversion is implicit and one-way, so the caller physically cannot send or close. close(nums) happened while three values were still buffered, and all three were delivered anyway. And <-nums after the drain returned instantly with the zero value rather than blocking, which is why the comma-ok form exists.
Technical Depth: The Channel Axioms
Every operation, every state
Almost every channel bug is a cell in this table that the author had not memorised. It is worth learning outright.
| Operation | nil channel | Open, empty | Open, full | Closed |
|---|---|---|---|---|
Send ch <- v | Blocks forever | Buffered: proceeds. Unbuffered: waits for a receiver | Blocks until a slot frees | panic: send on closed channel |
Receive <-ch | Blocks forever | Blocks until a value arrives | Proceeds | Drains the buffer, then returns the zero value immediately, ok == false |
close(ch) | panic: close of nil channel | Succeeds | Succeeds; buffered values still delivered | panic: close of closed channel |
len / cap | 0, 0 | Values buffered, capacity | Values buffered, capacity | Still legal, still reports the remaining buffer |
Note the asymmetry that catches everyone: receiving from a closed channel is fine forever, sending to one is fatal. That is deliberate -- close means "no more values", and a receiver never needs to ask whether it may keep reading, while a sender always needs to know whether anyone will ever read again.
Unbuffered means rendezvous, and rendezvous means ordering
An unbuffered send and its receive complete at the same moment, so both goroutines learn something about each other's progress. The Go memory model makes this precise:
- A send on a channel happens before the corresponding receive completes.
- The completion of a receive happens before the corresponding send completes (unbuffered only).
- The
closehappens before a receive that observes the channel is closed.
That is why the done := make(chan string) handshake above needs no mutex to publish anything the goroutine wrote before the send: everything it did is visible to the receiver afterwards. A single unbuffered channel is the cheapest correct way to say "wait for exactly one thing and see all its work".
Buffer size is a design decision, not a tuning knob
| Capacity | What it means | Use it when |
|---|---|---|
0 (unbuffered) | Full lockstep. Sender's progress is bounded by the receiver's. | You want backpressure and a synchronisation point. This is the correct default. |
1 | One value in flight; a "mailbox" or a mutex-like token. | Signalling, semaphores, "latest value" handoffs. |
n (small, fixed) | Absorbs bursts up to n; sender still feels a sustained mismatch. | Smoothing jitter between stages that are on average balanced. |
len(work) | The producer never blocks at all. | The work is known up front and you want the producer done and gone. |
A large buffer does not fix a slow consumer -- it delays the moment you find out about it, and turns a stall into unbounded memory growth. If you cannot name the invariant a buffer preserves, use 0.
Who closes, and what closing is for
Two rules make close safe in practice:
- Only the sender closes. A receiver that closes will cause the sender to panic on its next send.
- With multiple senders, nobody closes -- a coordinator does, after they all finish. The standard shape is a
sync.WaitGroupover the senders plus one goroutine that doeswg.Wait(); close(out). Attempting to have each sender "close if it is the last" is a race.
And note what close is not for: it is not a way to cancel a receiver's work, and it is not a general broadcast mechanism for values. It broadcasts exactly one bit -- "finished" -- to everyone. That single bit is genuinely useful, which is why close(done) is the idiomatic fan-out signal, and why context.Done() returns a channel that is only ever closed, never sent on.
Directional types
chan T converts implicitly to <-chan T (receive-only) and chan<- T (send-only); neither converts back. The arrow binds as far left as it can, so chan<- chan int is "send-only channel of bidirectional channels", and you need parentheses for anything else. Using directional types in signatures is free documentation that the compiler enforces: a function taking <-chan T provably cannot close your channel out from under you.
Request/reply: channels inside messages
A channel is an ordinary value, so it can be a struct field or a channel element. That gives request/reply without any registry of pending calls:
type req struct {
key string
reply chan<- string // the caller's private mailbox
}
The server loop reads a req, computes, and sends on r.reply. Each caller makes its own make(chan string, 1) -- buffered by one, so the server can answer and move on even if the caller has given up. This is the pattern behind most single-goroutine state managers in Go, and it is also how you get an answer back from a worker without ever sharing the state it guards.
Deadlock, detected and undetected
If every goroutine is blocked, the runtime notices and aborts with fatal error: all goroutines are asleep - deadlock! and a full dump. That is the friendly case, and it is why an unbuffered send in main with no other goroutine fails loudly and immediately. The unfriendly case is one goroutine blocked forever while others keep working: the runtime cannot tell that from ordinary waiting, so nothing is reported and you have a leak. Deadlock detection is a debugging convenience, not a safety net.
Channels versus mutexes
Use a channel to transfer ownership of data, to distribute work, or to signal; use a mutex to protect a field that several goroutines read and write in place. A channel costs more per operation than an uncontended mutex -- it involves the scheduler -- so a hot counter behind sync.Mutex or atomic will beat a channel-based one every time. Choosing by taste rather than by which of those two sentences applies is the usual source of over-engineered Go concurrency.
Real World Example: A Three-Stage Pipeline With Fan-Out in the Middle
Each stage owns its output channel, closes it, and returns it as receive-only. The caller wires them together as an expression. Stage three deliberately fans out to three workers so you can see exactly what that costs you.
package main
import (
"fmt"
"sort"
"strconv"
"strings"
"sync"
)
type record struct {
seq int
raw string
level string
ms int
err error
}
// Stage 1: source. Owns out, closes out.
func source(lines []string) <-chan record {
out := make(chan record)
go func() {
defer close(out)
for i, l := range lines {
out <- record{seq: i, raw: l}
}
}()
return out
}
// Stage 2: parse "level ms". Errors ride along inside the record.
func parse(in <-chan record) <-chan record {
out := make(chan record)
go func() {
defer close(out)
for r := range in {
fields := strings.Fields(r.raw)
if len(fields) != 2 {
r.err = fmt.Errorf("want 2 fields, got %d", len(fields))
} else if ms, err := strconv.Atoi(fields[1]); err != nil {
r.err = fmt.Errorf("bad duration %q", fields[1])
} else {
r.level, r.ms = strings.ToUpper(fields[0]), ms
}
out <- r
}
}()
return out
}
// Stage 3: fan-out to N workers over one input, fan-in to one output.
// Many senders means no sender may close: a coordinator does it.
func flag(in <-chan record, workers int) <-chan record {
out := make(chan record)
var wg sync.WaitGroup
for w := 0; w < workers; w++ {
wg.Add(1)
go func() {
defer wg.Done()
for r := range in { // all workers read the same channel
if r.err == nil && r.ms > 200 {
r.level = "SLOW/" + r.level
}
out <- r
}
}()
}
go func() {
wg.Wait() // every sender has returned
close(out)
}()
return out
}
func main() {
lines := []string{
"info 12",
"warn 250",
"error",
"debug abc",
"info 900",
"warn 30",
}
var got []record
for r := range flag(parse(source(lines)), 3) {
got = append(got, r)
}
// Fan-in destroys order. The seq we carried from stage 1 restores it.
sort.Slice(got, func(a, b int) bool { return got[a].seq < got[b].seq })
for _, r := range got {
if r.err != nil {
fmt.Printf("%d %-10s error: %v\n", r.seq, "-", r.err)
continue
}
fmt.Printf("%d %-10s %dms\n", r.seq, r.level, r.ms)
}
}
Output:
0 INFO 12ms
1 SLOW/WARN 250ms
2 - error: want 2 fields, got 1
3 - error: bad duration "abc"
4 SLOW/INFO 900ms
5 WARN 30ms
The wiring is one expression, and it is a pipeline because of the channel types. flag(parse(source(lines)), 3) reads like function composition and behaves like a running system: three stages, five goroutines, all started and all terminating without a single WaitGroup visible to main. The reason it composes is that every stage takes <-chan record and returns <-chan record, so any stage can be inserted, removed, or repeated without touching its neighbours. That is the whole payoff of directional channel types in signatures.
Termination propagates by itself, from the front. source runs out of lines and closes its channel; parse's for range therefore ends, its defer close(out) fires; the three flag workers' range loops end, wg.Wait() returns, the coordinator closes the last channel, and main's range ends. Nobody was told to stop. This cascade is why "the sender closes" is a rule and not a style preference -- it is the only arrangement in which shutdown flows the same direction as the data.
Stage 3 shows both sides of fan-out. Three workers reading one channel is a load balancer with no code: whichever worker is free takes the next record, so a slow record cannot stall the others. The price is that order is gone -- the workers finish in whatever order they finish, and out receives them that way. Because stage 1 stamped a seq onto every record, the sort at the end reconstructs the original order exactly. If record had no seq, this program would be non-deterministic and untestable, and no amount of channel discipline would fix it.
Errors never leave the pipeline. A malformed line becomes a record with err set and keeps flowing; stage 3 checks r.err == nil before doing its work and passes the bad ones through untouched. The alternative -- a second errChan per stage -- doubles the plumbing, needs its own close discipline, and loses the association between an error and the item that caused it. Carrying the error in the payload keeps every stage's signature identical, which is exactly what let flag be inserted without thinking about failure at all.
Common Mistakes
- Sending on a closed channel.
panic: send on closed channel, and it is usually a shutdown-order bug: something closed while a producer was still running. The fix is ownership, not arecover. - Closing from the receiver, or closing twice. Both panic. Only the sender closes, exactly once --
defer close(out)in the goroutine that owns the sends. - Multiple senders where each one closes. A race with a guaranteed panic under load. Use
wg.Wait(); close(out)in a single coordinator goroutine. - Forgetting to close, then
for range-ing. The range never ends:fatal error: all goroutines are asleep - deadlock!if nothing else runs, or a permanent hang if something does. - Sending on an unbuffered channel from
mainwith no receiver yet. Immediate deadlock.ch := make(chan int); ch <- 1is the shortest deadlock in Go. - Forgetting to
makethe channel. A nilchanfield or avar ch chan intblocks forever on both send and receive, with no panic and no message -- the hardest channel bug to spot by reading. - Using
len(ch) > 0to decide whether to receive. The answer is stale the instant you have it. Useselectwith adefault(next lesson). - Treating a closed channel's zero value as data. A drained closed channel yields
0,"",nilforever at full speed. Without the comma-ok form, aforloop over it spins hot. - Growing the buffer to "fix" a slow consumer. It converts a visible stall into invisible memory growth. Fix the consumer, or add backpressure deliberately.
- Abandoning a receiver while producers are still sending. Every producer blocks forever on its next send -- a leak, not a crash. Producers need a cancellation path, which is what
selectpluscontextprovides. - Reaching for channels to guard a shared counter or map. A channel is for handing data over;
sync.Mutexandsync/atomicare for protecting data in place, and are far cheaper at it.
Best Practices
- Default to unbuffered. Add capacity only when you can state the burst it absorbs.
- Give every channel exactly one owner: the goroutine that sends on it is the goroutine that closes it.
- Return
<-chan Tfrom producers and accept<-chan Tin consumers, so the compiler enforces the direction. - Close with
defer close(out)as the first line of the producer goroutine, so it survives early returns and panics. - For many senders, use one
wg.Wait(); close(out)coordinator goroutine and nothing else. - Carry a sequence number through any stage that fans out, so order can be reconstructed and the output can be tested.
- Keep errors in the payload rather than in a parallel error channel.
- Use
close(done)-- never a send -- when the signal is "everyone stop", because closing is the only broadcast a channel has.
Practice Exercises
- Insert a fourth stage between
parseandflagthat drops records witherr != nilinstead of passing them along, and confirm the remaining output is unchanged apart from the two error lines. Explain why no other stage needed editing. - Remove the
sort.Slicecall, run the program ten times, and record how many distinct orderings you see. Then setworkersto 1 and explain why the ordering becomes stable again without the sort. - Move
close(out)inflagfrom the coordinator goroutine into each worker'sdeferand describe the exact panic message and which goroutine reports it. - Rewrite
mainto consume the pipeline withv, ok := <-chinside a plainforloop instead offor range, breaking on!ok. Then remove theokcheck and record what the program does.