WithCancel and WithTimeout
Creating cancelable and timed contexts
WithCancel and WithTimeout is a free Go Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
context.WithCancel
WithCancel derives a new context with a cancel function. Calling cancel closes the Done channel of the derived context and all its children.
ctx, cancel := context.WithCancel(parent)
defer cancel() // always call to release resources
go doWork(ctx)Always defer cancel
Failing to call cancel leaks the goroutine that monitors the parent context. Always defer cancel immediately after creating a cancellable context.
context.WithTimeout
WithTimeout derives a context that cancels automatically after the given duration. It is a convenience wrapper around WithDeadline.
ctx, cancel := context.WithTimeout(parent, 5*time.Second)
defer cancel()
if err := db.QueryContext(ctx, query); err != nil {
// err may be context.DeadlineExceeded
}Checking Err()
After Done is closed, ctx.Err() returns the reason: context.Canceled (cancelled explicitly) or context.DeadlineExceeded (timeout).
if err := ctx.Err(); errors.Is(err, context.DeadlineExceeded) {
log.Println("timeout")
}Cancelling from another goroutine
The cancel function is safe to call from any goroutine and from multiple goroutines simultaneously. Only the first call has effect.
ctx, cancel := context.WithCancel(context.Background())
go func() {
if detectError() { cancel() }
}()HTTP request timeout
Set a per-request timeout with WithTimeout on the incoming request context:
func handler(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
defer cancel()
result, err := service.Call(ctx)
// ...
}Cascading cancellation
If a parent context is cancelled, all derived contexts (children, grandchildren) are cancelled automatically, stopping all goroutines in the call tree.
Context in tests
Use context.Background() or context.WithTimeout in tests to ensure goroutines started by tests are bounded in time.
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
testResult := runTest(ctx)Propagating context through libraries
Always pass the context you received to outgoing calls (DB queries, HTTP calls, RPCs). Never discard or replace it unless you have a specific reason to reset the deadline.
Creating a context for a background job
For background jobs not tied to a request, use context.Background() as the root and add a WithCancel so the job can be stopped gracefully.
select with Done
Always select on ctx.Done() alongside the work channel to avoid blocking when the context is cancelled before work completes.
select {
case result := <-workCh:
return result, nil
case <-ctx.Done():
return nil, ctx.Err()
}Quick Check
What is the difference between context.WithCancel and context.WithTimeout?
Recap: WithCancel and WithTimeout
Key points:
- Always defer cancel() right after creation
- WithTimeout auto-cancels after duration; returns DeadlineExceeded
- ctx.Err() distinguishes Canceled vs DeadlineExceeded
- Cancellation propagates to all derived contexts
Frequently asked questions
Is the “WithCancel and WithTimeout” lesson free?
Yes — the full text of “WithCancel and WithTimeout” is free to read here on the web, and the Go Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Go Academy course, upgrade to CoddyKit PRO.
What will I learn in “WithCancel and WithTimeout”?
Creating cancelable and timed contexts You practise Go Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Go Academy?
No prior experience is required. Go Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “WithCancel and WithTimeout” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Go Academy lesson?
Yes. Every Go Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Why context.Context Exists
- WithCancel and WithTimeout
- WithDeadline and WithValue
- Context in HTTP and Database Calls