← writing

What context.Context is actually for

Rudra Narayan Panda ·

Every Go function that does I/O seems to take a ctx context.Context as its first argument, and for a long time I passed one along without knowing what it did. I knew it was something about timeouts. I did not know why it was an argument and not a setting, why it was a tree, or what the half-dozen With... functions were for.

This is the second post in a pair. The first covers how Go handles waiting. This one covers how you tell waiting work to stop. Every program here was run on Go 1.27.4 and the output is what it printed.

The short answer

  1. Go cannot kill a goroutine from outside. The only way to stop one is to ask it, and context is the standard way to ask.
  2. A context is a value you pass down the call chain. It carries a cancel signal, an optional deadline, and a few request-scoped values.
  3. Contexts form a tree. Cancelling one cancels everything derived from it, and never anything above it.
  4. Cancellation is cooperative. Nothing stops unless the code you call checks the context.

the problem: work you cannot take back

A user opens a page, your handler calls a service, which queries a database and starts two goroutines to fetch related data. Then the user closes the tab.

Nothing in that chain knows. The handler is still waiting, the query is still running, and both goroutines will finish their fetches and throw the results away. At small scale that is waste. Under load it is how a slow dependency turns into an outage: the requests nobody is waiting for any more keep every connection and goroutine busy.

Three things are needed to fix that, and every request needs all three:

Early Go code solved this one library at a time, usually with a done channel in a different shape for each. context started life outside the standard library and was added to it in Go 1.7, so that a server, a database driver and your own code can all be cancelled with the same value.

the interface is four methods

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

You almost never implement this interface. You get a context from the functions below and pass it on.

contexts form a tree

Every context is created from a parent. The root is context.Background(), which is never cancelled and carries nothing. Each With... call returns a child that adds one thing: a cancel signal, a deadline or a value.

A request context is cancelled and its children are cancelled with it A tree with Background at the top, a request context with a 2 second timeout below it, and three children below that: a database query with a 300 millisecond timeout, a cache lookup with a cancel function, and a context carrying a trace id. The request context and its three children are highlighted as cancelled. Background is not. Background never cancelled request WithTimeout(2s) db query WithTimeout(300ms) cache lookup WithCancel trace id WithValue request is cancelled (timeout, or the client left) every context below it is cancelled too, and Background is untouched
Orange means cancelled. The arrows are the direction the cancel signal travels. It goes down only.

Here is that tree in code, with the result:

root := context.Background()
req, cancelReq := context.WithCancel(root)
db, cancelDB := context.WithCancel(req)
defer cancelDB()
cache, cancelCache := context.WithCancel(req)
defer cancelCache()

fmt.Println("before:", req.Err(), db.Err(), cache.Err())
cancelReq()
fmt.Println("after cancelling req:", req.Err(), "|", db.Err(), "|", cache.Err())
fmt.Println("root still alive:", root.Err())
before: <nil> <nil> <nil>
after cancelling req: context canceled | context canceled | context canceled
root still alive: <nil>

The direction matters. Cancelling db alone would leave req and cache running. A child can give up without taking its parent down with it.

every way to make one

This is the whole menu. The next sections go through each row.

FunctionSinceUse it when
Background()1.7you are at the top: main, init, tests, or work you start yourself
TODO()1.7you need a context and do not have one yet. Same behavior as Background, but searchable
WithCancel1.7you decide when to stop
WithTimeout1.7stop after a duration
WithDeadline1.7stop at a clock time
WithValue1.7carry a request-scoped value down
signal.NotifyContext1.16stop when the process gets SIGINT or SIGTERM
WithCancelCause, Cause1.20you want to record why it was cancelled
WithTimeoutCause, WithDeadlineCause1.21you want a named reason when a timeout fires
WithoutCancel1.21work must outlive the request, but keep its values
AfterFunc1.21run a cleanup function when a context ends

The Since column comes from the api/go1.N.txt files in the Go distribution.

WithCancel: you decide when to stop

It returns a child and a cancel function. Call cancel and the child's Done channel closes. Use it when the stop condition is something your code detects: the first answer arrived, a user clicked cancel, one of several tasks failed.

ctx, cancel := context.WithCancel(parent)
defer cancel()

That defer cancel() is not optional, and it is the most common context mistake. Cancelling releases what the context holds (a timer, and the parent's reference to the child). Skip it, and the child stays registered with its parent until the parent ends. The package documentation says so directly: failing to call the cancel function leaks the child. After the first call, further calls do nothing, so deferring it is always fine, even if you also cancel earlier.

The toolchain catches the obvious cases. This function throws the cancel function away:

func g() {
	ctx, _ := context.WithTimeout(context.Background(), time.Second)
	_ = ctx
}
$ go vet .
main.go:15:7: the cancel function returned by context.WithTimeout should be called, not discarded, to avoid a context leak

WithTimeout and WithDeadline: stop after a limit

They are the same thing in two forms. WithTimeout(parent, 3*time.Second) is WithDeadline(parent, time.Now().Add(3*time.Second)). Use the timeout form when you have a duration and the deadline form when you already have a point in time, for example one received from a caller.

When the limit passes, Done closes and Err() returns context.DeadlineExceeded. Two behaviors are worth knowing, and I checked both:

parent, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
child, cancel2 := context.WithTimeout(parent, 5*time.Second) // asks for more than the parent has
defer cancel2()

pd, _ := parent.Deadline()
cd, _ := child.Deadline()
fmt.Println("child deadline equals parent deadline:", pd.Equal(cd))
child deadline equals parent deadline: true

A child can shorten its parent's deadline but never extend it. That is the property that makes deadlines safe to pass through code you do not own. Whatever a library asks for, it cannot run past the time you gave it.

The second is about checking the error. The error is usually wrapped by the time you see it, so compare with errors.Is, not ==:

err := short.Err()
fmt.Println(err, "| is DeadlineExceeded:", errors.Is(err, context.DeadlineExceeded))
wrapped := fmt.Errorf("fetch user: %w", err)
fmt.Println(wrapped, "| still matches:", errors.Is(wrapped, context.DeadlineExceeded))
context deadline exceeded | is DeadlineExceeded: true
fetch user: context deadline exceeded | still matches: true

Telling Canceled from DeadlineExceeded is useful. The first usually means the caller went away, which is normal and not worth an error log. The second means something was too slow, which is.

WithCancelCause: say why

A plain cancellation only says "cancelled." Since Go 1.20 you can attach a reason, and read it back with context.Cause. Err() still returns the standard error, so existing checks keep working.

ctx, cancel := context.WithCancelCause(context.Background())
cancel(errors.New("user closed the tab"))
fmt.Println("Err:  ", ctx.Err())
fmt.Println("Cause:", context.Cause(ctx))

ctx2, cancel2 := context.WithTimeoutCause(context.Background(), 50*time.Millisecond,
	errors.New("payment provider too slow"))
defer cancel2()
<-ctx2.Done()
fmt.Println("Err:  ", ctx2.Err())
fmt.Println("Cause:", context.Cause(ctx2))
Err:   context canceled
Cause: user closed the tab
Err:   context deadline exceeded
Cause: payment provider too slow

A bare context deadline exceeded in a log tells you nothing about which of ten calls timed out. A cause turns it into payment provider too slow. If no cause is set, Cause(ctx) returns the same value as ctx.Err(), so it is safe to call everywhere.

WithValue: carry data down the call chain

It attaches a key and a value to a child. Anything derived from that child can read it. This is how a request ID or trace ID reaches code that was never given a parameter for it.

type ctxKey struct{} // unexported type: no other package can collide with it

func WithRequestID(ctx context.Context, id string) context.Context {
	return context.WithValue(ctx, ctxKey{}, id)
}

func RequestID(ctx context.Context) (string, bool) {
	id, ok := ctx.Value(ctxKey{}).(string)
	return id, ok
}

ctx := WithRequestID(context.Background(), "req-42")
child, cancel := context.WithCancel(ctx) // values survive derivation
defer cancel()
id, ok := RequestID(child)
fmt.Println(id, ok)
_, ok = RequestID(context.Background())
fmt.Println("on a fresh context:", ok)
req-42 true
on a fresh context: false

The details that matter:

WithoutCancel: work that must outlive the request

A server's request context is cancelled when the client disconnects, and also when the handler returns. If the handler starts a goroutine that should finish after the response, say writing an audit record, that goroutine inherits a context that is about to die.

WithoutCancel (Go 1.21) returns a copy of a context that keeps the values but is never cancelled by its parent:

In this test, audit waits 100 ms to finish its work, or gives up early if its context is done. I start one with the request context and one with a detached copy, then cancel the request:

req, cancel := context.WithCancel(context.WithValue(context.Background(), ctxKey{}, "v"))
go audit(req, "with request ctx   ")
go audit(context.WithoutCancel(req), "with WithoutCancel")
cancel() // client went away
with request ctx    abandoned: context canceled
with WithoutCancel finished, err = <nil>
value still visible through WithoutCancel: v

It also drops the deadline, so a detached context has no limit at all. Give it its own: context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second). Detached work with no timeout is how you get a goroutine that never ends.

AfterFunc: run something when a context ends

context.AfterFunc(ctx, f) (Go 1.21) runs f in its own goroutine once ctx is done. It returns a stop function that cancels the registration if you no longer need it.

ctx, cancel := context.WithCancel(context.Background())
context.AfterFunc(ctx, func() { fmt.Println("cleanup ran") })
cancel()

ctx2, cancel2 := context.WithCancel(context.Background())
stop := context.AfterFunc(ctx2, func() { fmt.Println("should not print") })
fmt.Println("stopped before cancel:", stop())
cancel2()
cleanup ran
stopped before cancel: true

The classic use is a call that does not take a context. A blocking conn.Read cannot watch Done(), but AfterFunc(ctx, func() { conn.Close() }) makes cancellation close the connection, which makes the read return.

NotifyContext: cancel on Ctrl-C

In os/signal, NotifyContext (Go 1.16) gives you a context that is cancelled when the process receives one of the signals you name. It is the usual top of main for a service that must shut down cleanly:

ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
fmt.Println("working...")
<-ctx.Done()
fmt.Println("shutting down:", ctx.Err())
working...
shutting down: context canceled

I sent the process a SIGTERM from a goroutine to trigger that. Everything derived from this context, your server, your workers, your database calls, then stops together when Kubernetes or you ask the process to exit.

where a context goes

The standard library already accepts one almost everywhere that waits:

The HTTP pair is the clearest to see. I started a test server whose handler waits five seconds, then made a client call with a 200 ms timeout:

// server
select {
case <-time.After(5 * time.Second):
	fmt.Fprint(w, "slow answer")
case <-r.Context().Done():
	seen <- "handler saw: " + r.Context().Err().Error()
}

// client
ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
defer cancel()
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, srv.URL, nil)
_, err := http.DefaultClient.Do(req)
client error: Get "http://127.0.0.1:56167": context deadline exceeded
client gave up after 200ms
handler saw: context canceled

The client gave up at 200 ms, and the server's handler found out and could stop. That is the whole point: a decision made at one end travels through the call chain to the other.

Cancellation travelling from a client to a database call Four boxes left to right. The client gives up. The net/http server cancels the request context. Your handler passes the context to database/sql. database/sql stops waiting and returns the context error. client gives up net/http cancels r.Context() your handler passes ctx down database/sql stops waiting, returns ctx.Err() the chain only works if every layer passes the same ctx down
Whether the database server also stops the query is up to the driver. Your code stops waiting either way.

your half of the contract

This is the part that bites. A context does not stop anything. It announces that work should stop, and the code doing the work has to listen. A function that takes a ctx and never looks at it is not cancellable, however many contexts you wrap around it. I measured the difference with a 100 ms timeout:

func rude(ctx context.Context) { // takes ctx but never looks at it
	time.Sleep(time.Second)
}

func polite(ctx context.Context) error {
	for i := 0; ; i++ {
		if err := ctx.Err(); err != nil {
			return err
		}
		time.Sleep(10 * time.Millisecond) // one slice of work
		if i == 1000 {
			return nil
		}
	}
}
rude returned after 1s (ctx expired at 100ms)
polite returned after 110ms err: context deadline exceeded

Two ways to listen, and you need both:

And pass the context on. Every call you make that does I/O should receive the ctx you were given. That is what keeps the chain in the diagram connected.

the rules

These come straight from the package documentation, and they exist so that code from different authors composes:

the mistakes I keep seeing

the version to remember

  1. A context is how you ask work to stop: a cancel signal, an optional deadline and a few values, passed as the first argument.
  2. Contexts form a tree. Cancel flows down, never up, and a child can shorten a deadline but not extend it.
  3. WithCancel, WithTimeout and WithDeadline stop work. WithValue carries data. WithCancelCause and the ...Cause variants say why.
  4. WithoutCancel detaches work from the request. AfterFunc runs cleanup. NotifyContext ties the tree to Ctrl-C and SIGTERM.
  5. It is cooperative: always defer cancel(), pass ctx down, and check ctx.Done() wherever your code waits or loops.

The first post covers why waiting is cheap in Go, and What a goroutine actually is covers the scheduler under it. Context is the third piece: how you stop the work.