Multiplexing with Select

Multiplexing with Select in Go: A loop is a receptionist with one telephone. If that line is quiet, they sit there -- even if three other phones on the desk…

The Analogy: The Switchboard Operator

A for range ch loop is a receptionist with one telephone. If that line is quiet, they sit there -- even if three other phones on the desk are ringing off the hook. Waiting on a channel is unconditional: the goroutine parks until that specific channel is ready, and no amount of activity elsewhere will wake it.

select is the switchboard operator, watching every line at once and answering whichever one lights up first. You write one case per line -- a receive, a send, whatever -- and the runtime parks your goroutine on all of them simultaneously. The first operation that can proceed does, its case body runs, and every other case is abandoned untouched. One goroutine, many conversations, no polling.

Two lines lighting up at the same instant is where the analogy gets interesting: Go picks uniformly at random. There is no top-to-bottom priority, and this is deliberate -- a source that is always ready would otherwise starve every case below it forever. Alongside that, default turns the operator into someone who glances at the board and, finding nothing lit, immediately gets on with their paperwork instead of waiting. That single keyword is how every non-blocking channel operation in Go is written.

Where the analogy stops: an operator cannot pull a plug out of the board, and select can. Assigning nil to a channel variable disables its case permanently -- a nil channel is never ready, so the case is simply not in the running any more. What looks like the most useless rule in the language ("all operations on a nil channel block forever") turns out to be the mechanism for switching parts of an event loop off as they finish. The other surprise is that a <-chan time.Time from time.After is not special: a timeout is just another line on the board.


Syntax or Core Structure

package main

import (
	"fmt"
	"time"
)

func main() {
	a := make(chan string, 1)
	b := make(chan string, 1)

	// Exactly one case can proceed, so there is nothing to randomise.
	a <- "from a"
	select {
	case v := <-a:
		fmt.Println("got:", v)
	case v := <-b:
		fmt.Println("got:", v)
	}

	// default makes the whole select non-blocking.
	select {
	case v := <-a:
		fmt.Println("unexpected:", v)
	default:
		fmt.Println("nothing ready")
	}

	// A case may be a send. This one sheds load instead of blocking.
	b <- "occupied" // b now has 1 of 1 slots used
	select {
	case b <- "second":
		fmt.Println("queued")
	default:
		fmt.Println("dropped: buffer full")
	}

	// A nil channel is never ready, so its case is switched off.
	var off chan string
	select {
	case v := <-off:
		fmt.Println("impossible:", v)
	case v := <-b:
		fmt.Println("still got:", v)
	}

	// The two-case timeout, the most common select in Go.
	slow := make(chan string) // nobody will ever send on this
	select {
	case v := <-slow:
		fmt.Println("fast:", v)
	case <-time.After(20 * time.Millisecond):
		fmt.Println("timed out")
	}
}

Output:

got: from a
nothing ready
dropped: buffer full
still got: occupied
timed out

Every one of those five results is forced rather than lucky: in each select, at most one case could possibly proceed. That is the discipline to aim for in tests -- if two cases in a select can be ready at the same moment, the output order is genuinely unspecified and you must not assert on it.


Technical Depth: Exactly What Select Does

The algorithm

  1. Evaluate every case's operands, once, in source order -- the channel expression for each case, plus the value expression for each send case. This happens before any case is chosen, so it happens even for cases that never run.
  2. Collect the cases that can proceed right now.
  3. If more than one can, choose uniformly at random among them.
  4. If none can and there is a default, run default.
  5. If none can and there is no default, park the goroutine on all of them until one becomes ready.

Step 1 is the one that surprises people. In case out <- expensive():, expensive() is called every time the select is reached, whether or not that case is chosen -- and if the select is in a loop, once per iteration. Move the call out of the case, or accept the cost.

Every form

FormBehaviour
select {}Blocks forever. In main with no other goroutines: fatal error: all goroutines are asleep - deadlock!
One case, no defaultIdentical to writing the bare channel operation.
Any cases + defaultNever blocks. The non-blocking probe.
A nil channel caseNever ready; effectively deleted for this evaluation.
A closed channel caseAlways ready, forever, returning the zero value.

The closed-channel spin, and the nil-ing cure

Because a closed channel is permanently ready, a naive fan-in loop turns into a hot spin the moment one input closes -- it keeps selecting that case and receiving zeros millions of times per second. The fix is the one idiom you must know from this lesson:

func merge(a, b <-chan int) <-chan int {
	out := make(chan int)
	go func() {
		defer close(out)
		for a != nil || b != nil { // loop until both are switched off
			select {
			case v, ok := <-a:
				if !ok {
					a = nil // disable this case and re-enter select
					continue
				}
				out <- v
			case v, ok := <-b:
				if !ok {
					b = nil
					continue
				}
				out <- v
			}
		}
	}()
	return out
}

Setting the local variable to nil does not touch the caller's channel; it only removes the case from this select. The loop condition then doubles as the termination test. This shape generalises: any event loop whose sources finish at different times wants it.

break breaks the select, not the loop

loop:
	for {
		select {
		case v, ok := <-ch:
			if !ok {
				break loop // labelled: leaves the for
			}
			use(v)
		}
	}

A bare break inside a case exits the select and lands back at the top of the for, which is almost never what the author meant. Use a label, or return. continue inside a select does refer to the enclosing loop, which makes the asymmetry worse rather than better.

Timers: time.After allocates, Ticker leaks if you forget

time.After(d) creates a new timer and channel on every evaluation. In a select inside a hot loop that is one allocation per iteration, and the abandoned timers stay alive until they fire -- a real source of memory growth in long loops with long timeouts. For a per-loop deadline, create one timer outside the loop:

t := time.NewTimer(d)
defer t.Stop()
// ... select on t.C; t.Reset(d) after draining it

time.Ticker must always be stopped with defer tk.Stop(), or its goroutine and channel stay forever. As of Go 1.23 an unreferenced Timer/Ticker can be collected before firing, but writing Stop remains correct and portable.

There is no priority, and how to fake one

Since ready cases are chosen at random, select cannot express "drain urgent before touching bulk". The idiom is a nested probe:

select {
case v := <-urgent:
	handle(v)
default:
	select { // urgent was empty; now wait on both
	case v := <-urgent:
		handle(v)
	case v := <-bulk:
		handle(v)
	}
}

Do not scale this past two levels. If you find yourself building a priority tree, you want an actual priority queue behind one channel.

Cost

select locks all its channels (in address order, to avoid deadlocking against another select), checks them, and either proceeds or enqueues the goroutine on every one. It is therefore O(number of cases) per evaluation, and meaningfully more expensive than a bare channel operation. The compiler special-cases the small shapes -- zero cases, one case, and one case plus default -- into direct runtime calls, so the common non-blocking probe is cheap. A ten-case select in a tight loop is not.


Real World Example: A Worker Loop With Cancellation, Load Shedding and a Fake Clock

One loop, four exits, and a metrics sink that is allowed to lose data. Every parameter of run is a channel, including the deadline -- which is what makes the whole thing testable without sleeping.

package main

import (
	"fmt"
	"time"
)

// Passing nil for quit or deadline switches that case off entirely.
func run(
	jobs <-chan string,
	metrics chan<- string,
	quit <-chan struct{},
	deadline <-chan time.Time,
) (done, dropped int, why string) {
	for {
		select {
		case j, ok := <-jobs:
			if !ok {
				return done, dropped, "source closed"
			}
			if j == "poison" {
				return done, dropped, "aborted on " + j
			}
			done++

			// Nested and non-blocking: telemetry must never slow the work.
			select {
			case metrics <- "ok:" + j:
			default:
				dropped++
			}

		case <-quit:
			return done, dropped, "cancelled"

		case <-deadline:
			return done, dropped, "deadline exceeded"
		}
	}
}

func drain(ch chan string) []string {
	close(ch)
	var got []string
	for v := range ch {
		got = append(got, v)
	}
	return got
}

func report(label string, done, dropped int, why string, m []string) {
	fmt.Printf("== %s ==\n", label)
	fmt.Printf("done=%d dropped=%d why=%s\n", done, dropped, why)
	fmt.Println("metrics:", m)
}

func main() {
	// 1. Normal drain. The sink holds two, so the rest are shed.
	jobs := make(chan string, 4)
	for _, j := range []string{"alpha", "beta", "gamma", "delta"} {
		jobs <- j
	}
	close(jobs)
	metrics := make(chan string, 2)
	d, dr, why := run(jobs, metrics, nil, nil)
	report("drain", d, dr, why, drain(metrics))

	// 2. Cancelled before a single job arrives. Closing is the broadcast:
	// never send on a quit channel.
	quit := make(chan struct{})
	close(quit)
	metrics = make(chan string, 2)
	d, dr, why = run(make(chan string), metrics, quit, nil)
	report("cancel", d, dr, why, drain(metrics))

	// 3. A job that ends the loop early, mid-batch.
	jobs = make(chan string, 3)
	for _, j := range []string{"one", "poison", "three"} {
		jobs <- j
	}
	close(jobs)
	metrics = make(chan string, 2)
	d, dr, why = run(jobs, metrics, nil, nil)
	report("abort", d, dr, why, drain(metrics))

	// 4. A hand-fired clock: <-chan time.Time is an ordinary channel.
	fake := make(chan time.Time, 1)
	fake <- time.Time{}
	metrics = make(chan string, 2)
	d, dr, why = run(make(chan string), metrics, nil, fake)
	report("deadline", d, dr, why, drain(metrics))
}

Output:

== drain ==
done=4 dropped=2 why=source closed
metrics: [ok:alpha ok:beta]
== cancel ==
done=0 dropped=0 why=cancelled
metrics: []
== abort ==
done=1 dropped=0 why=aborted on poison
metrics: [ok:one]
== deadline ==
done=0 dropped=0 why=deadline exceeded
metrics: []

All four runs are deterministic, and that is a property of the design rather than luck. In every single evaluation of the outer select, at most one case can proceed: runs 1 and 3 pass nil for both quit and deadline, run 2 passes an open-and-empty jobs, run 4 passes an open-and-empty jobs and a nil quit. Passing nil deliberately is how you get a four-way event loop that a test can pin down one exit at a time -- without nil-able cases you would have to construct four different functions.

The nested select with default is load shedding, in three lines. Metrics are worth having and never worth blocking on, so the inner select either hands the string over immediately or counts a drop and moves on. Run 1 shows the shape working: four jobs completed, a sink with room for two, so dropped=2 and the two oldest samples are the ones that survived. Compare the alternative -- metrics <- "ok:" + j with no select -- which would have blocked the worker permanently on gamma because nothing drains metrics until the function has returned.

deadline being a plain <-chan time.Time is the testability trick worth stealing. time.After returns exactly that type, so production code can pass time.After(5*time.Second) while the test passes a buffered channel with a value already sitting in it. Run 4 takes the timeout branch instantly, with no time.Sleep, no flakiness and no wall-clock dependency. Any time you are tempted to sleep in a test, ask whether the thing you are waiting for can be a parameter instead.

Notice that every exit is a return, not a break. A bare break in any of those cases would leave the select and immediately re-enter the for, silently turning "cancelled" into an infinite loop -- and in run 2, where quit is closed and therefore permanently ready, into a hot spin. Returning named results from inside the cases sidesteps the labelled-break question entirely, which is why this shape is more common in real Go than loop: labels.


Common Mistakes

  1. Using a bare break to leave the loop. It exits the select only. Use a labelled break, or restructure so each terminal case returns.
  2. Selecting on a closed channel in a loop without disabling the case. A closed channel is always ready, so the loop spins at full CPU receiving zero values. Set the variable to nil after !ok.
  3. Assuming the first case wins. Ready cases are chosen at random. Tests that depend on case order pass on your machine and fail in CI.
  4. Calling a function in a case expression. case out <- build(): runs build() on every evaluation, chosen or not. Hoist it above the select.
  5. time.After inside a loop's select. One timer allocated per iteration, each held until it fires. Use one time.NewTimer with Reset, and defer t.Stop().
  6. Forgetting defer ticker.Stop(). A Ticker you drop keeps its runtime timer alive; over a long-lived process that is a slow leak plus wasted wakeups.
  7. Adding default to a select that is meant to wait. default makes it non-blocking, so the loop becomes a busy-poll that burns a core doing nothing. default is for probes, not for loops.
  8. Sending on the quit channel instead of closing it. A send wakes exactly one waiter; close wakes all of them, now and in future. Cancellation is always close(done).
  9. Expecting priority from case order. There is none. Use the nested probe idiom, or a real priority queue behind a single channel.
  10. Writing select {} to "wait forever" in main. It works only while some other goroutine is runnable; if they all finish or block, the runtime aborts with a deadlock panic. Wait on something concrete.
  11. Ignoring ok in a receive case. Without it, a closed channel silently feeds zero values into your handler and you cannot tell "no data" from "a real zero".

Best Practices

  • Make every case's readiness unambiguous when you can; keep two-ready-cases randomness out of anything you assert on.
  • Reach for nil to switch a case off -- on close, on completion, or to make an optional dependency absent.
  • Accept <-chan struct{} for cancellation and <-chan time.Time for deadlines as parameters, so tests can drive both without sleeping.
  • Pair default with a send when losing the value is acceptable, and count the drops.
  • Keep case bodies short: decide in the select, do the work in a function.
  • Create timers and tickers outside the loop, stop them with defer.
  • Prefer return over labelled break for terminal cases; it removes a whole class of loop bugs.
  • Once a loop needs more than about four cases, move the coordination into a small struct with methods -- or use context (Module 10), which is this pattern standardised.

Practice Exercises

  1. Replace both return statements in the quit and deadline cases with a bare break and run case 2 again. Record what the program does and explain it in terms of the readiness of a closed channel.
  2. Add a fifth case that receives from a <-chan string named reconfig and, on each message, changes which job name counts as poison. Keep all four existing outputs identical, and say why passing nil for reconfig guarantees that.
  3. Implement the two-source merge from the Technical Depth section, feed it two pre-filled closed channels, and collect the results. Then delete the a = nil / b = nil lines and describe what changes about the program's CPU use and its output.
  4. Rewrite run so metrics is unbuffered and there is a second goroutine draining it. Explain what dropped reports now, and why that number is no longer deterministic.