Context: cancellation and deadlines

A context carries a cancellation signal and a deadline across function calls and goroutines. It does not kill anything: it closes a channel, and every function that received the context decides to stop when that channel closes. That is why a context is the first parameter of a function that talks to the network, a database or another service, and why the discipline of checking it belongs to every layer.

WithCancel

context.Background() is the empty root. WithCancel returns a derived context and a cancel function; calling cancel closes ctx.Done(), and ctx.Err() then says why. A deferred cancel is not optional: it releases the context's resources even when the work finished on its own.

package main import ( "context" "fmt" "time" ) func main() { ctx, cancel := context.WithCancel(context.Background()) defer cancel() go func() { time.Sleep(10 * time.Millisecond) cancel() }() select { case <-ctx.Done(): fmt.Println("cancelled:", ctx.Err()) case <-time.After(time.Second): fmt.Println("never cancelled") } }

go build -o app main.go && ./app

cancelled: context canceled

The one-second case is a guard against a program that hangs when the cancellation never arrives; in a real function the guard is the deadline of the context itself. ctx.Err() returns context.Canceled for a cancel and context.DeadlineExceeded for a deadline, and both are comparable with errors.Is.

WithTimeout

WithTimeout is WithCancel plus a timer: the context is cancelled when the duration passes, with the deadline error as the reason. The timer is released by the cancel call, which is why the defer stays even here. A deadline further up the call stack is inherited: WithTimeout with a longer duration than the parent still ends when the parent ends.

package main import ( "context" "fmt" "time" ) func main() { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond) defer cancel() select { case <-time.After(50 * time.Millisecond): fmt.Println("work finished") case <-ctx.Done(): fmt.Println("stopped:", ctx.Err()) } }

go build -o app main.go && ./app

stopped: context deadline exceeded

The work would have taken fifty milliseconds and the deadline was ten, so the deadline won. A deadline is not a timeout of one call but of a whole request, and a function that receives a context should not shorten it with a timeout of its own unless it has a reason.

A function that honours the context

The function below waits for either the work or the cancellation, and returns the reason as an error. This is the shape every blocking call should have: one select with the work and ctx.Done(), and the error of the context returned unchanged so the caller can test it with errors.Is.

package main import ( "context" "fmt" "time" ) func fetch(ctx context.Context) (string, error) { select { case <-time.After(50 * time.Millisecond): return "data", nil case <-ctx.Done(): return "", ctx.Err() } } func main() { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond) defer cancel() value, err := fetch(ctx) fmt.Println("value:", value) fmt.Println("error:", err) }

go build -o app main.go && ./app

value:
error: context deadline exceeded

The value is empty and the error names the deadline. A caller can test it with errors.Is(err, context.DeadlineExceeded) and return 504 rather than 500, which is the difference between "our server is broken" and "our server gave up waiting". Wrapping the error with %w keeps that test working.

A context tree

A context derived from another is a child: cancelling the parent cancels every descendant, and cancelling a child leaves the parent alone. The child below reports the parent's error, because the error travels down the tree unchanged. That is how one deadline at the edge of a service bounds every call it makes.

package main import ( "context" "fmt" ) func main() { parent, cancelParent := context.WithCancel(context.Background()) child, cancelChild := context.WithCancel(parent) defer cancelChild() cancelParent() <-child.Done() fmt.Println("child error:", child.Err()) fmt.Println("parent error:", parent.Err()) fmt.Println("same error:", child.Err() == parent.Err()) }

go build -o app main.go && ./app

child error: context canceled
parent error: context canceled
same error: true

A context should be passed as the first argument and never stored in a struct, except in a type whose whole job is to carry it. A nil context is a bug the compiler accepts; context.TODO() is the honest placeholder for the call whose context is not wired yet.

Exercises

  1. Remove the defer cancel from the timeout program and read the vet output. Which check names the leak?
  2. Call cancel twice in the WithCancel program. What does the second call do, and why is the deferred cancel still needed after the first?
  3. Return a wrapped error from fetch and test it with errors.Is in main. What has to change in the return statement?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does a context carry?

    Answer

    A cancellation signal, a deadline and request-scoped values

    The first two are what most code uses.

  2. What does cancel() do?

    Answer

    Closes the Done channel of the context and its children

    Each function decides to stop when Done closes.

  3. Why is defer cancel() needed even when the work finished?

    Answer

    It releases the context resources and stops its timer

    A leaked timer outlives the request.

  4. What does WithTimeout add to WithCancel?

    Answer

    A timer that cancels at the deadline

    The error becomes DeadlineExceeded.

  5. What is ctx.Err() after a deadline?

    Answer

    context.DeadlineExceeded

    The two reasons are separate errors.

  6. How should a function react to a cancelled context?

    Answer

    Return ctx.Err() to the caller

    The caller can test it with errors.Is.

  7. What happens when a parent context is cancelled?

    Answer

    All its descendants end

    Cancellation flows down the tree.

  8. What happens when a child context is cancelled?

    Answer

    The parent is unaffected

    Cancellation does not flow up.

  9. Which HTTP status fits a deadline exceeded error?

    Answer

    504

    The upstream did not answer in time.

  10. What is context.TODO() for?

    Answer

    A placeholder where the context is not wired yet

    It is honest about a missing context.

The code on this page was run with go 1.26.10 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev