Skip to content
GDP for Noobs
☰ All patterns
ConcurrencyIntermediate

Context Cancellation

Tell goroutines to stop: timeouts, deadlines and manual cancel.

01

Explain it like I'm new

Real-life analogy

A kitchen timer and a cancelled order

The chef sets a 10-minute timer. If it rings, stop and move on. And if the customer leaves, the waiter shouts 'cancel table 4!' and everyone working on it stops.

😩 The problem

A slow database call or API request hangs forever, or keeps running after the user closed the page, wasting resources.

💡 The pattern

Pass a context.Context to every long-running function and select on ctx.Done(). Create it with WithTimeout, WithDeadline or WithCancel.

02

Play with it

An interactive model of the pattern. Click around, nothing can break.

needs 700ms
needs 2600ms
needs 1400ms

elapsed 0ms · state: idle

💡 Every task does select { case <-done: … case <-ctx.Done(): … }. When the deadline hits, they all stop together instead of wasting work.

03

Walk through the code

Click a step to highlight its lines. This is a complete program you can copy and run.

main.go
1package main
2
3import (
4 "context"
5 "fmt"
6 "time"
7)
8
9// slowTask does work but gives up as soon as ctx says "stop".
10func slowTask(ctx context.Context, name string, takes time.Duration) error {
11 select {
12 case <-time.After(takes):
13 fmt.Printf(" %s finished\n", name)
14 return nil
15 case <-ctx.Done():
16 fmt.Printf(" %s gave up: %v\n", name, ctx.Err())
17 return ctx.Err()
18 }
19}
20
21func main() {
22 // 1. Timeout: everything under this ctx must finish within 50ms.
23 fmt.Println("With a 50ms timeout:")
24 ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
25 defer cancel() // ALWAYS call cancel to free resources
26 slowTask(ctx, "quick task (10ms)", 10*time.Millisecond)
27 slowTask(ctx, "slow task (500ms)", 500*time.Millisecond)
28
29 // 2. Manual cancel: e.g. the user closed the browser tab.
30 fmt.Println("With manual cancel after 20ms:")
31 ctx2, cancel2 := context.WithCancel(context.Background())
32 go func() {
33 time.Sleep(20 * time.Millisecond)
34 cancel2() // tell everyone listening to stop
35 }()
36 slowTask(ctx2, "report (1s)", time.Second)
37}
terminal
Press ▶ Run to execute this program.

This output was captured by running the program with Go 1.24. Copy it into your editor or the Go Playground and try changing things.

04

When should I use it?

✅ Reach for it when…

  • •Every HTTP handler, DB query, RPC or long-running goroutine.

🚫 Skip it when…

  • •Don't store a context inside a struct. Pass it as the first parameter.

🐹 Go tip

Convention: ctx context.Context is always the FIRST parameter of a function.

🌍 You've already seen it in

http.Request.Context(), db.QueryContext and every gRPC call take a context.

05

Quick check

One question. No pressure.

What happens if you forget to call cancel() from WithTimeout?

Related: Pipeline, Worker Pool