Concurrency

Context

Carries deadlines, cancellation signals, and request-scoped values.

Request cancellationTimeoutsRequest tracing

Understanding Context

The Context pattern carries deadlines, cancellation signals, and request-scoped values across API boundaries and between goroutines. Go\'s context.Context is a built-in interface that propagates cancellation through a tree of goroutines — when a parent context is cancelled, all derived child contexts are cancelled too, enabling graceful shutdown of entire request processing chains. Every HTTP handler, database query, and RPC call in production Go code should accept a context as its first parameter. This is not just a pattern — it\'s a Go standard practice enforced by linters and style guides.

Key Concepts

  • context.Background() — the root context — never cancelled, used as the top of the tree
  • context.WithCancel() — creates a child context with a cancel function that stops all descendants
  • context.WithTimeout() — automatically cancels after a duration — essential for preventing hung operations
  • context.Value() — carries request-scoped data (trace IDs, auth tokens) — use sparingly, not as a general container

When to Use

✅ Use when
  • • Every HTTP handler, database query, and RPC call (standard Go practice)
  • • You need to propagate cancellation through a chain of goroutines
  • • You want to set timeouts for long-running operations
  • • You need to pass request-scoped values like trace IDs or auth info
⚠️ Avoid when
  • • You\'re using context.Value() as a general-purpose key-value store (anti-pattern)
  • • Passing explicit parameters is clearer than hiding data in context
  • • The operation is so simple it doesn\'t need cancellation support

Structure

Parent Context (Background)
↓ WithCancel / WithTimeout
Child Context
↓ passed to
Goroutine A
Goroutine B
Goroutine C

How It Works

Parent Context
WithCancel()
Worker 1
ctx.Done()?
Worker 2
ctx.Done()?
Worker 3
ctx.Done()?
Timeout: 5s
Context created with cancel/timeout
1

Create Context

Parent creates context with cancel or timeout.

1 / 4

Basic Implementation

Context with cancellation signal:

main.go
Loading editor...

Real-World Example: Timeout Handling

HTTP-style request with timeout:

main.go
Loading editor...