Tutorials / Go: From Basics to Production / select, timeouts and context

select, timeouts and context

14 min read go
Course contents (17 lessons)
  1. Getting started with Go
  2. Installing Go 1.25 and your first program
  3. Variables, types and constants
  4. Control flow: if, for and switch
  5. Functions, multiple returns and defer
  6. Slices and maps
  7. Arrays and slices
  8. Maps and working with strings
  9. Structs, methods and interfaces
  10. Structs, methods and pointers
  11. Interfaces
  12. Errors, packages and generics
  13. Error handling the Go way
  14. Packages and modules
  15. Generics
  16. Concurrency
  17. Goroutines and channels
  18. select, timeouts and context
  19. Mutexes, sync and the race detector
  20. Testing
  21. Testing and benchmarks
  22. Building and shipping a service
  23. Building an HTTP JSON API with net/http
  24. Building and deploying a Go service

Waiting on more than one thing

Sometimes a goroutine must react to whichever event comes first: a result arriving, a timeout, a shutdown signal. The select statement waits on several channel operations at once and runs the case that is ready first. It looks like switch, but every case is a channel send or receive.

select {
case res := <-results:
	fmt.Println("got", res)
case <-time.After(2 * time.Second):
	fmt.Println("timed out")
}

If several cases are ready at the same moment, Go picks one at random. If none are ready, select blocks. With a default case it never blocks, which is useful for a non-blocking attempt.

context: cancellation across goroutines

Timeouts built with time.After work for a single wait, but real programs need to stop an entire tree of work: a user closes their browser, a request takes too long, the server is shutting down. The context package carries a cancellation signal, a deadline and request-scoped values through your code.

The rule is simple: if a function can block or take long, such as calling a database or an HTTP service, it takes a context.Context as its first parameter, named ctx.

package main

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

// fetchPrice pretends to call a slow service.
func fetchPrice(ctx context.Context, sku string, delay time.Duration) (int, error) {
	select {
	case <-time.After(delay):
		return len(sku) * 100, nil
	case <-ctx.Done():
		return 0, ctx.Err()
	}
}

func main() {
	// 1. a call that finishes in time
	ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
	defer cancel()
	price, err := fetchPrice(ctx, "TEA", 100*time.Millisecond)
	fmt.Println(price, err)

	// 2. a call that is too slow
	ctx2, cancel2 := context.WithTimeout(context.Background(), 200*time.Millisecond)
	defer cancel2()
	_, err = fetchPrice(ctx2, "RICE", 2*time.Second)
	fmt.Println(err, errors.Is(err, context.DeadlineExceeded))

	// 3. manual cancellation
	ctx3, cancel3 := context.WithCancel(context.Background())
	done := make(chan struct{})
	go func() {
		defer close(done)
		ticker := time.NewTicker(100 * time.Millisecond)
		defer ticker.Stop()
		for {
			select {
			case <-ticker.C:
				fmt.Println("tick")
			case <-ctx3.Done():
				fmt.Println("stopping:", ctx3.Err())
				return
			}
		}
	}()
	time.Sleep(350 * time.Millisecond)
	cancel3()
	<-done
}

Output (the number of ticks can vary by one on a busy machine):

300 <nil>
context deadline exceeded true
tick
tick
tick
stopping: context canceled

What this shows

context.WithTimeout returns a new context that is cancelled automatically after the given time, plus a cancel function. context.WithCancel gives you a context that is cancelled when you call cancel(). Inside the work, ctx.Done() is a channel that closes when the context ends, and ctx.Err() tells you why: context.Canceled or context.DeadlineExceeded.

In fetchPrice the select races two events: the (fake) work finishing and the context ending. If the context wins, the function gives up and returns the context's error immediately, instead of making the caller wait. Real code does the same thing by passing ctx to calls such as http.NewRequestWithContext or db.QueryContext, and those libraries watch ctx.Done() for you.

Always defer cancel() right after creating a cancellable context. If you forget, the context's resources are held until the parent is cancelled, and go vet reports a "lostcancel" warning.

The ticker goroutine

The third example is a typical background loop. A time.Ticker delivers a value on ticker.C at regular intervals. The goroutine loops, waiting in select for either a tick or cancellation. After about 350 milliseconds, main cancels, the loop sees Done() and returns, and closing done lets main know the goroutine has really finished. This pattern, a loop with a select on ctx.Done(), is how nearly every long-running goroutine in Go is written. It guarantees that you can always stop it.

Rules for using context

  • Pass ctx as the first parameter. Do not store it in a struct for later use.
  • Do not pass a nil context. If you do not have one, use context.Background() in main and tests, or context.TODO() as a marker for code that still needs one.
  • Only the code that creates a context calls its cancel.
  • Use context.WithValue only for request-scoped data such as a request ID, never for optional function arguments.

Handling a shutdown signal

A very common use is stopping a server when the user presses Ctrl+C. The standard library gives you a context tied to operating system signals:

ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()

<-ctx.Done()   // blocks until Ctrl+C or a termination signal
fmt.Println("shutting down...")

We will use exactly this when we build the HTTP server, so that it finishes the requests in progress before exiting.

Common mistakes

  • Using time.After in a hot loop. Each call allocates a timer that lives until it fires. In a loop, create one timer or ticker and reuse it, or use context.WithTimeout.
  • Ignoring ctx inside long work. If your function accepts a context but never checks ctx.Done() or passes it on, cancellation does nothing.
  • Forgetting to stop a Ticker. Call ticker.Stop() when you are done with it.
  • Treating cancellation as failure. context.Canceled often means "the caller went away", which is normal. Do not log it as an error at high severity.
  • Busy-waiting with default. A select with a default inside an empty loop burns a whole CPU core. Block instead.

Try it yourself

Write a function firstResponse(ctx, urls []string) (string, error) that starts one goroutine per URL (simulate with random sleeps), and returns the name of the first one to finish. When it returns, the remaining goroutines must stop through context cancellation, not keep running. Add a one-second overall timeout and test it by making all the sleeps longer than that.

go
package main

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

// fetchPrice pretends to call a slow service.
func fetchPrice(ctx context.Context, sku string, delay time.Duration) (int, error) {
	select {
	case <-time.After(delay):
		return len(sku) * 100, nil
	case <-ctx.Done():
		return 0, ctx.Err()
	}
}

func main() {
	// 1. a call that finishes in time
	ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
	defer cancel()
	price, err := fetchPrice(ctx, "TEA", 100*time.Millisecond)
	fmt.Println(price, err)

	// 2. a call that is too slow
	ctx2, cancel2 := context.WithTimeout(context.Background(), 200*time.Millisecond)
	defer cancel2()
	_, err = fetchPrice(ctx2, "RICE", 2*time.Second)
	fmt.Println(err, errors.Is(err, context.DeadlineExceeded))

	// 3. manual cancellation
	ctx3, cancel3 := context.WithCancel(context.Background())
	done := make(chan struct{})
	go func() {
		defer close(done)
		ticker := time.NewTicker(100 * time.Millisecond)
		defer ticker.Stop()
		for {
			select {
			case <-ticker.C:
				fmt.Println("tick")
			case <-ctx3.Done():
				fmt.Println("stopping:", ctx3.Err())
				return
			}
		}
	}()
	time.Sleep(350 * time.Millisecond)
	cancel3()
	<-done
}

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account