Back to Concepts Roadmap
🟤 Level 7 — Runtime & Concurrency
Concurrency

Context (Timeouts & Cancellation)

Propagating cancellation signals, deadlines, and request-scoped metadata across API layers.

Real-World Analogy (Mental Model)

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.
Step-by-Step Code

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.

example.goGo 1.24+
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()

req, _ := http.NewRequestWithContext(ctx, "GET", "https://api.com", nil)
Battle-Tested Production Case Study

How Kubernetes Prevents Cluster-Wide Goroutine Floods via Context Cancellation

Kubernetes Architecture
Production Challenge

When a network partition occurred, blocked HTTP API client calls left orphaned goroutines waiting indefinitely for network I/O, eventually exhausting node memory (OOM).

Architectural Solution

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.

production_pattern.goZero leaked goroutines during network splits; memory footprint stabilized under peak load.
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

Mistake: Misusing context (timeouts & cancellation) without understanding its memory or concurrency semantics.
✅ Correct Way: Always follow standard Go idioms and verify with tests.
Self Assessment

Knowledge Check

Verify your understanding with these interactive practice questions.

Quizzes

Quick checks for understanding

Multiple-choice with inline explanations—expand to see why.

What is the primary concept behind Context (Timeouts & Cancellation)?

Finished this lesson?

Mark it as complete to track your overall Go mastery.