Context (Timeouts & Cancellation)
Propagating cancellation signals, deadlines, and request-scoped metadata across API layers.
“A mission commander with a red abort button. If the mission timer expires, pressing the abort button sends an instant cancel signal to all agents in the field.”
Key Concepts & Rules To Remember
- Always pass `ctx context.Context` as the first argument of functions performing I/O.
- `context.WithTimeout()` cancels operations that exceed time limits.
- Prevents wasted server CPU on abandoned HTTP client requests.
1. Understanding Context (Timeouts & Cancellation)
Propagating cancellation signals, deadlines, and request-scoped metadata across API layers. In Go, context (timeouts & cancellation) is designed around clarity and high runtime efficiency.
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
req, _ := http.NewRequestWithContext(ctx, "GET", "https://api.com", nil)How Kubernetes Prevents Cluster-Wide Goroutine Floods via Context Cancellation
When a network partition occurred, blocked HTTP API client calls left orphaned goroutines waiting indefinitely for network I/O, eventually exhausting node memory (OOM).
Mandated `context.WithTimeout()` on all etcd, client-go, and webhook calls. When an HTTP connection terminates, the top-level request context cancels instantly, terminating the whole subtree of worker goroutines.
ctx, cancel := context.WithTimeout(parentCtx, 5*time.Second)
defer cancel()
// etcd query automatically terminates if it exceeds 5 seconds
res, err := etcdClient.Get(ctx, "/registry/pods/default/nginx")Common Beginner Pitfalls & Mistakes
Knowledge Check
Verify your understanding with these interactive practice questions.
Quizzes
Quick checks for understanding
Multiple-choice with inline explanations—expand to see why.
Finished this lesson?
Mark it as complete to track your overall Go mastery.