Context in Go: timeouts and cancellation
Learn Go · Beginner · 12 min · After Goroutines and channels: work at the same time
How do you tell running work to stop?
1Guess
package main import ( "context" "fmt" "time" ) func main() { ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond) defer cancel() select { case <-ctx.Done(): fmt.Println(ctx.Err()) case <-time.After(time.Second): fmt.Println("finished") } }2Read
What a Context is
A
context.Contextcarries a cancel signal, an optional deadline and values across function calls. Pass it as the first parameter, namedctx. Work that can stop watchesctx.Done(), a channel that closes when the context ends. Create one withcontext.WithCancel(parent). It returns a new context and acancelfunction. Alwaysdefer cancel(), so the resources are released.3Code
Stop a worker with WithCancel
1 / 2package main import ( "context" "fmt" ) func worker(ctx context.Context, steps <-chan int, done chan<- int) { count := 0 for { select { case <-ctx.Done(): done <- count return case <-steps: count++ } } } func main() { ctx, cancel := context.WithCancel(context.Background()) steps := make(chan int) done := make(chan int) go worker(ctx, steps, done) for i := 0; i < 3; i++ { steps <- i } cancel() fmt.Println("steps done:", <-done) fmt.Println(ctx.Err()) }Read the program. What will it print?
4Read
Timeouts and deadlines
context.WithTimeout(parent, d)cancels itself afterd;WithDeadlinetakes a fixed time. When it ends,ctx.Err()iscontext.DeadlineExceeded, orcontext.Canceledafter acancel()call. Test for them witherrors.Is(err, context.DeadlineExceeded). Contexts form a tree: when a parent is cancelled, every child made from it is cancelled too.5Code
An operation that respects its context
1 / 2package main import ( "context" "errors" "fmt" "time" ) func slowOp(ctx context.Context, d time.Duration) error { select { case <-time.After(d): return nil case <-ctx.Done(): return ctx.Err() } } func main() { ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) defer cancel() fmt.Println(slowOp(ctx, time.Millisecond)) err := slowOp(ctx, time.Second) fmt.Println(err) fmt.Println(errors.Is(err, context.DeadlineExceeded)) }Read the program. What will it print?
6Fix
package main import ( "context" "fmt" "time" ) func slowOp(ctx context.Context, d time.Duration) error { time.Sleep(d) return nil } func main() { ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond) defer cancel() if err := slowOp(ctx, 300*time.Millisecond); err != nil { fmt.Println("stopped:", err) return } fmt.Println("done") }7Say it back
8Mission · 12 min
Write a program that prints a counter every 100 ms and stops after a one-second timeout set with a context. When it stops, print the reason from ctx.Err().
go run .
Common questions
- Why is ctx the first parameter in Go?
- It is a convention that the standard library and most packages follow, written as ctx context.Context. A fixed place makes calls easy to read and lets tools and reviewers see at a glance which functions can be cancelled. Do not store a context in a struct field; pass it to each call that needs it, so every call can have its own limit.
- Does cancelling a context stop my goroutine automatically?
- No. Cancelling only closes the channel returned by ctx.Done() and sets ctx.Err(). Your code must watch that channel, usually in a select, and return when it closes. A goroutine that never checks the context keeps running. That is why standard library functions that accept a context check it for you.
- What is the difference between context.Canceled and DeadlineExceeded?
- Both are values of ctx.Err() after a context ends. Canceled means someone called the cancel function, or a parent was cancelled. DeadlineExceeded means a timeout or deadline passed. Use errors.Is to test for them, because they are often wrapped, and use the difference to decide whether to retry or to report a timeout to the user.
Sources
- https://pkg.go.dev/context (read 2026-12-03)
- https://go.dev/blog/context (read 2026-12-03)
- https://go.dev/doc/database/cancel-operations (read 2026-12-03)
Measured with go1.27.4 darwin/arm64 on 2026-12-03
Published Dec 3, 2026 · Updated Dec 3, 2026