The Analogy: The Notice Passed Down the Chain
A client cancels a building job. They do not walk the site telling each tradesperson individually -- they hand one notice to the main contractor, who hands it to every subcontractor they engaged, who hand it to theirs. Within minutes the electrician on the third floor knows, even though the client has never met them. The notice travels down the chain of engagement, not across it.
Three things about that notice matter. It carries a reason -- cancelled, or the deadline passed. It only flows downwards: a subcontractor stopping their own work does not cancel the whole job. And it is a request, not a physical intervention: nobody switches off the electrician's drill, so if they have their headphones on and never check the site office, they keep drilling. The notice works only because everyone has agreed to check for it.
context.Context is that notice, and a Go program's call tree is the chain of engagement. An incoming HTTP request creates one context with a deadline; every function it calls receives that context and passes it on; every database query, outbound request and worker goroutine underneath it selects on the same Done() channel. When the client hangs up, one cancel() at the top propagates to every goroutine below it, and each one returns instead of continuing to burn a connection nobody is waiting on.
The part people underestimate is the last property. Cancellation in Go is cooperative. There is no mechanism to kill a goroutine; ctx.Done() closing is only an announcement, and a function that never checks it -- or that calls a blocking operation which ignores contexts -- will run to completion regardless. Everything in this lesson is about making that announcement reach the places that need to hear it.
Syntax or Core Structure
package main
import (
"context"
"errors"
"fmt"
"time"
)
// work does "steps" units of work, checking the notice before each one.
func work(ctx context.Context, name string, steps int) error {
for i := 0; i < steps; i++ {
select {
case <-ctx.Done():
return fmt.Errorf("%s: %w", name, ctx.Err())
case <-time.After(5 * time.Millisecond):
// one unit of real work
}
}
return nil
}
func main() {
root := context.Background()
// 1. A deadline the work cannot possibly meet.
slow, cancelSlow := context.WithTimeout(root, 25*time.Millisecond)
defer cancelSlow()
err := work(slow, "slow", 1000)
fmt.Println(err)
fmt.Println(" is DeadlineExceeded:", errors.Is(err, context.DeadlineExceeded))
// 2. Cancellation triggered from somewhere else entirely.
quick, cancelQuick := context.WithCancel(root)
defer cancelQuick()
go func() {
time.Sleep(25 * time.Millisecond)
cancelQuick()
}()
err = work(quick, "quick", 1000)
fmt.Println(err)
fmt.Println(" is Canceled:", errors.Is(err, context.Canceled))
// 3. Cancelling a parent cancels every descendant.
parent, cancelParent := context.WithCancel(root)
child, cancelChild := context.WithTimeout(parent, time.Hour)
defer cancelChild()
cancelParent()
<-child.Done()
fmt.Println("child of a cancelled parent:", child.Err())
// 4. A parent's deadline is a ceiling: a child cannot extend it.
tight, cancelTight := context.WithTimeout(root, 10*time.Millisecond)
defer cancelTight()
loose, cancelLoose := context.WithTimeout(tight, time.Hour)
defer cancelLoose()
d, ok := loose.Deadline()
fmt.Println("child kept the parent's deadline:", ok, time.Until(d) < time.Second)
// 5. Work that fits inside its budget.
fine, cancelFine := context.WithTimeout(root, time.Second)
defer cancelFine()
fmt.Println("finished within budget:", work(fine, "fast", 3) == nil)
}
Output:
slow: context deadline exceeded
is DeadlineExceeded: true
quick: context canceled
is Canceled: true
child of a cancelled parent: context canceled
child kept the parent's deadline: true true
finished within budget: true
Case 3 and case 4 are the two facts that make contexts a tree rather than a bag of flags. Cancelling parent cancelled child even though child had asked for an hour, and child.Err() reports Canceled -- the parent's reason, inherited. Case 4 is the same rule applied to time: WithTimeout(tight, time.Hour) did not produce an hour-long deadline, it produced tight's ten milliseconds, because a child can only ever tighten a budget.
Technical Depth: A Tree of Notices
The interface is four methods
| Method | Returns | Notes |
|---|---|---|
Done() <-chan struct{} | a channel closed on cancellation | nil for a context that can never be cancelled, and a receive on a nil channel blocks forever |
Err() error | nil, context.Canceled, or context.DeadlineExceeded | non-nil after Done is closed, and never changes afterwards |
Deadline() (time.Time, bool) | when it will expire | ok == false means no deadline |
Value(key any) any | request-scoped data | walks up the parent chain |
That is the whole contract. Every constructor in the package returns something implementing exactly these four methods.
The constructor family
| Constructor | Since | Purpose |
|---|---|---|
Background() | 1.7 | the root of a program's tree: never cancelled, no deadline, no values |
TODO() | 1.7 | identical behaviour, but marks a call site you have not plumbed yet |
WithCancel(parent) | 1.7 | returns a child plus the cancel func that stops it |
WithDeadline(parent, t) | 1.7 | cancels itself at an absolute time |
WithTimeout(parent, d) | 1.7 | WithDeadline(parent, time.Now().Add(d)) |
WithValue(parent, k, v) | 1.7 | attaches one key/value pair |
WithCancelCause(parent) | 1.20 | cancel(err) records why, retrievable with Cause |
Cause(ctx) | 1.20 | the reason, which may be more specific than Err() |
WithDeadlineCause / WithTimeoutCause | 1.21 | supply the error a timeout should report as its cause |
AfterFunc(ctx, f) | 1.21 | run f in its own goroutine once ctx is done; returns a stop func |
WithoutCancel(parent) | 1.21 | keeps the parent's values, drops its cancellation |
Err is the class, Cause is the reason
ctx, cancel := context.WithCancelCause(context.Background())
cancel(fmt.Errorf("upstream returned 503"))
ctx.Err() // context.Canceled -- always one of two values
context.Cause(ctx) // upstream returned 503 -- your error, wrapped or not
Err() deliberately reports only Canceled or DeadlineExceeded so that errors.Is checks stay stable. Cause is the escape hatch for propagating a specific reason down the tree, and it works through descendants: a grandchild of the cancelled context reports the same cause.
Cancellation is cooperative, and cancel is not optional
Calling cancel is what detaches a child from its parent. Skip it and the child stays registered on the parent's list of children until the parent itself is cancelled, which for a long-lived parent is a leak of both memory and, for timer-based contexts, a live timer. cancel is idempotent and safe to call from multiple goroutines, so defer cancel() on the line after the constructor is unconditionally correct -- and go vet's lostcancel analyser exists to catch the cases where you forget.
Values: narrow by design
type reqIDKey struct{} // unexported: nothing outside this package can collide
func WithRequestID(ctx context.Context, id string) context.Context {
return context.WithValue(ctx, reqIDKey{}, id)
}
func RequestID(ctx context.Context) (string, bool) {
id, ok := ctx.Value(reqIDKey{}).(string)
return id, ok
}
Three rules follow from how Value works. The key must be a private type, never a bare string, because two packages using "id" would silently overwrite each other. Lookup walks the parent chain one node at a time, so it is O(depth) and not a place for hot-path data. And the contents should be limited to data that genuinely belongs to the request -- a trace span, an authenticated subject, a request id. Configuration, loggers and database handles are dependencies: pass them as parameters or struct fields, where the compiler can check them.
AfterFunc and WithoutCancel
stop := context.AfterFunc(ctx, func() { conn.Close() })
defer stop() // stop reports whether it prevented f from running
// A request has ended, but this audit write must still complete.
go writeAudit(context.WithoutCancel(ctx), entry)
AfterFunc replaces the hand-written go func() { <-ctx.Done(); cleanup() }(), and correctly does nothing if the context was already done. WithoutCancel solves the opposite problem: work that must outlive the request but should still carry its trace id.
The conventions
Pass the context as the first parameter, name it ctx, and never accept nil -- use context.TODO() at a call site you intend to fix. Do not store a context in a long-lived struct; a context describes one operation's lifetime, so a struct field turns a per-call deadline into a permanent one. Library code should never invent context.Background() internally, because that silently opts the caller out of cancellation.
Real World Example: One Budget, Three Backends
A handler needs three pieces of data from three services and has a fixed budget for the whole request. If any one of them fails outright there is no point waiting for the others, and if the budget runs out everyone should stop. That is two different cancellations layered on one tree.
package main
import (
"context"
"errors"
"fmt"
"sync"
"time"
)
var ErrUpstream = errors.New("upstream unavailable")
type job struct {
name string
took time.Duration
fail bool
}
type result struct {
name string
body string
err error
}
// backend stands in for a real dependency: it either answers after "took",
// or notices the notice first and gives up.
func backend(ctx context.Context, j job) (string, error) {
select {
case <-ctx.Done():
return "", fmt.Errorf("%s: %w", j.name, ctx.Err())
case <-time.After(j.took):
}
if j.fail {
return "", fmt.Errorf("%s: %w", j.name, ErrUpstream)
}
return j.name + "-payload", nil
}
// fetchAll layers two cancellations on the caller's context: a shared budget,
// and an abort that the first real failure triggers for its siblings.
func fetchAll(parent context.Context, budget time.Duration, jobs []job) ([]result, error) {
timed, cancelBudget := context.WithTimeout(parent, budget)
defer cancelBudget()
ctx, abort := context.WithCancelCause(timed)
defer abort(nil)
out := make([]result, len(jobs))
var wg sync.WaitGroup
for i, j := range jobs {
wg.Add(1)
go func() { // requires go 1.22+ in go.mod for per-iteration i and j
defer wg.Done()
body, err := backend(ctx, j)
out[i] = result{name: j.name, body: body, err: err} // own slot: no lock needed
if errors.Is(err, ErrUpstream) {
abort(err) // first caller sets the cause; later calls are no-ops
}
}()
}
wg.Wait()
if cause := context.Cause(ctx); cause != nil && !errors.Is(cause, context.Canceled) {
return out, cause
}
return out, nil
}
func run(label string, budget time.Duration, jobs []job) error {
fmt.Printf("%s (budget %v)\n", label, budget)
out, err := fetchAll(context.Background(), budget, jobs)
for _, r := range out {
if r.err != nil {
fmt.Printf(" %-8s %-5s %s\n", r.name, "error", r.err)
continue
}
fmt.Printf(" %-8s %-5s %s\n", r.name, "ok", r.body)
}
fmt.Println(" fetchAll error:", err)
return err
}
func main() {
ms := time.Millisecond
run("scenario A: all three answer", 500*ms, []job{
{name: "users", took: 10 * ms},
{name: "orders", took: 20 * ms},
{name: "prices", took: 15 * ms},
})
errB := run("scenario B: one fails fast", 500*ms, []job{
{name: "users", took: 10 * ms, fail: true},
{name: "orders", took: 300 * ms},
{name: "prices", took: 300 * ms},
})
fmt.Println(" cause is ErrUpstream:", errors.Is(errB, ErrUpstream))
errC := run("scenario C: the budget runs out", 50*ms, []job{
{name: "users", took: 10 * ms},
{name: "orders", took: 400 * ms},
{name: "prices", took: 400 * ms},
})
fmt.Println(" cause is DeadlineExceeded:", errors.Is(errC, context.DeadlineExceeded))
}
Output:
scenario A: all three answer (budget 500ms)
users ok users-payload
orders ok orders-payload
prices ok prices-payload
fetchAll error: <nil>
scenario B: one fails fast (budget 500ms)
users error users: upstream unavailable
orders error orders: context canceled
prices error prices: context canceled
fetchAll error: users: upstream unavailable
cause is ErrUpstream: true
scenario C: the budget runs out (budget 50ms)
users ok users-payload
orders error orders: context deadline exceeded
prices error prices: context deadline exceeded
fetchAll error: context deadline exceeded
cause is DeadlineExceeded: true
Scenario B is the payoff. users failed after ten milliseconds and called abort(err); the other two were sitting in a select waiting three hundred milliseconds each, and both returned immediately with context canceled. Nothing coordinated them -- they never learned that users specifically had failed, only that the notice had arrived. That is the whole design: the failing goroutine states a reason once, and context.Cause lets fetchAll report users: upstream unavailable rather than the useless context canceled that ctx.Err() alone would have given it.
Scenario C shows the same machinery driven by the clock instead of a peer. The timeout lives one level up the tree, on timed, so when it fires the cause propagates down through ctx to every goroutine, and context.Cause(ctx) returns DeadlineExceeded without fetchAll needing to check the clock itself. Layering the two contexts is what keeps the two concerns separate: the budget is the caller's policy, the abort is this function's policy, and either one can fire without knowing about the other.
Two details do real work here. Each goroutine writes only out[i], its own slot in a pre-sized slice, so results come back in job order with no mutex and no sorting -- concurrent writes to distinct elements of a slice do not race. And the guard cause != nil && !errors.Is(cause, context.Canceled) is what makes defer abort(nil) harmless: that deferred call runs after the return value has been computed, and even if the ordering were reversed, a bare Canceled with no specific reason is not something worth reporting to the caller.
What this function still cannot do is stop work that does not cooperate. backend is well behaved because it selects on ctx.Done(), and real equivalents -- http.NewRequestWithContext, db.QueryContext, exec.CommandContext -- are well behaved for the same reason. A CPU-bound loop or a call into a C library through cgo will keep running until it finishes, and the goroutine holding it will outlive the request no matter how many contexts you wrap around it. When that matters, the fix is inside the loop: check ctx.Err() every N iterations, exactly as backend checks it once.
Common Mistakes
- Not calling
cancel. The child stays attached to its parent's children list, and a timer-based context keeps a live timer.defer cancel()on the line after the constructor, every time --go vet'slostcancelcheck is looking for exactly this. - Storing a context in a struct field. A context describes the lifetime of one operation. Put it in a struct that lives for the process and every call inherits a deadline set once, at startup.
- Passing
nilas a context. Every method call on it panics.context.TODO()is the placeholder that says "not plumbed yet" without crashing. - Creating
context.Background()inside a library. It silently discards the caller's deadline and cancellation, so their timeout stops meaning anything below that line. - Using a
stringas aWithValuekey. Two packages that both pick"user"overwrite each other with no warning. An unexported empty struct type cannot collide. - Treating
WithValueas dependency injection. Loggers, config and database handles passed through a context are invisible to the compiler and to whoever reads the function signature. Pass them as parameters. - Checking
ctx.Err()instead of selecting onctx.Done(). A polled check only fires when the loop happens to come round; inside aselectalongside your real work, cancellation is noticed immediately. - Expecting a child to extend a parent's deadline.
WithTimeout(parent, time.Hour)on a parent expiring in a second gives you a second. Deadlines only shrink. - Reporting
ctx.Err()when a specific reason exists.context canceledin a log tells you nothing about why.WithCancelCausepluscontext.Causepreserves the actual failure. - Assuming cancellation kills goroutines. It closes a channel. A goroutine in a tight CPU loop, a blocking syscall without a context, or a cgo call runs to completion regardless.
- Forgetting that
Done()can be nil.context.Background().Done()returns nil, and a receive on a nil channel blocks forever -- fine inside aselectwith other cases, a deadlock on its own.
Best Practices
- Make
ctx context.Contextthe first parameter of every function that does I/O, blocks, or spawns goroutines, and pass it down rather than storing it. - Set the deadline once, as high up as you can -- usually where the request enters the process -- and let every layer below inherit it.
- Pair every constructor with
defer cancel()immediately, before writing anything else. - Use
WithCancelCauseandcontext.Causewhenever the reason for stopping is more interesting than the fact of it. - Wrap
ctx.Err()with%wso callers can stillerrors.IsforCanceledandDeadlineExceededthrough your own message. - Keep context values to request-scoped identity and tracing data, behind typed
With.../getter helpers with an unexported key type. - Reach for
context.AfterFuncinstead of hand-rolling a<-ctx.Done()watcher goroutine, andcontext.WithoutCancelfor work that must outlive the request. - In long CPU-bound loops, check
ctx.Err()every few thousand iterations, since there is noselectfor the scheduler to interrupt.
Practice Exercises
- Write
retry(ctx, attempts int, f func(context.Context) error) errorthat backs off between attempts and gives up immediately if the context is done. Prove with a test that a 50ms context stops it mid-backoff and that the returned error satisfieserrors.Is(err, context.DeadlineExceeded). - Build a three-level context chain with values at each level, then print what
Valuereturns for a key set at the top when queried from the bottom, and for a key set at the bottom when queried from the middle. Explain the direction of the walk. - Take the
fetchAllexample and add a per-backend timeout that is stricter than the shared budget, so a single slow dependency cannot consume the whole allowance. Show that the strict timeout wins when it is shorter and that the budget wins when it is not. - Write a CPU-bound function that sums a large slice and accepts a context, then measure how long it takes to notice cancellation when it checks
ctx.Err()every 1, every 1000, and every 1000000 iterations. Explain the tradeoff you are making.