Context cancellation causes and callbacks
suggest changeThe original context API tells you only two things about a canceled context: ctx.Err() is either context.Canceled or context.DeadlineExceeded. It doesn't say who canceled it or why. It also has no way to run code when a context is canceled, other than a goroutine waiting on ctx.Done(), and no way to keep a context's values while dropping its cancellation.
Newer Go versions fill those gaps:
context.WithCancelCauseandcontext.Cause(Go 1.20) attach a reason to cancellationcontext.WithTimeoutCauseandcontext.WithDeadlineCause(Go 1.21) do the same for timeoutscontext.AfterFunc(Go 1.21) runs a callback when a context is canceledcontext.WithoutCancel(Go 1.21) keeps the values but not the cancellationsignal.NotifyContext(Go 1.26) records which signal canceled the contextt.Context()(Go 1.24) gives each test a context that is canceled when the test ends
This article assumes you know the basics from Context and Writing cancellable functions.
WithCancelCause and context.Cause
context.WithCancelCause works like context.WithCancel, but its cancel function takes an error. context.Cause(ctx) returns that error:
package main
import (
"context"
"errors"
"fmt"
)
var errQuotaExceeded = errors.New("quota exceeded")
func main() {
ctx, cancel := context.WithCancelCause(context.Background())
child, cancelChild := context.WithCancel(ctx)
defer cancelChild()
fmt.Println("before:", ctx.Err(), context.Cause(ctx))
cancel(errQuotaExceeded)
cancel(errors.New("ignored: already canceled"))
fmt.Println("err: ", ctx.Err())
fmt.Println("cause: ", context.Cause(ctx))
fmt.Println("child: ", child.Err(), "/", context.Cause(child))
fmt.Println("is quota:", errors.Is(context.Cause(child), errQuotaExceeded))
// cancel(nil) records context.Canceled as the cause
ctx2, cancel2 := context.WithCancelCause(context.Background())
cancel2(nil)
fmt.Println("nil cause:", context.Cause(ctx2))
// Cause works on any context; without a cause it returns ctx.Err()
ctx3, cancel3 := context.WithCancel(context.Background())
cancel3()
fmt.Println("plain:", context.Cause(ctx3))
}
before: <nil> <nil>
err: context canceled
cause: quota exceeded
child: context canceled / quota exceeded
is quota: true
nil cause: context canceled
plain: context canceled
The rules:
ctx.Err()doesn't change. It's stillcontext.Canceled, so existing code that checkserrors.Is(err, context.Canceled)keeps working.- Only the first cancel counts. Later calls, with any cause, do nothing.
- Children inherit the cause.
context.Cause(child)walks up to the context that was actually canceled. cancel(nil)sets the cause tocontext.Canceled.context.Causeworks on every context. If there's no cause it returnsctx.Err(), and before cancellation it returnsnil. So you can call it everywhere you'd callctx.Err().
Return the cause, not just Err()
A cause only helps if it reaches the code that handles the error. A cancellable function should return context.Cause(ctx) instead of ctx.Err():
package main
import (
"context"
"errors"
"fmt"
"time"
)
type ShutdownError struct {
Reason string
}
func (e *ShutdownError) Error() string { return "shutting down: " + e.Reason }
func processJobs(ctx context.Context, jobs []string) error {
for i, job := range jobs {
select {
case <-ctx.Done():
// return the cause, not ctx.Err(), so the caller learns why
return fmt.Errorf("stopped before job %d (%s): %w", i, job, context.Cause(ctx))
case <-time.After(20 * time.Millisecond):
fmt.Println("done:", job)
}
}
return nil
}
func main() {
ctx, cancel := context.WithCancelCause(context.Background())
go func() {
time.Sleep(50 * time.Millisecond)
cancel(&ShutdownError{Reason: "config reload"})
}()
err := processJobs(ctx, []string{"a", "b", "c", "d"})
fmt.Println(err)
var se *ShutdownError
if errors.As(err, &se) {
fmt.Println("reason:", se.Reason)
}
fmt.Println("is Canceled:", errors.Is(err, context.Canceled))
}
done: a
done: b
stopped before job 2 (c): shutting down: config reload
reason: config reload
is Canceled: false
A cause can be any error, including your own type, and errors.As finds it.
Note the last line, though. The returned error no longer matches context.Canceled, which can break callers that check for it (for example, to avoid logging a canceled request as a failure). If that matters, wrap both errors. fmt.Errorf accepts more than one %w:
return fmt.Errorf("query: %w: %w", ctx.Err(), context.Cause(ctx))
The next example uses this form.
WithTimeoutCause and WithDeadlineCause
context.WithTimeoutCause(parent, d, cause) and context.WithDeadlineCause(parent, t, cause) set the cause used when the timer fires. This turns a generic "context deadline exceeded" into something you can act on:
package main
import (
"context"
"errors"
"fmt"
"time"
)
var errSlowDB = errors.New("database query took longer than 50ms")
func query(ctx context.Context, d time.Duration) error {
select {
case <-time.After(d):
return nil
case <-ctx.Done():
return fmt.Errorf("query: %w: %w", ctx.Err(), context.Cause(ctx))
}
}
func main() {
// the timer fires: Cause is our error, Err is DeadlineExceeded
ctx, cancel := context.WithTimeoutCause(context.Background(), 50*time.Millisecond, errSlowDB)
defer cancel()
err := query(ctx, time.Second)
fmt.Println(err)
fmt.Println("deadline:", errors.Is(err, context.DeadlineExceeded), "slow db:", errors.Is(err, errSlowDB))
// cancel() called first: the cause is plain context.Canceled
ctx2, cancel2 := context.WithTimeoutCause(context.Background(), time.Second, errSlowDB)
cancel2()
fmt.Println("after cancel():", context.Cause(ctx2))
// a parent's cause wins over the child's timeout cause
parent, cancelParent := context.WithCancelCause(context.Background())
child, cancelChild := context.WithTimeoutCause(parent, time.Second, errSlowDB)
defer cancelChild()
cancelParent(errors.New("user logged out"))
fmt.Println("child cause:", context.Cause(child))
}
query: context deadline exceeded: database query took longer than 50ms
deadline: true slow db: true
after cancel(): context canceled
child cause: user logged out
Two things are easy to get wrong:
- The cause is used only when the deadline passes. The returned cancel function is a plain
context.CancelFuncwith no argument, and calling it recordscontext.Canceled. That's what you want: the usualdefer cancel()after the work is done isn't a timeout. - If you need both a timeout cause and your own cancel reason, nest them:
WithCancelCauseon the outside,WithTimeoutCauseinside (or the other way around). Whichever fires first sets the cause.
AfterFunc: run code when a context is canceled
context.AfterFunc(ctx, f) calls f in a new goroutine once ctx is done. It returns a stop function that removes the callback.
The main use is cancelling operations that don't accept a context. net.Conn.Read, sync.Cond.Wait and many third-party APIs block with no way to pass a ctx. With AfterFunc you can unblock them when the context is canceled. For a network connection you set a read deadline in the past:
package main
import (
"bufio"
"context"
"errors"
"fmt"
"net"
"time"
)
// readLine reads one line from conn. conn.Read doesn't take a context,
// so when ctx is canceled we set a read deadline in the past, which
// makes a blocked Read return immediately.
func readLine(ctx context.Context, conn net.Conn, br *bufio.Reader) (string, error) {
stop := context.AfterFunc(ctx, func() {
conn.SetReadDeadline(time.Now())
})
defer stop()
line, err := br.ReadString('\n')
if err != nil && ctx.Err() != nil {
// report why we gave up, not "i/o timeout"
return line, context.Cause(ctx)
}
return line, err
}
func main() {
client, server := net.Pipe()
defer client.Close()
go func() {
server.Write([]byte("hello\n"))
server.Write([]byte("partial")) // then the peer stalls
}()
ctx, cancel := context.WithTimeoutCause(context.Background(),
100*time.Millisecond, errors.New("peer stopped sending"))
defer cancel()
br := bufio.NewReader(client)
line, err := readLine(ctx, client, br)
fmt.Printf("%q %v\n", line, err)
line, err = readLine(ctx, client, br) // blocks until the timeout
fmt.Printf("%q %v\n", line, err)
}
"hello\n" <nil>
"partial" peer stopped sending
Before AfterFunc you'd write this with a goroutine that selects on ctx.Done() and a done channel. That's more code, and if you forget the done channel the goroutine leaks until the context is canceled, which for context.Background() is never. AfterFunc doesn't start a goroutine until the context is actually canceled, and defer stop() cleans up the registration when the read finishes normally.
The WebSockets article uses the same trick to send a proper close frame when a request context ends.
How stop works
package main
import (
"context"
"fmt"
"time"
)
func main() {
ctx, cancel := context.WithCancel(context.Background())
stop1 := context.AfterFunc(ctx, func() { fmt.Println("callback 1 runs") })
stop2 := context.AfterFunc(ctx, func() { fmt.Println("callback 2 runs") })
fmt.Println("stop2() stopped it:", stop2())
fmt.Println("stop2() again:", stop2())
cancel()
time.Sleep(10 * time.Millisecond) // callbacks run in their own goroutines
fmt.Println("stop1() after cancel:", stop1())
// registering on an already-canceled context runs f right away
done := make(chan struct{})
context.AfterFunc(ctx, func() {
fmt.Println("late callback runs")
close(done)
})
<-done
}
stop2() stopped it: true
stop2() again: false
callback 1 runs
stop1() after cancel: false
late callback runs
stop()returnstrueif it preventedffrom running.- It returns
falseiffhas already started (or was stopped before). It does not wait forfto finish. If you need to know thatfcompleted, makefsignal it, e.g. by closing a channel. - You can register any number of callbacks on one context. They're independent.
- If the context is already done,
fstarts right away, in its own goroutine.
Because f runs on another goroutine, anything it touches must be safe for concurrent use. SetReadDeadline and Close on a net.Conn are; most of your own types aren't without a mutex.
In readLine, if stop() returns false the deadline has already been set, and later reads on that connection fail immediately. That's fine here because the context is canceled anyway. A function that reuses the connection after a cancellation would need to reset the deadline with conn.SetReadDeadline(time.Time{}).
Canceling a context when another one is done
A context has one parent, but sometimes work should stop when either of two contexts ends. A typical case is a request that should stop when the client goes away or when the server shuts down. AfterFunc combined with WithCancelCause does that and keeps the reason:
package main
import (
"context"
"errors"
"fmt"
)
// withStop returns a context that is canceled when ctx or stopCtx is done.
// It keeps the values and deadline of ctx.
func withStop(ctx, stopCtx context.Context) (context.Context, context.CancelFunc) {
ctx, cancel := context.WithCancelCause(ctx)
stop := context.AfterFunc(stopCtx, func() {
cancel(context.Cause(stopCtx))
})
return ctx, func() {
stop()
cancel(context.Canceled)
}
}
func main() {
serverCtx, shutdown := context.WithCancelCause(context.Background())
reqCtx := context.Background() // stands in for r.Context()
ctx, cancel := withStop(reqCtx, serverCtx)
defer cancel()
shutdown(errors.New("server shutting down"))
<-ctx.Done()
fmt.Println("request ctx:", context.Cause(ctx))
}
request ctx: server shutting down
The returned cancel function calls stop() first. Without it, every request would leave a callback registered on the long-lived serverCtx until shutdown, which is a memory leak.
WithoutCancel: keep the values, drop the cancellation
When an HTTP handler returns, r.Context() is canceled. Work you start in the background with that context is cut off mid-way. That's a common bug with audit logs, cache warming, metrics and emails sent after a response.
You can't just use context.Background() instead, because you'd lose the values stored in the request context: request ID, trace span, authenticated user. context.WithoutCancel(ctx) returns a context that has the parent's values but is never canceled and has no deadline:
package main
import (
"context"
"fmt"
"time"
)
type ctxKey string
func main() {
reqCtx, cancel := context.WithTimeout(context.Background(), time.Second)
reqCtx = context.WithValue(reqCtx, ctxKey("request-id"), "r-42")
bg := context.WithoutCancel(reqCtx)
cancel() // the request is over
fmt.Println("request err:", reqCtx.Err())
fmt.Println("bg err: ", bg.Err())
fmt.Println("bg done: ", bg.Done() == nil)
_, hasDeadline := bg.Deadline()
fmt.Println("bg deadline:", hasDeadline)
fmt.Println("bg value: ", bg.Value(ctxKey("request-id")))
fmt.Println("bg cause: ", context.Cause(bg))
}
request err: context canceled
bg err: <nil>
bg done: true
bg deadline: false
bg value: r-42
bg cause: <nil>
Done() returns nil, a channel that never becomes ready. That's exactly the danger: work running under a WithoutCancel context can hang forever. Always add your own timeout. Here is the bug and the fix in a real handler:
package main
import (
"context"
"fmt"
"io"
"net/http"
"net/http/httptest"
"sync"
"time"
)
type ctxKey string
var wg sync.WaitGroup
// saveAuditLog pretends to write to a slow store.
func saveAuditLog(ctx context.Context, label string) {
select {
case <-time.After(50 * time.Millisecond):
fmt.Printf("%s: saved audit log for %v\n", label, ctx.Value(ctxKey("user")))
case <-ctx.Done():
fmt.Printf("%s: audit log lost: %v\n", label, context.Cause(ctx))
}
}
func handler(w http.ResponseWriter, r *http.Request) {
ctx := context.WithValue(r.Context(), ctxKey("user"), "alice")
fmt.Fprintln(w, "order placed")
// wrong: r.Context() is canceled as soon as the handler returns
wg.Go(func() { saveAuditLog(ctx, "with request ctx") })
// right: keep the values, drop the cancellation, add our own limit
bg, cancel := context.WithTimeout(context.WithoutCancel(ctx), 2*time.Second)
wg.Go(func() {
defer cancel()
saveAuditLog(bg, "WithoutCancel")
})
}
func main() {
srv := httptest.NewServer(http.HandlerFunc(handler))
defer srv.Close()
resp, err := http.Get(srv.URL)
if err != nil {
panic(err)
}
body, _ := io.ReadAll(resp.Body)
resp.Body.Close()
fmt.Print("response: ", string(body))
wg.Wait()
}
with request ctx: audit log lost: context canceled
response: order placed
WithoutCancel: saved audit log for alice
wg.Go is the Go 1.25 shorthand for wg.Add(1) plus go func() { defer wg.Done(); ... }(). A real server would also wait for these goroutines during graceful shutdown, so they aren't killed when the process exits.
Use WithoutCancel for short follow-up work that belongs to the request. Long-running jobs should go to a proper worker queue with its own lifetime instead.
Which signal stopped the program
signal.NotifyContext returns a context that is canceled when the process receives one of the given signals. It's the standard way to start a graceful shutdown (see OS Signals for the channel-based API). Since Go 1.26 the context is canceled with a cause that names the signal:
package main
import (
"context"
"errors"
"fmt"
"os"
"os/signal"
"syscall"
"time"
)
func main() {
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
// simulate `kill <pid>` arriving while we work
go func() {
time.Sleep(50 * time.Millisecond)
syscall.Kill(os.Getpid(), syscall.SIGTERM)
}()
<-ctx.Done()
fmt.Println("err: ", ctx.Err())
fmt.Println("cause:", context.Cause(ctx))
fmt.Println("is Canceled:", errors.Is(context.Cause(ctx), context.Canceled))
}
Output on Linux (syscall.Kill doesn't exist on Windows):
err: context canceled
cause: terminated signal received
is Canceled: true
The cause is an unexported error type. Its message is the signal's name plus "signal received", and it matches context.Canceled with errors.Is. You get a readable log line, but not the os.Signal value itself. If you need to act differently on SIGINT and SIGTERM, use signal.Notify with a channel.
The cause is more useful when the shutdown can also be triggered from inside the program. Put a WithCancelCause context under NotifyContext and let goroutines report fatal errors through it. After <-ctx.Done(), one context.Cause call tells you what happened:
package main
import (
"context"
"errors"
"fmt"
"os"
"os/signal"
"syscall"
"time"
)
func worker(ctx context.Context, fail context.CancelCauseFunc) {
time.Sleep(200 * time.Millisecond)
fail(errors.New("worker: lost connection to queue"))
}
func main() {
root, fail := context.WithCancelCause(context.Background())
defer fail(nil)
ctx, stop := signal.NotifyContext(root, os.Interrupt, syscall.SIGTERM)
defer stop()
go worker(ctx, fail)
<-ctx.Done()
cause := context.Cause(ctx)
fmt.Println("shutting down:", cause)
// a signal is a normal shutdown, anything else is a failure
var code int
switch {
case errors.Is(cause, context.Canceled):
code = 0
default:
code = 1
}
fmt.Println("exit code:", code)
}
When the worker fails first:
shutting down: worker: lost connection to queue
exit code: 1
When the process gets SIGINT (Ctrl+C) first:
shutting down: interrupt signal received
exit code: 0
t.Context() in tests
Since Go 1.24, t.Context() (and b.Context() for benchmarks) returns a context that is canceled just before the functions registered with t.Cleanup run. Pass it to code under test instead of context.Background(), and goroutines started by the test stop when the test ends:
package poller
import (
"context"
"time"
)
// Poll calls f every interval until ctx is canceled.
// It returns a channel that is closed when polling has stopped.
func Poll(ctx context.Context, interval time.Duration, f func()) <-chan struct{} {
done := make(chan struct{})
go func() {
defer close(done)
t := time.NewTicker(interval)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
f()
}
}
}()
return done
}
package poller
import (
"context"
"sync/atomic"
"testing"
"time"
)
func TestPoll(t *testing.T) {
var calls atomic.Int32
done := Poll(t.Context(), 5*time.Millisecond, func() { calls.Add(1) })
t.Cleanup(func() {
// t.Context() is already canceled when cleanups run
t.Logf("ctx: %v", context.Cause(t.Context()))
<-done // wait for the goroutine so it doesn't outlive the test
t.Log("poller stopped")
})
time.Sleep(30 * time.Millisecond)
if calls.Load() == 0 {
t.Fatal("f was never called")
}
}
$ go test -v
=== RUN TestPoll
poller_test.go:16: ctx: context canceled
poller_test.go:18: poller stopped
--- PASS: TestPoll (0.03s)
PASS
Because the context is canceled before cleanups run, a cleanup can wait for background work to finish, as above. Don't use t.Context() inside a cleanup to do new work: it's already canceled. Use context.WithoutCancel(t.Context()) if a cleanup needs the context's values.
Summary
| You want to | Use |
|---|---|
| Say why you canceled | context.WithCancelCause, cancel(err) |
| Say why a timeout matters | context.WithTimeoutCause, context.WithDeadlineCause |
| Find out why a context ended | context.Cause(ctx) (works on any context) |
| Unblock a call that doesn't take a context | context.AfterFunc + defer stop() |
| Cancel when either of two contexts ends | WithCancelCause + AfterFunc |
| Keep values after the request ends | context.WithoutCancel, plus your own WithTimeout |
| Know which signal triggered shutdown | context.Cause on a signal.NotifyContext context |
| Stop goroutines when a test ends | t.Context() |
And the mistakes to avoid:
- returning
context.Cause(ctx)alone when callers checkerrors.Is(err, context.Canceled): wrap both with two%w - expecting the timeout cause after calling the cancel function: it's used only when the deadline passes
- forgetting
stop()forAfterFuncon a long-lived context: the callback stays registered - assuming
stop()waits for the callback: it doesn't - running background work under
WithoutCancelwith no timeout: it can block forever
Context is a tree of values explains how cancellation (and now its cause) flows from parent to children.