Concurrency · 9 min read · Intermediate
Context Propagation & Cancellation
Cancel long-running work and enforce request deadlines cleanly across call trees using the context package.
What you'll learn
- Pass context.Context as the first parameter to I/O functions
- Enforce deadlines with context.WithTimeout
- Always call cancel() with defer to avoid leaks
Overview
Cancel long-running work and enforce request deadlines cleanly across call trees using the context package.
Go prioritizes simplicity, explicit control flow, fast compilation, and safe concurrency. Every feature in this lesson is part of Go’s minimal standard toolkit used across cloud infrastructure, CLI tools, and high-throughput APIs.
Idiomatic Go Example
package main
import (
"context"
"fmt"
"time"
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
defer cancel()
<-ctx.Done()
fmt.Println("Stopped:", ctx.Err())
}
Key Takeaways
- Pass context.Context as the first parameter to I/O functions
- Enforce deadlines with context.WithTimeout
- Always call cancel() with defer to avoid leaks
Quick Check
Check Your Understanding
Score: 0 / 1
1. Why should you always `defer cancel()` after calling `context.WithTimeout`?
Study Workspace
Finished this lesson?
Your progress is saved locally in your browser, no account needed.