Select Statement
The select statement waits on multiple channel operations simultaneously — like switch for channels.
Introduction
The select statement waits on multiple channel operations simultaneously — like switch for channels. It enables timeouts, non-blocking tries, graceful shutdown listening on ctx.Done(), and fair random choice when multiple cases ready.
Select is essential for production servers that must respond to cancellation, process work, and heartbeat concurrently. The default case makes select non-blocking for try-send/receive patterns.
This lesson builds select patterns used in Kubernetes controllers, gRPC streaming, and every net/http server shutdown handler.
The story
A Kubernetes health probe goroutine waits on multiple signals: a shutdown channel from SIGTERM, a ticker every 10 seconds for liveness checks, and a result channel from an async API call. select chooses whichever case is ready first — the pattern behind graceful shutdown in every production Go HTTP server.
Without select, you'd poll channels in a loop wasting CPU; with it, the runtime parks goroutines efficiently until an event arrives.
Understanding the topic
Key concepts
- select { case v := <-ch1: case ch2 <- x: default: }.
- If multiple cases ready, one chosen randomly (fair).
- default runs immediately if no case ready — non-blocking.
- select {} blocks forever — rare, used as deliberate block.
- Combining ctx.Done() with work channels for cancellation.
- time.After in select for timeout (prefer context.WithTimeout).
Step-by-step explanation
- Evaluate all channel operations simultaneously.
- Block until at least one case can proceed.
- Execute exactly one matching case body.
- Random selection if multiple ready — no priority order.
- default prevents blocking when no channel ready.
- Empty select {} deadlocks current goroutine intentionally.
Practical code example
Select with timeout, cancellation, and default non-blocking try:
package mainimport ("context""fmt""time")func main() {ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)defer cancel()ch := make(chan string, 1)go func() {time.Sleep(100 * time.Millisecond)ch <- "result"}()select {case msg := <-ch:fmt.Println("received:", msg)case <-ctx.Done():fmt.Println("cancelled:", ctx.Err())}// non-blocking tryselect {case ch <- "ping":fmt.Println("sent ping")default:fmt.Println("channel full, skip")}}
Output
received: result sent ping
Line-by-line code explanation
ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)creates a context that is cancelled automatically after 200 milliseconds.defer cancel()releases it when main ends.ch := make(chan string, 1)creates a channel for strings with a buffer of one. A send into it will not block while the buffer is empty.time.Sleep(100 * time.Millisecond)is inside an anonymous goroutine started with go func. It waits 100 milliseconds and then sends the string result on ch.select {starts the first select. It waits until one of its cases can proceed, and then runs only that case.case msg := <-ch:is chosen if a value arrives first. The goroutine sends after 100 ms and the timeout is 200 ms, so in normal runs this case wins and the program prints received: result.case <-ctx.Done():would win if the 200 ms timeout fired first. It would print cancelled: followed by the context's error, but that does not happen with these timings.case ch <- "ping":is in a second select that tries to send into ch. The first value has already been received, so the buffer has room, the send succeeds, and it prints sent ping.default:makes the second select non-blocking. If the send could not happen right away, this branch would print channel full, skip instead of waiting.
Key takeaway: Select waits on several channel operations and runs whichever is ready first. A context's Done channel is the standard way to add a timeout or cancellation case. A default case turns a send or receive into a try that never blocks.
Real-world use
Where you'll use this in production
- HTTP server Shutdown listening on os.Interrupt and ctx.Done().
- Timeout on external API call with select + time.After.
- Multiplexing multiple worker result channels.
- Heartbeat ticker alongside work processing loop.
Best practices
- Always include ctx.Done() case in long-running selects.
- Use context.WithTimeout instead of time.After in loops.
- Avoid select default busy-loop — add time.Sleep or block.
- Document select fairness — no guaranteed priority.
- Combine select with for loop for event processing.
Common mistakes
- time.After leak in for-select loop — creates timer each iteration.
- Missing default causing goroutine stuck forever.
- Only one case ever ready due to wrong channel wiring.
- Expecting priority order among cases — Go randomizes.
- select on single channel — just use receive directly.
Advanced interview questions
Interview Prep
Practice concise answers, then expand each card for the explanation.
1BeginnerQuestionselect with multiple ready cases?+
Answer
2BeginnerQuestiondefault case purpose?+
Answer
3IntermediateQuestionImplement timeout with select?+
Answer
4IntermediateQuestiontime.After leak in loop?+
Answer
5AdvancedQuestionGraceful shutdown select pattern.+
Answer
Summary
select multiplexes channel send/receive operations. Combine with context for cancellation and timeouts. default enables non-blocking try patterns. Avoid time.After in loops — use context deadlines. Next lesson: WaitGroup — waiting for goroutine completion.