Skip to content
Tutorials Center
My learning

Topics

Lesson 70 of 147 ยท Concurrency

The context Package

Learn Go's context package - Background and TODO, WithCancel, WithTimeout, WithDeadline, WithValue, ctx.Done and Err, cancellation propagation, Cause, AfterFunc and best practices.

Starting goroutines is easy. Stopping them at the right moment is the hard part. A user closes the browser tab, a request takes too long, a parent operation fails and its sub-tasks are now pointless: all of them should stop quickly and release their resources. Without a standard way to say "stop", every library would invent its own channel or flag.

The context package is that standard. A context.Context is a small value you pass down through function calls. It can carry a cancellation signal, a deadline, and a few request-scoped values. Almost every Go API that does I/O or can block (net/http, database/sql, gRPC clients, and many more) takes a context as its first parameter. This lesson covers creating contexts, cancellation, timeouts and deadlines, how cancellation spreads from parent to children, causes, AfterFunc, values, and the conventions to follow.

The Context interface

A context has four methods:

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

The one you use most is Done(): it returns a channel that is closed when the context is cancelled or its deadline passes. Because receiving from a closed channel returns immediately (channels), a goroutine can wait on ctx.Done() inside a select and react the moment the work is cancelled. After Done is closed, Err() explains why: context.Canceled (someone cancelled) or context.DeadlineExceeded (the time ran out). Before that, Err() is nil.

You rarely implement the interface yourself. You create contexts with the functions below.

Background and TODO

Every context tree starts with a root that is never cancelled and has no values:

  • context.Background() is the root to use in main, in tests and at the top of a request that does not already have a context.
  • context.TODO() is the same value, but a signpost for readers and tools: "a context belongs here, but I have not decided where it comes from yet".
Go The root contexts never end

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The output is Err: <nil>, Done is nil: true (a root context can never be cancelled, so it has no channel), has deadline: false, and the contexts print as context.Background and context.TODO. You then derive child contexts from the root, adding behavior.

WithCancel: stopping work on demand

context.WithCancel(parent) returns a new context and a cancel function. Calling cancel() closes the context's Done channel. A worker checks the channel and returns:

Go Cancelling a worker goroutine

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The worker prints worker stopping: context canceled - sum so far: 10. The sends are unbuffered, so all four values have been received before cancel() runs, which makes the sum predictable.

Two rules about the cancel function:

  1. Always call it, even when the work finishes normally. The usual way is defer cancel() right after creating the context. A context that is never cancelled keeps its resources (and its entry in the parent's list of children) until the parent ends.
  2. It is safe to call cancel more than once; later calls do nothing.

go vet has a check (lostcancel) that warns when you drop the cancel function.

WithTimeout and WithDeadline

Often you want to bound how long something may take. context.WithTimeout(parent, d) cancels automatically after the duration d; context.WithDeadline(parent, t) does the same at an absolute time t (a timeout is just a deadline of "now plus d").

Go A timeout that cuts a slow call short

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The first query finishes well inside the budget: fast query: rows <nil>. The second is abandoned when the 100 ms budget ends, long before its 5 seconds: slow query: "" context deadline exceeded, and errors.Is(err, context.DeadlineExceeded) is true. The context carries one budget for everything done with it, so the second call only had the remaining time; the last line confirms that Deadline() reports a deadline and that it has passed by then (has deadline: true and it already passed: true). Compare errors with errors.Is (see wrapping errors), since libraries often wrap ctx.Err().

Cancellation is cooperative. A context cannot forcibly stop a goroutine; it only announces that it is time to stop. The goroutine must check ctx.Done() (or call functions that do) at sensible points. A loop that does heavy work without ever looking at the context will keep running after the cancel.

Cancellation flows down the tree

Every With... function takes a parent. Cancelling a context cancels all contexts derived from it, but never its parent. A child can also have a shorter deadline than its parent (a longer one is clamped to the parent's).

Go Cancelling a parent cancels its children

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

All three contexts report context canceled after the parent is cancelled, even though the child had a one-hour timeout. In the last part, cancelling only the child leaves its parent untouched: p2: <nil> c2: context canceled. This one-way flow is what makes contexts convenient: cancel the context at the top of a request, and every goroutine, database call and HTTP request below it receives the signal.

Passing a context: the conventions

The Go team documents a few strict conventions. Follow them and your code will fit every library:

  • The context is the first parameter, named ctx: func Fetch(ctx context.Context, id int) (User, error).
  • Do not store contexts in structs. Pass them to each call. (The exception is a struct that represents one request or one operation, as http.Request does.)
  • Never pass a nil context. If you do not know which to use, pass context.TODO().
  • Always call the cancel function from WithCancel, WithTimeout and WithDeadline.
  • Derive, do not reuse: pass ctx to functions you call, and create child contexts only when you need a shorter deadline or an independent cancel.

Here is a typical pipeline stage that honors cancellation, written the idiomatic way:

Go A generator that stops when the context ends

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

It prints 1 2 3 4 5. Without the context, the generator goroutine would be blocked forever on ch <- n after the loop breaks: a goroutine leak. With it, defer cancel() closes Done, the select takes the second case, and the goroutine exits. This is the pattern to remember: every blocking send or receive in a long-running goroutine should be in a select with ctx.Done().

Cause: why was it cancelled?

ctx.Err() only says canceled or deadline exceeded. Since Go 1.20 you can attach a more specific reason with WithCancelCause, and read it with context.Cause(ctx). There are also WithTimeoutCause and WithDeadlineCause (Go 1.21):

Go Cancelling with a cause

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

You get Err: context canceled next to Cause: quota exceeded, and for the timeout Err: context deadline exceeded next to Cause: upstream service too slow. Err stays the same standard sentinel for compatibility, while Cause carries the detail. If no cause is given, Cause returns the same as Err.

AfterFunc and WithoutCancel

Two newer helpers handle special situations.

context.AfterFunc(ctx, f) (Go 1.21) runs f in its own goroutine after ctx is done. It returns a stop function that prevents the call if it has not started. It is handy for cleanup that must happen on cancellation, such as closing a connection that cannot itself watch a context:

Go Running cleanup when a context ends

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The first stop() returns true (the function had not run), so the first cleanup never prints. The second registration fires after cancel(): second cleanup ran. stop() returns false if the function already started or was stopped before.

context.WithoutCancel(parent) (Go 1.21) returns a context that keeps the parent's values but is never cancelled. Use it when work must outlive the request, for example writing an audit log after the client has disconnected. Do this deliberately and rarely.

Context values

context.WithValue(parent, key, value) returns a context that carries one key and value; ctx.Value(key) looks it up through the chain of parents. Values are meant for request-scoped data that crosses API boundaries, such as a request ID, an authenticated user, or a trace ID. They are not a way to pass optional function parameters.

Use your own unexported key type, so keys from different packages can never collide:

Go Request-scoped values with a private key type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The first call prints no request id, the second handling request req-42, and looking up the plain string "requestID" gives <nil>, because keys are compared by type and value and our key type is private to the package. The small WithRequestID and RequestID helpers keep the key hidden and the type assertion in one place.

Do's and don'ts

  • Do use values for request IDs, trace and user identity, deadlines of the caller.
  • Don't put database handles, loggers you could pass explicitly, configuration or optional arguments in a context. Values are untyped and invisible in a function signature, which hurts readability and testing.
  • Don't use built-in types like string as keys; define your own type.
  • Values are immutable: WithValue creates a new context and leaves the old one unchanged. Lookup walks the parent chain, so deep chains slow it slightly.

Contexts in the standard library

Because the convention is universal, most blocking standard-library calls accept a context:

Go
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
rows, err := db.QueryContext(ctx, "SELECT ...")
cmd := exec.CommandContext(ctx, "ffmpeg", args...)
conn, err := (&net.Dialer{}).DialContext(ctx, "tcp", addr)

An incoming *http.Request carries a context (r.Context()) that is cancelled when the client disconnects, so passing it on gives you free cleanup. You will use this heavily in Building an HTTP Server. For graph-shaped work, combine contexts with the patterns in Concurrency Patterns: a failure in one worker cancels the shared context and stops its siblings.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does ctx.Done() return?

    Done returns a receive-only channel that is closed on cancellation or deadline. Err() then tells you the reason.
  2. 2. Why should you usually write defer cancel() right after ctx, cancel := context.WithTimeout(...)?

    The context keeps timers and a link to its parent until it ends. Calling cancel releases them early; go vet warns when the cancel function is lost.
  3. 3. A parent context is cancelled. What happens to a child created with context.WithTimeout(parent, time.Hour)?

    Cancellation flows from parent to all descendants, regardless of their own deadlines. The reverse is not true: cancelling a child never affects its parent.
  4. 4. Where should the context parameter go in a function signature?

    By convention the context is the first parameter, func F(ctx context.Context, ...), and it is not stored in structs.
  5. 5. Which is a good use of context.WithValue?

    Context values are for request-scoped data that crosses API boundaries, such as request or trace IDs. Dependencies and options belong in explicit parameters or struct fields.

Summary

  • A context.Context carries cancellation, a deadline and request-scoped values through a call tree; blocking and I/O functions take it as their first parameter, ctx.
  • Start from context.Background() (or context.TODO() when undecided) and derive children with WithCancel, WithTimeout, WithDeadline and WithValue.
  • Always call the returned cancel function, normally with defer cancel().
  • ctx.Done() is a channel closed on cancellation; ctx.Err() returns context.Canceled or context.DeadlineExceeded; compare with errors.Is.
  • Cancellation is cooperative and flows from parent to children, never upward: long-running code must check Done() inside select.
  • WithCancelCause and context.Cause record why; context.AfterFunc runs cleanup on cancellation; context.WithoutCancel detaches work from cancellation but keeps values.
  • Use values only for request-scoped data, with your own unexported key type; never store contexts in structs or pass nil.

Next: Concurrency Patterns combines goroutines, channels and contexts into pipelines, worker pools and more.