☰ All patterns
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.
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.
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