Lesson 4 of 9 · 25m
Channel Design and Backpressure
Choose channel direction, ownership, buffering, and close responsibility deliberately so channels communicate pressure instead of hiding it.
Channels are seductive because they look like plumbing. Connect enough pipes and the program appears elegant. Then production traffic arrives, one stage slows down, and the system blocks in a place nobody can see. The practical rule is simple: a channel is not just a queue; it is a coordination contract.
Direction is part of the contract
Use directional channel types at API boundaries:
func consume(in <-chan Event, out chan<- Result) {
for event := range in {
out <- handle(event)
}
}<-chan means receive-only and chan<- means send-only. Direction prevents a consumer from accidentally closing or writing to a channel it does not own, and it makes ownership visible in review.
Only the producer closes
The side that knows no more values will be sent closes the channel:
func produce(ctx context.Context, out chan<- Job) {
defer close(out)
for _, job := range loadJobs() {
select {
case out <- job:
case <-ctx.Done():
return
}
}
}Receivers should not close a shared input. With multiple producers, neither may close it unless an outer owner coordinates them — usually with a WaitGroup and one closer.
Buffers are capacity, not magic
A buffer of size one permits one item in transit. A buffer of size 1,000 moves work into memory:
jobs := make(chan Job, 128)Use buffering to absorb short bursts across a stable rate mismatch. Do not use it to paper over a permanently slower downstream. That mismatch belongs in metrics, load shedding, worker tuning, or a persistent queue.
Backpressure should be observable
When a producer blocks, backpressure is doing its job. Make it visible with queue depth, send-block duration, worker occupancy, and deliberate drop counters. len(ch) is approximate but useful. If depth is always at capacity, the buffer is not helping; it is delaying overload while consuming memory.
Field notes
- Closing a channel does not discard values already sent; receivers can drain them.
- Sending on a closed channel panics. Receiving from a closed channel returns the zero value with
ok == false. selectchooses pseudo-randomly among ready cases. Use separate priority lanes if priority matters.- Nil channels block forever. That is occasionally useful in
selectlifecycle tricks and catastrophic when accidental.
Was this lesson helpful?