0Pricing
Go Academy · Lesson

Why context.Context Exists

Cancellation and request lifecycle management

Why context.Context Exists is a free Go Academy lesson on CoddyKit — lesson 1 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.

The problem

Without a mechanism to cancel in-flight work, a slow database query or HTTP call blocks its goroutine until it completes, wasting resources when the original request was already abandoned.

context.Context overview

context.Context is an interface that carries a cancellation signal, an optional deadline, and key-value metadata across API boundaries and goroutines.

type Context interface {
    Deadline() (deadline time.Time, ok bool)
    Done() <-chan struct{}
    Err() error
    Value(key any) any
}

The Done channel

ctx.Done() returns a channel that is closed when the context is cancelled or times out. Goroutines select on it to detect cancellation.

select {
case result := <-workCh:
    return result, nil
case <-ctx.Done():
    return nil, ctx.Err()
}

context.Background()

context.Background() is the root context — never cancelled, has no deadline, carries no values. Use it at the top of a request, in main, or in tests.

context.TODO()

context.TODO() is also a non-cancellable root context, used as a placeholder when the correct context is not yet available. It communicates intent to reviewers.

Why pass Context as first argument?

By convention, the first parameter of any function that can be cancelled is ctx context.Context. This makes cancellation explicit and discoverable in APIs.

func FetchUser(ctx context.Context, id int) (*User, error) {
    return db.QueryContext(ctx, "SELECT ...", id)
}

Cancellation propagates

Cancelling a parent context cancels all derived child contexts. This lets a single cancel call stop an entire tree of goroutines and operations.

What Context is not

Context is not a general-purpose bag of values — use it only for request-scoped data like trace IDs or auth tokens, not for optional parameters. Keep values in typed structs.

Standard library integration

The standard library's HTTP client, SQL driver, gRPC, and many third-party packages accept a Context, enabling cancellation to propagate through the full call stack.

Storing Context in a struct

Do not store a Context inside a struct. Pass it explicitly as a function argument. Storing it makes the cancellation lifetime opaque and often leads to bugs.

Context is immutable

A Context is immutable — you derive new contexts by wrapping with WithCancel, WithDeadline, WithTimeout, or WithValue. The parent is unmodified.

Quick Check

What does ctx.Done() return?

Recap: context.Context

Key points:

  • Carries cancellation, deadline, and metadata across goroutines
  • Pass as first argument; never store in structs
  • ctx.Done() channel closes on cancel/timeout
  • Cancellation propagates from parent to all children

Frequently asked questions

Is the “Why context.Context Exists” lesson free?

Yes — the full text of “Why context.Context Exists” 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 “Why context.Context Exists”?

Cancellation and request lifecycle management 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 1 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Why context.Context Exists” 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

  1. Why context.Context Exists
  2. WithCancel and WithTimeout
  3. WithDeadline and WithValue
  4. Context in HTTP and Database Calls
← Back to Go Academy