SyntaxPilot
Courses/Go Programming/Lesson 49
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Go Programming · Lesson 49 of 89

select, timeouts and timers

select statementblocking selectdefault case for non-blocking operationsrandom choice among ready casesfor-select loopdisabling cases with nil channelstime.Aftertime.NewTimerStop and Resettime.Tickertime.Ticktimeoutsheartbeatstimer changes in Go 1.23

These are the notes for Go episode 49. One delivery boy serves two hatches, a slow tandoor and a fast grill, by waiting on each in turn: in 900 ms only 3 grill dishes go out instead of about 18. You invent select, which waits on many channel operations and runs whichever is ready first. Then you see that select picks at random among ready cases, use default to send or receive without waiting, write the for-select loop, switch off a closed channel's case by setting it to nil, give a customer a timeout with time.After, use timers (NewTimer, Stop, Reset) and tickers for heartbeats, and watch the Go 1.23 timer change remove a stale-value bug just by changing one line of go.mod.

All outputs here are from real runs (Go 1.24.7, linux/amd64, a machine with 2 CPUs). Counts, timings and the order of some lines change between runs.

Facts and sources

  • The Go Programming Language Specification, Select statements: "If one or more of the communications can proceed, a single one that can proceed is chosen via a uniform pseudo-random selection. Otherwise, if there is a default case, that case is chosen. If there is no default case, the "select" statement blocks until at least one of the communications can proceed." And: "Since communication on nil channels can never proceed, a select with only nil channels and no default case blocks forever."
  • Go Wiki: Go 1.23 Timer Channel Changes: "Unstopped timers and tickers that are no longer referenced can be garbage collected." "Timer channels are now synchronous (unbuffered)", so "after one of those methods returns, no future receive from the timer channel will observe a stale time value". The new behaviour applies to "programs where package main is in a module with a go.mod declaring go 1.23 or later"; "The GODEBUG setting asynctimerchan=1 forces the old semantics".

The problem: two hatches, one delivery boy

In Raju's kitchen In Go
the tandoor: a veg dish every 300 ms a slow sender goroutine
the grill: a nonveg dish every 50 ms a fast sender goroutine
the boy waits at veg, then nonveg, in turn two receives, one after the other
package main

import (
    "fmt"
    "time"
)

func cook(name string, gap time.Duration, out chan<- string) {
    for {
        time.Sleep(gap) // cooking
        out <- name
    }
}

func main() {
    veg, nonveg := make(chan string), make(chan string)
    go cook("veg", 300*time.Millisecond, veg)       // slow: tandoor
    go cook("nonveg", 50*time.Millisecond, nonveg) // fast: grill
    count := map[string]int{}
    start := time.Now()
    for time.Since(start) < 900*time.Millisecond {
        count[<-veg]++    // wait for a veg dish...
        count[<-nonveg]++ // ...then a nonveg dish, in turn
    }
    fmt.Println("in 900ms:", count)
}

Real output:

in 900ms: map[nonveg:3 veg:3]

The grill could make about 18 dishes in 900 ms, but made 3. While main waited on <-veg, the grill's dish sat in its unbuffered channel and the grill goroutine was blocked holding it. A receive waits on exactly one channel.

The fix: select

In Raju's kitchen In Go
stand between both hatches and watch both select { ... }
one plan per hatch one case per channel operation
take the first dish that appears, then come back the first ready case runs; loop for the next

The select statement looks like a switch, but every case is a channel operation: a receive (case v := <-ch:, case <-ch:, case v, ok := <-ch:) or a send (case ch <- v:). It blocks until at least one case can proceed, then runs exactly that one.

package main

import (
    "fmt"
    "time"
)

func cook(name string, gap time.Duration, out chan<- string) {
    for {
        time.Sleep(gap) // cooking
        out <- name
    }
}

func main() {
    veg, nonveg := make(chan string), make(chan string)
    go cook("veg", 300*time.Millisecond, veg)       // slow: tandoor
    go cook("nonveg", 50*time.Millisecond, nonveg) // fast: grill
    count := map[string]int{}
    start := time.Now()
    for time.Since(start) < 900*time.Millisecond {
        select { // wait for whichever is ready first
        case d := <-veg:
            count[d]++
        case d := <-nonveg:
            count[d]++
        }
    }
    fmt.Println("in 900ms:", count)
}

Real output:

in 900ms: map[nonveg:17 veg:3]

When several cases are ready: random choice

package main

import "fmt"

func main() {
    a := make(chan int, 1000)
    b := make(chan int, 1000)
    for i := 0; i < 1000; i++ {
        a <- i // both hatches always have a dish ready
        b <- i
    }
    picked := map[string]int{}
    for i := 0; i < 1000; i++ {
        select {
        case <-a:
            picked["a"]++
        case <-b:
            picked["b"]++
        }
    }
    fmt.Println("picked:", picked)
}

Real output (a different split every run):

picked: map[a:503 b:497]

Uniform means every ready case has the same chance; pseudo-random means chosen by a random number generator. Go doesn't pick top-to-bottom, because a busy first case would starve the others (they would never be served). Never write code that depends on case order.

default: non-blocking operations

At Raju's counter In Go
an order board with 2 hooks make(chan string, 2)
board full? say sorry now select with default: a non-blocking send
no orders? wipe the counter a non-blocking receive

default runs when no other case is ready at this moment, so the select never blocks.

package main

import "fmt"

func main() {
    board := make(chan string, 2) // the order board has 2 hooks
    for _, o := range []string{"dosa", "idli", "vada", "poha"} {
        select {
        case board <- o:
            fmt.Println("order taken:", o)
        default: // the send can't proceed right now: don't wait
            fmt.Println("board full, sorry:", o)
        }
    }
    for i := 0; i < 3; i++ {
        select {
        case o := <-board:
            fmt.Println("cooking", o)
        default:
            fmt.Println("no orders: wipe the counter")
        }
    }
}

Real output:

order taken: dosa
order taken: idli
board full, sorry: vada
board full, sorry: poha
cooking dosa
cooking idli
no orders: wipe the counter

Warning: for { select { ...; default: } } never sleeps. If nothing is ready it spins, burning a CPU (episode 47's busy waiting). Use default for one quick try, not as a way to wait.

The for-select loop

A goroutine that serves until told to stop puts select in a for loop with a stop case: the most common shape in concurrent Go.

package main

import (
    "fmt"
    "time"
)

func kitchen(orders <-chan string, closing <-chan struct{}) {
    for { // the for-select loop
        select {
        case o := <-orders:
            fmt.Println("cooking", o)
        case <-closing:
            fmt.Println("kitchen: closing time, stove off")
            return
        }
    }
}

func main() {
    orders, closing := make(chan string), make(chan struct{})
    go kitchen(orders, closing)
    orders <- "dosa"
    orders <- "idli"
    close(closing) // broadcast: stop
    time.Sleep(50 * time.Millisecond)
}

Real output:

cooking dosa
cooking idli
kitchen: closing time, stove off

close(closing) is episode 48's broadcast: every goroutine waiting on it wakes. (Note: if an order and closing are both ready, select may pick either, so a real kitchen drains or checks closing first when order matters.)

Switching cases off with nil channels

Merging two channels means reading both into one stream until both are closed. A closed channel's receive is always ready (episode 48), so its case keeps winning the select:

package main

import (
    "fmt"
    "time"
)

func main() {
    veg, nonveg := make(chan string), make(chan string)
    go func() { veg <- "paneer"; close(veg) }()
    go func() {
        time.Sleep(20 * time.Millisecond)
        nonveg <- "chicken"
        close(nonveg)
    }()
    vegDone, nonvegDone, wasted := false, false, 0
    for !vegDone || !nonvegDone {
        select {
        case d, ok := <-veg:
            if !ok { // closed: but this case stays ready forever
                vegDone = true
                wasted++
                continue
            }
            fmt.Println("serving", d)
        case d, ok := <-nonveg:
            if !ok {
                nonvegDone = true
                continue
            }
            fmt.Println("serving", d)
        }
    }
    fmt.Println("wasted wake-ups on the closed veg hatch:", wasted)
}

Real output:

serving paneer
serving chicken
wasted wake-ups on the closed veg hatch: 289382

The fix: set the channel variable to nil when it closes. A nil channel is never ready, so select ignores that case.

package main

import (
    "fmt"
    "time"
)

func main() {
    veg, nonveg := make(chan string), make(chan string)
    go func() { veg <- "paneer"; close(veg) }()
    go func() {
        time.Sleep(20 * time.Millisecond)
        nonveg <- "chicken"
        close(nonveg)
    }()
    wakeups := 0
    for veg != nil || nonveg != nil { // until both are switched off
        wakeups++
        select {
        case d, ok := <-veg:
            if !ok {
                veg = nil // a nil channel is never ready: case switched off
                continue
            }
            fmt.Println("serving", d)
        case d, ok := <-nonveg:
            if !ok {
                nonveg = nil
                continue
            }
            fmt.Println("serving", d)
        }
    }
    fmt.Println("total wake-ups:", wakeups)
}

Real output:

serving paneer
serving chicken
total wake-ups: 4

4 wake-ups: two dishes, two closes. And remember: a select with only nil channels and no default blocks forever.

Timeouts with time.After

At Raju's counter In Go
a customer waits for a dish case d := <-dish:
...but only 200 ms time.After(200 * time.Millisecond): a channel that receives one value (the time) after the duration
whichever comes first select: work vs clock

A timeout is a limit on how long you wait.

package main

import (
    "fmt"
    "time"
)

func order(dish string, cookTime time.Duration) <-chan string {
    ch := make(chan string, 1) // buffered: the cook never gets stuck
    go func() {
        time.Sleep(cookTime)
        ch <- dish
    }()
    return ch
}

func main() {
    for _, o := range []struct {
        dish string
        took time.Duration
    }{{"chai", 100 * time.Millisecond}, {"biryani", 400 * time.Millisecond}} {
        select {
        case d := <-order(o.dish, o.took):
            fmt.Println("served", d)
        case <-time.After(200 * time.Millisecond): // the customer's patience
            fmt.Println("customer left: waited too long for", o.dish)
        }
    }
}

Real output:

served chai
customer left: waited too long for biryani

order returns a channel with a buffer of 1 so the cook can always drop the dish and finish even after the customer left: no goroutine leak (episode 48). With an unbuffered channel, every timed-out order would leak one goroutine.

Timers: Stop and Reset

Raju's chai timer In Go
set the timer; it rings once t := time.NewTimer(d): delivers the time on t.C once
order cancelled: switch it off t.Stop(): true if it stopped the timer before it fired
new order: set it again t.Reset(d): start again with a new duration
package main

import (
    "fmt"
    "time"
)

func main() {
    start := time.Now()
    since := func() time.Duration { return time.Since(start).Round(10 * time.Millisecond) }

    chai := time.NewTimer(300 * time.Millisecond) // chai is ready in 300ms
    fmt.Println(since(), "Stop before it fired:", chai.Stop()) // customer cancelled

    chai.Reset(100 * time.Millisecond) // a new order: start it again
    <-chai.C                           // C delivers the time when it fires
    fmt.Println(since(), "chai ready")
    fmt.Println(since(), "Stop after it fired:", chai.Stop())
}

Real output:

0s Stop before it fired: true
100ms chai ready
100ms Stop after it fired: false

Use a Timer instead of time.After when you need to cancel or reuse it, for example a timeout that is pushed back every time activity happens (see the mini project).

Tickers and heartbeats

On Raju's street In Go
a clock that strikes every hour time.NewTicker(d): a value on C every d until Stop
the watchman whistles each round a heartbeat: a regular "I'm alive" signal
no whistle for a while? check on him a watchdog: select with a timeout on the heartbeat
package main

import (
    "fmt"
    "time"
)

func worker(beat chan<- struct{}) {
    tick := time.NewTicker(100 * time.Millisecond) // every 100ms
    defer tick.Stop()
    for n := 1; ; n++ {
        <-tick.C
        if n == 4 {
            time.Sleep(time.Hour) // the worker gets stuck
        }
        beat <- struct{}{} // heartbeat: "I'm alive"
    }
}

func main() {
    start := time.Now()
    beat := make(chan struct{})
    go worker(beat)
    for {
        select {
        case <-beat:
            fmt.Println(time.Since(start).Round(10*time.Millisecond), "heartbeat")
        case <-time.After(250 * time.Millisecond):
            fmt.Println("no heartbeat for 250ms: the worker looks stuck")
            return
        }
    }
}

Real output:

100ms heartbeat
200ms heartbeat
300ms heartbeat
no heartbeat for 250ms: the worker looks stuck

time.After is created again on each loop iteration, so it measures silence since the last heartbeat. Always Stop a ticker you're done with (defer tick.Stop()). time.Tick(d) returns only the ticker's channel, with no way to stop it; since Go 1.23 an unreferenced ticker can be garbage collected, but Tick is still best for things that tick for the life of the program.

The Go 1.23 timer change

Before Go 1.23, a timer's channel had a buffer of 1. If the timer fired while nobody was reading, the value stayed in the buffer, and after Reset the next receive got that stale value (one that's out of date) at once. Go 1.23 made timer channels unbuffered (synchronous), so after Stop or Reset returns no stale value can be received, and it lets unreferenced, unstopped timers be garbage collected.

The new behaviour is chosen by the go line in go.mod (episode 28), so old programs keep their old behaviour. The compiler stage runs these as a module with go run ..

go 1.22:

// $ go run .
// ---- go.mod ----
module shop

go 1.22
// ---- main.go ----
package main

import (
    "fmt"
    "time"
)

func main() {
    t := time.NewTimer(50 * time.Millisecond)
    time.Sleep(100 * time.Millisecond) // it fires while nobody reads t.C
    t.Reset(time.Second)               // set it again: 1 second from now
    start := time.Now()
    <-t.C
    fmt.Println("fired after", time.Since(start).Round(time.Millisecond))
}

Real output:

$ go run .
fired after 0s

go 1.24:

// $ go run .
// ---- go.mod ----
module shop

go 1.24
// ---- main.go ----
package main

import (
    "fmt"
    "time"
)

func main() {
    t := time.NewTimer(50 * time.Millisecond)
    time.Sleep(100 * time.Millisecond) // it fires while nobody reads t.C
    t.Reset(time.Second)               // set it again: 1 second from now
    start := time.Now()
    <-t.C
    fmt.Println("fired after", time.Since(start).Round(time.Millisecond))
}

Real output:

$ go run .
fired after 1s

Same code, same toolchain: only the go.mod line changed. You can force the old behaviour with the setting GODEBUG=asynctimerchan=1, or a godebug line in go.mod:

// $ go run .
// ---- go.mod ----
module shop

go 1.24

godebug asynctimerchan=1
// ---- main.go ----
package main

import (
    "fmt"
    "time"
)

func main() {
    t := time.NewTimer(50 * time.Millisecond)
    time.Sleep(100 * time.Millisecond)
    t.Reset(time.Second)
    start := time.Now()
    <-t.C
    fmt.Println("fired after", time.Since(start).Round(time.Millisecond))
}

Real output:

$ go run .
fired after 0s

Mini project: the chai stall monitor

One for-select loop: a ticker prints "stall open" every 200 ms, orders arrive at uneven gaps, a quiet timer fires after 500 ms without orders (and is Reset after each order), a closing timer ends everything after 2 s, and when the orders stream closes its case is switched off with nil.

package main

import (
    "fmt"
    "time"
)

func customers(orders chan<- string) {
    gaps := []int{50, 80, 600, 40, 120} // ms between orders
    for i, g := range gaps {
        time.Sleep(time.Duration(g) * time.Millisecond)
        orders <- fmt.Sprint("chai #", i+1)
    }
    close(orders) // bonus: the stream ends early
}

func main() {
    start := time.Now()
    at := func() time.Duration { return time.Since(start).Round(10 * time.Millisecond) }
    orders := make(chan string)
    go customers(orders)

    tick := time.NewTicker(200 * time.Millisecond)
    defer tick.Stop()
    closing := time.NewTimer(2 * time.Second)
    defer closing.Stop()
    quiet := time.NewTimer(500 * time.Millisecond)
    defer quiet.Stop()

    for {
        select {
        case o, ok := <-orders:
            if !ok {
                orders = nil // switch this case off
                fmt.Println(at(), "no more customers today")
                continue
            }
            fmt.Println(at(), "cooking", o)
            quiet.Reset(500 * time.Millisecond) // Go 1.23+: no stale value
        case <-tick.C:
            fmt.Println(at(), "stall open")
        case <-quiet.C:
            fmt.Println(at(), "quiet, wiping counter")
            quiet.Reset(500 * time.Millisecond)
        case <-closing.C:
            fmt.Println(at(), "closing the stall")
            return
        }
    }
}

Real output (exact times vary a little):

50ms cooking chai #1
130ms cooking chai #2
200ms stall open
400ms stall open
600ms stall open
630ms quiet, wiping counter
730ms cooking chai #3
770ms cooking chai #4
800ms stall open
890ms cooking chai #5
890ms no more customers today
1s stall open
1.2s stall open
1.39s quiet, wiping counter
1.4s stall open
1.6s stall open
1.8s stall open
1.89s quiet, wiping counter
2s stall open
2s closing the stall

Common mistakes (and the real results)

Mistake Real result Why Fix
receiving from channels in turn map[nonveg:3 veg:3] a receive waits on one channel select
relying on case order picked: map[a:505 b:495] ready cases are chosen at random don't depend on order
for + select + default to wait a spinning CPU default never blocks block, or add a timer
a closed channel left in a select loop wasted wake-ups ...: 402704 a closed receive is always ready set it to nil
unbuffered result channel + timeout a leaked goroutine per timeout nobody receives the late result buffer of 1
a ticker never stopped resources held (before Go 1.23, never freed) it keeps firing defer t.Stop()
Reset after an unread fire, old go.mod fired after 0s stale buffered value go 1.23+ in go.mod
time.After in a long-lived loop body for a whole-loop deadline the deadline restarts every iteration a new timer each time create one Timer before the loop

Practice

  1. Count select's choices with three always-ready channels, 300 rounds.
  2. Add a 100 ms timeout to episode 48's mandi example, so the shop uses yesterday's price if no supplier answers in time, without leaking goroutines.
  3. Predict the output: a buffered channel of capacity 1, three non-blocking sends with default, then a non-blocking receive from a nil channel.
  4. Why does the heartbeat watchdog create time.After inside the loop, while the chai stall's closing time uses one Timer created before the loop?
Solutions

1.

package main

import "fmt"

func main() {
    a, b, c := make(chan int, 300), make(chan int, 300), make(chan int, 300)
    for i := 0; i < 300; i++ {
        a <- i
        b <- i
        c <- i
    }
    picked := map[string]int{}
    for i := 0; i < 300; i++ {
        select {
        case <-a:
            picked["a"]++
        case <-b:
            picked["b"]++
        case <-c:
            picked["c"]++
        }
    }
    fmt.Println(picked)
}

Real output (varies, about 100 each):

map[a:101 b:97 c:102]

2.

package main

import (
    "fmt"
    "time"
)

func ask(supplier string, delay time.Duration, answer chan<- string) {
    time.Sleep(delay)
    answer <- supplier
}

func main() {
    answer := make(chan string, 3) // every supplier can finish
    go ask("Mandi A", 300*time.Millisecond, answer)
    go ask("Mandi B", 250*time.Millisecond, answer)
    select {
    case s := <-answer:
        fmt.Println("first answer:", s)
    case <-time.After(100 * time.Millisecond):
        fmt.Println("no price in 100ms: use yesterday's")
    }
}

Real output:

no price in 100ms: use yesterday's

The buffer of 3 lets both late suppliers finish after main stopped waiting.

3.

package main

import "fmt"

func main() {
    jobs := make(chan int, 1)
    for i := 1; i <= 3; i++ {
        select {
        case jobs <- i:
            fmt.Println("queued", i)
        default:
            fmt.Println("dropped", i)
        }
    }
    var never chan int
    select {
    case v := <-never:
        fmt.Println("got", v)
    default:
        fmt.Println("nil channel: never ready")
    }
}

Real output:

queued 1
dropped 2
dropped 3
nil channel: never ready

4. The watchdog measures silence since the last heartbeat, so it must restart the clock every time; the closing time is a fixed deadline for the whole loop, so it must not restart.

Quick quiz

1. An empty unbuffered channel, a 50 ms time.After and a default, in one select. What prints? (From the video.)

A. nothing ready · B. timeout · C. got 0 · D. deadlock

Answer

A. When select runs, neither case is ready and default exists, so it runs at once without waiting for the timer.

2. select {} (no cases) in main, with no other goroutines. What happens?

Answer

It blocks forever; with no other goroutines Go reports fatal error: all goroutines are asleep - deadlock! (the goroutine state is [select (no cases)]).

3. What does t.Stop() return if the timer already fired?

Answer

false.

4. In a select loop merging two channels, how do you stop reading from one that closed?

Answer

Set its variable to nil; a nil channel is never ready, so its case is ignored.

Interview questions

  1. What does select do? Waits on several channel operations and runs one that can proceed; blocks if none can (unless there's a default).
  2. How does select choose among several ready cases? Uniform pseudo-random selection, to avoid starvation.
  3. How do you do a non-blocking send or receive? A select with the operation and a default case.
  4. How do you implement a timeout? select on the result channel and time.After(d) (or a Timer, or a context deadline, episode 51).
  5. Why might a timeout leak goroutines, and how do you prevent it? The worker blocks sending a result nobody receives; give the result channel a buffer of 1 or a cancellation signal.
  6. What's the role of nil channels in select? They disable a case dynamically, e.g. after a channel closes.
  7. Timer vs Ticker vs time.After? After: one-shot channel, can't be stopped. Timer: one-shot, with Stop/Reset. Ticker: fires repeatedly until Stop.
  8. What changed for timers in Go 1.23? Timer channels became unbuffered (no stale values after Stop/Reset), and unreferenced timers/tickers can be garbage collected even if not stopped; enabled by go 1.23+ in go.mod, reversible with GODEBUG=asynctimerchan=1.
  9. What is a heartbeat? A periodic signal a goroutine sends to show it's alive and making progress; a watchdog detects missing heartbeats.

Glossary

Term Meaning Example
select a statement that waits on several channel operations and runs one that's ready select { case d := <-veg: ... }
Case (in select) one channel operation plus the code to run if it happens case d := <-nonveg:
Blocking select a select without default: waits until a case is ready the two-hatch loop
Ready case a case whose send or receive can proceed now a buffered channel with a value
Uniform pseudo-random selection every ready case has an equal chance, picked by a random generator a:505 b:495
Starvation some work never gets served because other work always wins a fixed first-case rule would starve case 2
default runs if no case is ready, so select never blocks "board full, sorry"
Non-blocking operation a send or receive that gives up instead of waiting select { case ch <- v: default: }
for-select loop for { select { ... } }, usually with a stop case the kitchen goroutine
Merging channels combining several channels into one stream veg + nonveg
Disabling a case setting its channel to nil so it's never ready veg = nil
Timeout a limit on how long to wait time.After(200 * time.Millisecond)
time.After(d) a channel that receives the time once, after d the customer's patience
time.Duration a length of time (nanoseconds as int64) 300 * time.Millisecond
Timer a value that sends the time on C once, after a duration time.NewTimer(300 * time.Millisecond)
t.C the timer's or ticker's channel <-chai.C
Stop stops a timer/ticker; for a timer, true if it hadn't fired chai.Stop()
Reset restarts a timer with a new duration chai.Reset(100 * time.Millisecond)
Ticker sends the time on C every duration until stopped time.NewTicker(100 * time.Millisecond)
time.Tick returns only a ticker's channel; can't be stopped for range time.Tick(time.Second)
Heartbeat a regular "I'm alive" signal beat <- struct{}{}
Watchdog code that notices when heartbeats stop select with time.After
Stale value a value that is out of date fired after 0s
Synchronous (unbuffered) timer channel Go 1.23+: no value is stored in the channel fired after 1s
go.mod go line the Go language version a module declares; selects default behaviours go 1.22, go 1.24
GODEBUG a setting that switches some runtime behaviours asynctimerchan=1

Summary

  • A receive waits on one channel; select waits on many and runs whichever case is ready, randomly among several.
  • default makes select non-blocking; never spin on it in a loop.
  • The for-select loop with a stop case runs a goroutine until told to stop.
  • A closed channel is always ready: set it to nil to switch its case off.
  • time.After gives timeouts; Timer adds Stop/Reset; Ticker fires repeatedly and drives heartbeats; stop what you start.
  • With go 1.23+ in go.mod, timer channels are unbuffered: no stale values after Stop/Reset, and unreferenced timers are collected.

Next episode: sync beyond Mutex, and atomics: sync.Once, OnceFunc, OnceValue, sync.Cond, sync.Map, sync.Pool, sync/atomic types, CompareAndSwap, lock-free counters and false sharing.