Skip to Content
Skip to content
Go Intermediate: Interfaces, Concurrency, and Services
Intermediate
Courses
Go Intermediate: Interfaces, Concurrency, and Services

Coordinate Pipelines and Timeouts With Channels and select

Send values safely over channels, close channels from the sender, and multiplex with select and ctx.Done(). After this, goroutines exit cleanly instead of leaking.

Course content

Sign in to save your progress.

Course Home

Channels let goroutines pass values and ownership safely without explicit locks, and select lets a goroutine wait on multiple channels—or a ctx.Done() timeout—simultaneously. Used well, channels make pipelines crystal clear. Used carelessly, one blocked send on an unbuffered channel leaks a goroutine forever in memory.

Skip ahead

If you already close channels strictly from producers, prevent send leaks with buffered channels or select + ctx.Done(), and disable closed branches with ch = nil, take the section quiz or continue to "Write Structured JSON Logs With log/slog."

Experiment 1: Ownership—why only the producer closes a channel

Two runtime rules govern closing channels in Go: sending on a closed channel panics, and closing an already-closed channel panics. That leads to one universal ownership rule: only the sender (producer) closes a channel—never the receiver. Once the producer closes the channel after sending its final item, every receiver ranging with for v := range ch exits automatically.

Experiment 2: Stopping goroutine leaks when a timeout fires

Imagine an API handler starts a background goroutine to fetch a recommendation and gives it 15 ms before falling back to a default list. If ch := make(chan string) is unbuffered and the handler times out at 15 ms and returns, the goroutine finishes at 100 ms, tries to execute ch <- "ok", and blocks forever because nobody is listening anymore!

Two small changes eliminate that leak completely: make the result channel capacity 1 (make(chan string, 1)) and select on ctx.Done() inside the worker:

package main

import (
	"context"
	"fmt"
	"time"
)

func fetchWithTimeout(ctx context.Context, delay time.Duration) (string, error) {
	ch := make(chan string, 1) // buffer of 1 lets worker exit even if caller already returned
	go func() {
		select {
		case <-time.After(delay):
			ch <- "ok"
		case <-ctx.Done():
			return
		}
	}()

	select {
	case res := <-ch:
		return res, nil
	case <-ctx.Done():
		return "", ctx.Err()
	}
}

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 15*time.Millisecond)
	defer cancel()
	_, err := fetchWithTimeout(ctx, 100*time.Millisecond)
	fmt.Println("timed out:", err)
}
$ go run -race .
timed out: context deadline exceeded

Look at why both protections work together: case <-ctx.Done() wakes the worker immediately at 15 ms instead of waiting 100 ms, and the capacity-1 buffer guarantees that even if the worker finished at the exact same microsecond as the timeout, ch <- "ok" drops the result into the buffer and exits cleanly so the GC frees both goroutine and channel.

Experiment 3: Draining two channels cleanly by setting a closed channel to nil

Here is a subtle select gotcha: receiving from a closed channel never blocks—it returns the zero value immediately with ok == false! If you loop over two channels a and b and a closes first, case v, ok := <-a spins millions of times per second unless you disable that branch by setting a = nil (because a nil channel blocks forever inside select):

package main

import "fmt"

func main() {
	a := make(chan string, 1)
	b := make(chan string, 1)
	a <- "from-a"
	b <- "from-b"
	close(a)
	close(b)

	var seen []string
	for a != nil || b != nil {
		select {
		case v, ok := <-a:
			if !ok {
				a = nil // disables this select case!
				continue
			}
			seen = append(seen, v)
		case v, ok := <-b:
			if !ok {
				b = nil
				continue
			}
			seen = append(seen, v)
		}
	}
	fmt.Println("drained:", len(seen))
}
$ go run -race .
drained: 2

Once both a and b become nil, the loop exits cleanly with zero busy-spinning.

Common mistakes

  • Putting a default: case inside an infinite for { select { ... } } loop: Makes the loop non-blocking so it spins at 100% CPU doing nothing.
  • Sending on an unbuffered channel when the receiver might exit early: Permanently leaks the sending goroutine; always pair sends with case <-ctx.Done(): or a capacity-1 buffer for single-result goroutines.
  • Forgetting that range ch blocks forever if nobody closes ch: Always make sure the producer closes ch (for example with defer close(ch)) on every exit path.

💡 Tip

Use channel directions in function signatures—jobs <-chan Job (receive-only) and results chan<- Result (send-only). The compiler then prevents a worker from accidentally closing a receive-only channel.

What happens if you skip this step

Unbounded goroutine leaks on timed-out requests accumulate slowly—a few leaked goroutines per minute looks invisible in development, then slowly climbs to 50,000 stuck goroutines and crashes production three days later.

Inside a for { select { case v, ok := <-a: ... case v, ok := <-b: ... } } loop, channel a closes while channel b is still sending items. What happens if you forget to set a = nil when !ok?

About

Send values safely over channels, close channels from the sender, and multiplex with select and ctx.Done(). After this, goroutines exit cleanly instead of leaking.

Duration
5 min
Last update
11/27/2026
Was this helpful?
​ 0 ​ 0

Comments

Sign in to comment

No comments yet.