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
- Go cannot kill a goroutine from outside. The only way to stop one is to ask it, and
contextis the standard way to ask. - 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.
- Contexts form a tree. Cancelling one cancels everything derived from it, and never anything above it.
- 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:
- Cancellation: "stop, nobody wants this any more."
- A deadline: "stop anyway if it takes longer than this."
- Request-scoped values: "this is request 42, from this user," visible to every function on the way down without adding a parameter to each.
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
}
Done()returns a channel that is closed when the work should stop. A closed channel unblocks every receiver at once, which is why one context can cancel many goroutines, and whyselecton it works.Err()isniluntilDoneis closed. After that it says why:context.Canceledorcontext.DeadlineExceeded.Deadline()reports when it will expire, if it has a deadline.Value(key)looks up a value attached to the context or one of its ancestors.
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.
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.
| Function | Since | Use it when |
|---|---|---|
Background() | 1.7 | you are at the top: main, init, tests, or work you start yourself |
TODO() | 1.7 | you need a context and do not have one yet. Same behavior as Background, but searchable |
WithCancel | 1.7 | you decide when to stop |
WithTimeout | 1.7 | stop after a duration |
WithDeadline | 1.7 | stop at a clock time |
WithValue | 1.7 | carry a request-scoped value down |
signal.NotifyContext | 1.16 | stop when the process gets SIGINT or SIGTERM |
WithCancelCause, Cause | 1.20 | you want to record why it was cancelled |
WithTimeoutCause, WithDeadlineCause | 1.21 | you want a named reason when a timeout fires |
WithoutCancel | 1.21 | work must outlive the request, but keep its values |
AfterFunc | 1.21 | run 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:
- Use your own key type. The documentation says a key should not be a string or another built-in type, so two packages cannot collide on
"user". An unexported struct type is the usual choice. - Wrap it in a function pair, as above, so callers never touch the key or do the type assertion.
- Lookup walks up the tree until it finds the key. It is cheap for a few values, and not a place to keep a lot of data.
- Values are invisible in a function signature. That is the cost. Use them only for data that crosses API boundaries with the request: request and trace IDs, the authenticated user. If a function needs a value to do its job, make it a normal parameter. A context is not a bag for optional arguments.
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:
http.NewRequestWithContextfor outgoing requests, andr.Context()for incoming onesdatabase/sql:QueryContext,ExecContext,BeginTxand their siblings(*net.Dialer).DialContextfor connectionsexec.CommandContext, which kills the process when the context ends
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.
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:
- At a point where you block, use
selectwithctx.Done()next to the thing you are waiting for. This is the pattern from the first post.select { case v := <-results: return v, nil case <-ctx.Done(): return zero, ctx.Err() } - Inside a long loop that does not block, check
ctx.Err()every so often, aspolitedoes. Check at the granularity of one unit of work. Too rarely and cancellation is slow, and too often costs more than the work.
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:
- Context is the first parameter, named
ctx:func Do(ctx context.Context, arg Arg) error. - Do not store a context in a struct. Pass it to each function that needs it. A context belongs to one call or one request, and a struct usually outlives both. The Go blog has a post on this, Contexts and structs.
- Never pass a
nilcontext. If you are not sure which one to use, passcontext.TODO(). - Always call the cancel function, usually with
defer. - Use values only for request-scoped data that crosses API boundaries.
- A context is safe to share across goroutines. Passing one to ten goroutines is normal.
the mistakes I keep seeing
- Starting a new
context.Background()in the middle of a call chain. It silently cuts the chain. Everything below it ignores the caller's cancellation and deadline. If you have actx, derive from it. - Using the request context for work that outlives the request. It dies when the handler returns. Use
WithoutCancel, and give the result its own timeout. - Adding a timeout at every layer. Decide where the user's patience ends, put one deadline there, and let it flow down. Inner timeouts are for carving a smaller budget out of it, such as 300 ms for the database inside a 2 s request. Since a child cannot outlive its parent, a larger inner timeout does nothing.
- Comparing errors with
==. Useerrors.Is(err, context.DeadlineExceeded), because the error is usually wrapped. - Treating every cancellation as a failure. A cancelled request is the client leaving. Logging it at error level fills your logs with noise.
- Putting application data in values. The moment a function cannot work without a value from the context, it should have been a parameter.
the version to remember
- A context is how you ask work to stop: a cancel signal, an optional deadline and a few values, passed as the first argument.
- Contexts form a tree. Cancel flows down, never up, and a child can shorten a deadline but not extend it.
WithCancel,WithTimeoutandWithDeadlinestop work.WithValuecarries data.WithCancelCauseand the...Causevariants say why.WithoutCanceldetaches work from the request.AfterFuncruns cleanup.NotifyContextties the tree to Ctrl-C and SIGTERM.- It is cooperative: always
defer cancel(), passctxdown, and checkctx.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.