context: Cancellation, Deadlines, Values
"At Google, we developed a context package that makes it easy to pass request-scoped values, cancellation signals, and deadlines across API boundaries to all the goroutines involved in handling a request." — Sameer Ajmani, "Go Concurrency Patterns: Context", The Go Blog, 29 July 2014
Summary: context.Context is how one Go request tells all the work done on its behalf to stop: it carries a cancellation signal, an optional deadline and a few request-scoped values down the call chain, across goroutines, into HTTP, gRPC and database calls, and (as a timeout) across the network to other services. Focus: the four methods (Done, Err, Deadline, Value), Background/TODO, the derivation tree (WithCancel, WithTimeout, WithDeadline, WithCancelCause/Cause, WithTimeoutCause, WithoutCancel, AfterFunc), defer cancel() and vet's lostcancel, cooperative cancellation, r.Context() and client disconnect, NewRequestWithContext, http.TimeoutHandler, deadline propagation and gRPC deadlines, QueryContext and pgx, typed value keys, slog context handlers, errgroup.WithContext, t.Context(), leaks, and how to classify context.Canceled vs context.DeadlineExceeded for logs and retries. Learning goal: Thread one ctx from the edge of a service to every blocking call, give each hop a budget that fits inside its caller's, stop work the moment nobody is waiting for it, and read a context canceled or context deadline exceeded in a log and know exactly who gave up and whether a retry makes sense.
This page owns the context package and how the standard library and the common drivers use it. It does not re-teach its neighbours: select and the for-select loop are in select, channels and goroutine basics in Goroutines & Channels, cancelling worker pools and pipelines as a design in Worker Pools, Pipelines & errgroup, signal.NotifyContext and graceful shutdown in OS Processes, Signals & Graceful Shutdown, timers and time.After in time.Time, Timers & math/rand, the HTTP server and client themselves in net/http, middleware chaining in Middlewares, database/sql and pgx in database/sql & pgx, gRPC itself in gRPC & Protobuf in Go, and error wrapping in Errors, Panic, Recover & Defer. The system-level choice of timeout values and retry policy is in Timeouts, Retries & Jitter and the latency budget idea in Latency Budgets & Tail Latency.
Facts below were checked against the Go 1.27 standard-library source on go.dev (context, net/http, database/sql, log/slog, testing; pkg.go.dev returns 403 to scripted fetches), the Go 1.7, 1.20, 1.21, 1.23 and 1.24 release notes, the Go blog posts on context and on contexts in structs, the Go Code Review Comments wiki, grpc.io's deadline and cancellation guides, the grpc-go, pgx and golang.org/x/sync sources, and the Laravel 13 Context documentation. Snippets declare go 1.24 (they use t.Context(), b.Loop and slog.DiscardHandler, which are 1.24) and pin golang.org/x/sync v0.19.0, the last release whose go.mod still says 1.24. They were compiled, vetted and tested with -race on Go 1.27.4 (macOS); the numbers in the lab are from that run.
Page map
| If you are looking for | Go to |
|---|---|
| The tables you can memorise in one minute | Everything in one minute |
| Why a request needs a stop signal at all | Why it exists |
| Where the package comes from, version by version | Where it comes from |
| A before/after handler | Go |
Done, Err, Deadline, Value | The Context interface |
context.Background vs context.TODO | Background and TODO |
WithCancel, the cancel func, defer cancel, lostcancel | WithCancel |
WithTimeout, WithDeadline, the shorter deadline wins | Timeouts and deadlines |
WithCancelCause, context.Cause, WithTimeoutCause | Cancellation causes |
| Why cancel does not kill anything | Cooperative cancellation |
First parameter ctx, no structs, no nil | Propagation rules |
r.Context() and client disconnect | Server side |
http.NewRequestWithContext and Client.Timeout | Client side |
http.TimeoutHandler and server timeouts | TimeoutHandler |
| Budgets across services, gRPC deadline | Deadline propagation |
QueryContext, BeginTx, pgx | Database calls |
| Request id, principal, trace span in ctx | Context values |
slog and InfoContext | slog context |
errgroup.WithContext | errgroup |
context.AfterFunc | AfterFunc |
WithoutCancel, fire-and-forget after the response | WithoutCancel |
| Goroutine leaks and timer leaks | Leaks |
t.Context() in tests | Testing |
| Implementing your own Context | Custom Contexts |
| Data structures, linked list lookup, exact error texts | Mechanics |
| The common bugs and their fixes | Solving the classic problems |
| Retry and log classification | Classify errors |
| What to use when | Choosing |
| Monolith to distributed system | In architecture |
| Reproduce it on your machine | Lab |
Laravel request lifecycle and the Context facade | For PHP/Laravel developers |
Everything in one minute
The four methods. Every context, however it was built, answers these four questions. Each row is unpacked in the concept catalogue.
| Method | Returns | Plain words | Before cancel | After cancel |
|---|---|---|---|---|
Done() | <-chan struct{} | "Has anyone told me to stop?" as a channel you can select on | Open (or nil if it can never be canceled) | Closed, forever |
Err() | error | "Why did I stop?" | nil | context.Canceled or context.DeadlineExceeded |
Deadline() | time.Time, bool | "When must I be finished?" | Same as after | ok == false when no deadline |
Value(key) | any | "What request-scoped data travels with me?" | Same as after | Values survive cancellation |
The constructors. All take a parent and return a child; cancellation flows from parent to child only.
| Constructor | Since | Adds | Returns a cancel func? | Typical use |
|---|---|---|---|---|
context.Background() | 1.7 | Nothing: root | No | main, tests, top of a server |
context.TODO() | 1.7 | Nothing: placeholder root | No | "I have not threaded ctx here yet" |
WithCancel(parent) | 1.7 | A stop button | CancelFunc | Stop siblings, stop a loop |
WithTimeout(parent, d) | 1.7 | Deadline now+d | CancelFunc | Bound one call |
WithDeadline(parent, t) | 1.7 | Deadline t | CancelFunc | Inherit an absolute deadline |
WithValue(parent, k, v) | 1.7 | One key/value | No | Request id, principal, trace span |
WithCancelCause(parent) | 1.20 | Stop button with a reason | CancelCauseFunc | Say why in logs |
WithDeadlineCause, WithTimeoutCause | 1.21 | Deadline with a reason | CancelFunc | Name the budget that fired |
WithoutCancel(parent) | 1.21 | Values only, no Done | No | Work that must outlive the request |
AfterFunc(ctx, f) | 1.21 | Callback on cancel | stop func() bool | Wake up an API without ctx |
The errors you will read in logs.
| Text | Variable | Who caused it | Retry? |
|---|---|---|---|
context canceled | context.Canceled | Someone called cancel: client disconnect, sibling failed, shutdown, handler returned | No |
context deadline exceeded | context.DeadlineExceeded | A deadline passed, yours or one you inherited | Only if a per-attempt timeout fired and the overall budget remains |
Get "https://api.example.test/x": context deadline exceeded | wraps DeadlineExceeded | http.Client with a ctx deadline | As above |
... (Client.Timeout exceeded while awaiting headers) | net.Error with Timeout() == true | http.Client.Timeout | As above |
rpc error: code = DeadlineExceeded desc = context deadline exceeded | gRPC codes.DeadlineExceeded (4) | Client deadline in grpc-go | As above |
timeout: context deadline exceeded | pgx errTimeout wrapping it | pgx query whose ctx expired | As above |
http: Handler timeout | http.ErrHandlerTimeout | Write after http.TimeoutHandler fired | No |
Why it exists
A Go server handles each request in its own goroutine, and that goroutine usually starts more: one per downstream call, one per database query in a fan-out, one for a cache warm-up. When the browser closes the tab, when the load balancer gives up after 30 seconds, or when one of three parallel calls fails, nobody is waiting for the result any more, and every goroutine still working on it is spending CPU, a database connection and a slot in someone else's queue for nothing. Under load that waste is what turns a slow dependency into an outage (see Cascading Failures).
Go has no way to kill a goroutine from the outside, and that is deliberate: a goroutine killed half-way through holds locks and half-written state. So the stop signal has to be something the work itself looks at. context is that signal, standardised so that every library (net/http, database/sql, gRPC, pgx, AWS SDK) looks at the same one.
| Without a shared stop signal | With context.Context |
|---|---|
| Each library invents its own timeout knob | One ctx parameter everywhere |
| Work continues after the caller left | Work stops at the next check |
| Timeouts add up: 5 s + 5 s + 5 s behind a 3 s gateway | Each hop gets what is left of the caller's budget |
| Goroutines blocked on sends leak | Every blocking point has an exit |
| Request id passed as an extra argument through 12 layers | Carried once as a request-scoped value |
| Simpler signatures | One more parameter on every function that blocks |
An everyday picture. A restaurant order ticket. The waiter writes the table number and "must be out by 20:15" on the ticket (values and deadline) and hangs it in the kitchen; the chef splits it into tickets for the grill and the salad station (child contexts). If the guests leave, the waiter pulls the ticket and every station sees it is gone (cancel flows down). A station cannot cancel the whole order by itself, and nobody snatches the pan out of a cook's hands: the cook glances at the rail between steps and stops (cooperative cancellation).
Three common misunderstandings, up front
- "Cancelling a context stops the goroutine." It closes a channel. Code that never looks at
ctx.Done()or never passesctxto a blocking call runs to the end. - "
context.WithTimeout(ctx, 5*time.Second)gives the call five seconds." It gives it at most five seconds: if the parent's deadline is sooner, the parent wins. - "Context is a convenient bag for passing things down." Values are for request-scoped data that crosses API boundaries (request id, auth principal, trace span), never for a logger, a database handle or configuration.
Where it comes from
The package was written at Google for RPC servers and published as golang.org/x/net/context; Sameer Ajmani introduced it on the Go blog on 29 July 2014 with the rule that a Context is passed "as the first argument to every function on the call path between incoming and outgoing requests". Go 1.7 (August 2016) moved it into the standard library as context, added Request.Context and Request.WithContext to net/http, DialContext to net, and the vet check -lostcancel, which the release notes describe as detecting "failure to call the cancellation function returned by the WithCancel, WithTimeout, and WithDeadline functions". Go 1.8 added the ...Context methods of database/sql.
The second wave came much later. Go 1.20 added WithCancelCause and Cause. Go 1.21 added WithoutCancel, WithDeadlineCause, WithTimeoutCause and AfterFunc. Go 1.23 added httptest.NewRequestWithContext and made unreferenced timers collectable even without Stop, which removed the classic time.After-in-a-loop memory leak. Go 1.24 added T.Context and B.Context, a context "canceled after the test completes and before test cleanup functions run". The February 2021 blog post "Contexts and structs" (Jean Barkhuysen, Matt T. Proud) explains why net/http stored a context in http.Request and why your code should not copy that choice.
Go
Before
A handler that works on a quiet day: it sleeps instead of waiting on anything, builds its own root context for the downstream call and has no deadline. When the browser goes away, the downstream is still called; when the downstream hangs, so does the handler.
// Package before shows a handler that compiles and works on a quiet day but
// ignores cancellation: it starts from context.Background deep in the call
// chain, sleeps instead of waiting on ctx, and calls downstream without a
// deadline. Nothing here is broken code; it is the design that fails under load.
package before
import (
"context"
"io"
"net/http"
"time"
)
// Inventory calls a downstream stock service.
type Inventory struct {
BaseURL string
Client *http.Client
}
// Reserve builds its own root context: the caller's deadline and the client's
// disconnect never reach the outgoing request.
func (inv *Inventory) Reserve(sku string) (string, error) {
req, err := http.NewRequestWithContext(context.Background(), http.MethodPost,
inv.BaseURL+"/reserve?sku="+sku, nil)
if err != nil {
return "", err
}
resp, err := inv.Client.Do(req) // no deadline: waits as long as the server does
if err != nil {
return "", err
}
defer resp.Body.Close()
b, err := io.ReadAll(resp.Body)
return string(b), err
}
// Handler keeps working after the browser has gone away.
func Handler(inv *Inventory) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
time.Sleep(200 * time.Millisecond) // simulated work that cannot be interrupted
id, err := inv.Reserve(r.URL.Query().Get("sku"))
if err != nil {
http.Error(w, err.Error(), http.StatusBadGateway)
return
}
io.WriteString(w, id)
}
}After
The same handler with r.Context() threaded through: the wait listens to ctx.Done(), the downstream call gets a child with its own budget, and the error is classified before it is reported.
// Package after is the same handler with the request context threaded through:
// the client's disconnect and the per-call budget reach every blocking call.
package after
import (
"context"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"time"
)
// Inventory calls a downstream stock service.
type Inventory struct {
BaseURL string
Client *http.Client
Timeout time.Duration // per-call budget; the caller's deadline still wins if sooner
}
// Reserve takes ctx first and derives a shorter child for the outgoing call.
func (inv *Inventory) Reserve(ctx context.Context, sku string) (string, error) {
ctx, cancel := context.WithTimeout(ctx, inv.Timeout)
defer cancel() // releases the timer as soon as Reserve returns
req, err := http.NewRequestWithContext(ctx, http.MethodPost,
inv.BaseURL+"/reserve?sku="+sku, nil)
if err != nil {
return "", err
}
resp, err := inv.Client.Do(req)
if err != nil {
return "", fmt.Errorf("reserve %s: %w", sku, err)
}
defer resp.Body.Close()
b, err := io.ReadAll(resp.Body) // the body read is also bound to ctx
return string(b), err
}
// sleepCtx waits for d or until ctx is done, whichever comes first.
func sleepCtx(ctx context.Context, d time.Duration) error {
t := time.NewTimer(d)
defer t.Stop()
select {
case <-t.C:
return nil
case <-ctx.Done():
return context.Cause(ctx)
}
}
// Handler stops as soon as the client disconnects or the budget runs out.
func Handler(inv *Inventory, log *slog.Logger) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context() // canceled on client disconnect or when ServeHTTP returns
if err := sleepCtx(ctx, 200*time.Millisecond); err != nil {
log.InfoContext(ctx, "client went away", "err", err)
return
}
id, err := inv.Reserve(ctx, r.URL.Query().Get("sku"))
switch {
case errors.Is(err, context.Canceled):
log.InfoContext(ctx, "canceled by caller", "err", err) // not an outage
return
case errors.Is(err, context.DeadlineExceeded):
http.Error(w, "inventory timed out", http.StatusGatewayTimeout)
return
case err != nil:
http.Error(w, "inventory failed", http.StatusBadGateway)
return
}
io.WriteString(w, id)
}
}The test proves both properties: a slow downstream is cut at 50 ms with a 504, and a request whose client is already gone never reaches the downstream.
package after
import (
"context"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"sync/atomic"
"testing"
"time"
)
func TestHandlerTimesOutSlowInventory(t *testing.T) {
slow := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
select {
case <-time.After(2 * time.Second):
io.WriteString(w, "late")
case <-r.Context().Done(): // the downstream sees our cancellation too
}
}))
defer slow.Close()
inv := &Inventory{BaseURL: slow.URL, Client: slow.Client(), Timeout: 50 * time.Millisecond}
h := Handler(inv, slog.New(slog.DiscardHandler))
rec := httptest.NewRecorder()
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/?sku=A1", nil)
start := time.Now()
h(rec, req)
if rec.Code != http.StatusGatewayTimeout {
t.Fatalf("code = %d, want 504", rec.Code)
}
if d := time.Since(start); d > time.Second {
t.Fatalf("handler took %v; the timeout did not propagate", d)
}
}
func TestHandlerStopsWhenClientCancels(t *testing.T) {
var calls atomic.Int32
down := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls.Add(1)
io.WriteString(w, "r-1")
}))
defer down.Close()
inv := &Inventory{BaseURL: down.URL, Client: down.Client(), Timeout: time.Second}
h := Handler(inv, slog.New(slog.DiscardHandler))
ctx, cancel := context.WithCancel(t.Context())
cancel() // the client is already gone
rec := httptest.NewRecorder()
h(rec, httptest.NewRequestWithContext(ctx, http.MethodGet, "/?sku=A1", nil))
if n := calls.Load(); n != 0 {
t.Fatalf("downstream called %d times after the client left", n)
}
}The Go angle
Go made cancellation an explicit parameter rather than thread-local magic. The cost is one argument on every blocking function; the benefit is that you can see from a signature whether a call can be stopped, static analysis can check it (lostcancel, contextcheck), and the same value works in goroutines, in select, over HTTP and over gRPC. The standard library and the ecosystem honour it uniformly: net.Dialer.DialContext, http.NewRequestWithContext, sql.DB.QueryContext, exec.CommandContext, signal.NotifyContext, grpc-go stubs, pgx, the AWS SDK for Go v2 and Watermill all take ctx first.
The concept catalogue
The Context interface Must-know
In plain words: A context is a read-only handle with four questions you can ask it: should I stop (Done), why (Err), by when (Deadline), and what do I know about this request (Value). You cannot cancel a context through the interface; only whoever created it holds the cancel function.
Common misunderstanding: "ctx.Done() blocks until cancellation." It returns a channel immediately; receiving from that channel is what blocks. And for context.Background() it returns nil, a channel that blocks forever, which is correct: Background is never canceled.
Definition: type Context interface { Deadline() (deadline time.Time, ok bool); Done() <-chan struct{}; Err() error; Value(key any) any }. The docs promise that successive calls to Done return the same channel, that Err returns nil until Done is closed and then the same non-nil error forever, and that "Contexts are safe for simultaneous use by multiple goroutines". There is no Cancel method on purpose; the blog explains that "the function receiving a cancellation signal is usually not the one that sends the signal".
goroutine A (owner) goroutine B (worker)
1 ctx, cancel := WithCancel(parent)
2 go work(ctx) select { case <-ctx.Done(): ... } // waits
3 cancel() ── closes ctx.Done() ─────────▶ receive succeeds
4 ctx.Err() == context.Canceled
5 cancel() (no-op: first call wins) return ctx.Err()Real scenario: a search page that queries three shards and cancels the two slow ones when the first answers; a checkout handler that stops reserving stock when the user closes the tab; a batch export that stops at the next row when the operator presses Ctrl-C; a streaming endpoint that stops writing when the client disconnects.
| Method | Cost | Safe from many goroutines | Can block |
|---|---|---|---|
Done() | First call allocates the channel lazily, then an atomic load | Yes | No (receiving from it can) |
Err() | One atomic load on cancelCtx ("~5x faster than a mutex" per the source) | Yes | No |
Deadline() | Field read | Yes | No |
Value(k) | Walk up the parent chain | Yes | No |
Fix / how to use it: select on Done() where you wait, call Err() where you loop, and return ctx.Err() (or context.Cause(ctx)) so callers can classify. The derivation tree snippet below exercises all four methods.
// Package tree shows the derivation tree: cancellation flows from a parent to
// every descendant, never upwards, and the first cancellation wins.
package tree
import (
"context"
"errors"
"time"
)
// ErrShutdown is a cause a server records when it stops accepting work.
var ErrShutdown = errors.New("server shutting down")
// ErrBudget is a cause attached to a deadline so logs say which budget fired.
var ErrBudget = errors.New("checkout budget of 300ms exhausted")
// Snapshot reports what a context says about itself right now.
type Snapshot struct {
Err error
Cause error
HasDeadline bool
}
// Inspect reads Err, Cause and Deadline without blocking.
func Inspect(ctx context.Context) Snapshot {
_, ok := ctx.Deadline()
return Snapshot{Err: ctx.Err(), Cause: context.Cause(ctx), HasDeadline: ok}
}
// Build returns a small tree rooted at parent:
//
// parent ── request (WithCancelCause) ── db (WithTimeoutCause)
// └─ cache (WithTimeout, shorter)
func Build(parent context.Context, dbBudget, cacheBudget time.Duration) (
request, db, cache context.Context, cancelRequest context.CancelCauseFunc, stop func(),
) {
request, cancelRequest = context.WithCancelCause(parent)
db, cancelDB := context.WithTimeoutCause(request, dbBudget, ErrBudget)
cache, cancelCache := context.WithTimeout(request, cacheBudget)
stop = func() {
cancelCache()
cancelDB()
cancelRequest(nil)
}
return request, db, cache, cancelRequest, stop
}Background and TODO Must-know
In plain words: Both are empty roots: never canceled, no deadline, no values. Background says "this is the top of a real tree"; TODO says "a ctx should come from my caller, but the plumbing is not there yet".
Common misunderstanding: "context.Background() is the safe default inside a function that has no ctx." Inside a request path it is the bug: it detaches the work from the client's disconnect and the caller's deadline. The Code Review Comments wiki puts it plainly: "The default case is to pass a Context; only use context.Background() directly if you have a good reason why the alternative is a mistake."
Definition: Background "is typically used by the main function, initialization, and tests, and as the top-level Context for incoming requests". TODO is for when "it's unclear which Context to use or it is not yet available". They print as context.Background and context.TODO, which is how you spot them in a %v of a context. Since Go 1.21 two calls to Background() may compare equal; comparing contexts was never defined behaviour.
1 main() ctx := context.Background() -- correct: real root
2 http.Server BaseContext() -> Background() -- correct: server root
3 handler ctx := r.Context() -- correct: inherit
4 repo.Find(ctx,...) db.QueryContext(context.Background()) -- BUG: cuts the tree
5 legacy code ctx := context.TODO() -- honest marker, grep for it laterReal scenario: a main that builds a root context with signal.NotifyContext(context.Background(), ...); a cron job that starts each run from Background with a timeout; a library function migrated to take ctx whose old wrapper passes TODO; a test written before Go 1.24 that used Background instead of t.Context().
| Situation | Use | Why |
|---|---|---|
main, CLI entry point | signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) | Ctrl-C and SIGTERM cancel the whole program |
| Inside a handler | r.Context() | Disconnect and server shutdown reach your code |
| Inside a test (1.24+) | t.Context() | Canceled when the test ends |
| Old API without ctx you have not refactored | context.TODO() | Searchable debt |
| Work that must outlive the request | context.WithoutCancel(r.Context()) | Keeps the request id; see WithoutCancel |
Fix / how to use it: grep for context.Background() outside main, tests and constructors; every hit in a request path is either a bug or a WithoutCancel in disguise. Linters such as contextcheck (in golangci-lint) flag functions that call a ctx-taking function with a fresh Background.
WithCancel, the cancel func and lostcancel Must-know
In plain words: WithCancel gives you a child context and a function that cancels it. Call that function when the work is done or must stop, and always call it eventually, usually with defer cancel() on the next line.
Common misunderstanding: "If the work finished normally, I do not need to cancel." You do: until cancel is called (or the parent is), the parent keeps a reference to the child in its children map and, for a timeout, a timer stays armed. The package docs: "Failing to call the CancelFunc leaks the child and its children until the parent is canceled." With a Background parent that is forever.
Definition: WithCancel(parent) (ctx Context, cancel CancelFunc). The child's Done is closed "when the returned cancel function is called or when the parent context's Done channel is closed, whichever happens first". A CancelFunc "does not wait for the work to stop", may be called from many goroutines, and after the first call "subsequent calls to a CancelFunc do nothing". go vet's lostcancel analyzer reports a cancel func that is discarded or not called on every path.
1 ctx, cancel := context.WithCancel(parent) parent.children = {ctx}
2 defer cancel()
3 go producer(ctx); go producer(ctx)
4 v := <-results first answer wins
5 return v -> deferred cancel() runs ctx.Done() closed, parent.children = {}
6 producers see Done, exitReal scenario: hedged requests (send to two replicas, take the first, cancel the other); "first result wins" across caches; stopping a watcher goroutine when its owner closes; a consumer loop that must stop when the broker connection drops.
| Mistake | What vet says (Go 1.27.4, real output) |
|---|---|
ctx, _ := context.WithTimeout(parent, time.Second) | the cancel function returned by context.WithTimeout should be called, not discarded, to avoid a context leak |
ctx, cancel := context.WithCancel(parent) then an early return before defer cancel() | the cancel function is not used on all paths (possible context leak) |
| The early return itself | this return statement may be reached without using the cancel var defined on line 15 |
Fix / how to use it: put defer cancel() on the line right after the With* call; if the context must outlive the function (a goroutine owns it), hand the cancel func to whoever owns the lifetime and document it. The leak snippet shows the "first result wins" shape with defer cancel() stopping the losers.
WithTimeout and WithDeadline Must-know
In plain words: WithTimeout(ctx, 2*time.Second) is "cancel this automatically in two seconds"; WithDeadline(ctx, t) is the same with a clock time. Either way, a child can only shorten the time it has, never extend it.
Common misunderstanding: "A 10-second timeout inside a handler that has 1 second left gives the database 10 seconds." WithDeadline returns a context whose deadline is "no later than d. If the parent's deadline is already earlier than d, WithDeadline(parent, d) is semantically equivalent to parent." The shorter deadline always wins.
Definition: WithTimeout(parent, d) is exactly WithDeadline(parent, time.Now().Add(d)). The returned context is a timerCtx holding a time.AfterFunc timer that cancels it with DeadlineExceeded. If the deadline is already in the past it is canceled at once. Its Done closes on the deadline, on cancel, or when the parent's closes, "whichever happens first". Deadline() returns (t, true); context.DeadlineExceeded has Timeout() == true, so it also satisfies net.Error-style timeout checks.
t=0ms handler ctx deadline = t+1000ms (from the gateway)
t=0ms dbCtx, cancel := WithTimeout(ctx, 10*time.Second) -> deadline still t+1000ms
t=0ms cacheCtx, c2 := WithTimeout(ctx, 50*time.Millisecond) -> deadline t+50ms
t=50ms cacheCtx.Err() == DeadlineExceeded; ctx and dbCtx unaffected
t=1000ms ctx, dbCtx canceled with DeadlineExceeded; QueryContext returnsReal scenario: a cache lookup limited to 50 ms so a slow Redis falls back to the database; an outgoing payment-provider call limited to 3 s inside a 10 s checkout; a cron job that must finish within its 5-minute slot; a health check that answers in 1 s or fails.
| Layer | Knob | Default | Relation to ctx |
|---|---|---|---|
| Your code | WithTimeout per call | None | The budget you choose |
http.Client | Timeout | 0 (none) | Separate timer; whichever fires first |
http.Server | ReadTimeout, WriteTimeout, IdleTimeout, ReadHeaderTimeout | 0 (none) | Connection-level; not visible through ctx.Deadline() |
| gRPC-Go client | ctx deadline | None ("gRPC does not set a deadline") | Sent as grpc-timeout |
| PostgreSQL | statement_timeout | 0 (disabled) | Server-side backstop; independent of ctx |
| pgx | ctx passed to Query | Connection deadline on cancel | Breaks the connection (see Database calls) |
Fix / how to use it: derive a timeout per outgoing call, not per handler only; keep the timeouts nested (handler budget > call budget > per-attempt budget); and check ctx.Deadline() before starting work you know takes longer than what is left. The tree test shows that a child asking for an hour inside a 20 ms parent gets 20 ms.
package tree
import (
"context"
"errors"
"testing"
"time"
)
func TestCancelFlowsDownWithCause(t *testing.T) {
request, db, cache, cancelRequest, stop := Build(t.Context(), time.Hour, time.Hour)
defer stop()
cancelRequest(ErrShutdown)
for name, ctx := range map[string]context.Context{"request": request, "db": db, "cache": cache} {
<-ctx.Done()
s := Inspect(ctx)
if !errors.Is(s.Err, context.Canceled) {
t.Errorf("%s: Err = %v, want context.Canceled", name, s.Err)
}
if !errors.Is(s.Cause, ErrShutdown) {
t.Errorf("%s: Cause = %v, want ErrShutdown", name, s.Cause)
}
}
}
func TestChildDeadlineDoesNotTouchParent(t *testing.T) {
request, db, _, _, stop := Build(t.Context(), 10*time.Millisecond, time.Hour)
defer stop()
<-db.Done()
if s := Inspect(db); !errors.Is(s.Err, context.DeadlineExceeded) || !errors.Is(s.Cause, ErrBudget) {
t.Fatalf("db: %+v, want DeadlineExceeded with ErrBudget cause", s)
}
if err := request.Err(); err != nil {
t.Fatalf("parent was canceled by a child: %v", err)
}
}
func TestShorterParentDeadlineWins(t *testing.T) {
parent, cancel := context.WithTimeout(t.Context(), 20*time.Millisecond)
defer cancel()
child, cancelChild := context.WithTimeout(parent, time.Hour) // asks for more, gets less
defer cancelChild()
pd, _ := parent.Deadline()
cd, _ := child.Deadline()
if !cd.Equal(pd) {
t.Fatalf("child deadline %v, want parent's %v", cd, pd)
}
}
func TestFirstCancellationWins(t *testing.T) {
ctx, cancel := context.WithCancelCause(t.Context())
cancel(ErrShutdown)
cancel(errors.New("second call is ignored"))
if got := context.Cause(ctx); !errors.Is(got, ErrShutdown) {
t.Fatalf("Cause = %v", got)
}
}
func TestBackgroundIsNeverCanceled(t *testing.T) {
s := Inspect(context.Background())
if s.Err != nil || s.Cause != nil || s.HasDeadline || context.Background().Done() != nil {
t.Fatalf("Background: %+v", s)
}
}Cancellation causes: WithCancelCause, Cause, WithTimeoutCause Important
In plain words: ctx.Err() only ever says "canceled" or "deadline exceeded". A cause is the real reason, attached when you cancel ("payment provider down", "server shutting down", "checkout budget of 300ms exhausted"), and readable with context.Cause(ctx) on that context or any descendant.
Common misunderstanding: "If I cancel with a cause, ctx.Err() returns my error." It does not: Err still returns context.Canceled (or DeadlineExceeded), so all existing errors.Is checks keep working; only Cause returns your error. Another one: the cancel func of WithTimeoutCause "does not set the cause"; the cause is only used when the timer fires.
Definition: WithCancelCause(parent) (ctx, cancel CancelCauseFunc); cancel(err) records err, cancel(nil) sets the cause to Canceled. Cause(c) "returns a non-nil error explaining why c was canceled. The first cancellation of c or one of its parents sets the cause." If no cause was given, Cause(c) equals c.Err(); before cancellation it is nil. WithDeadlineCause and WithTimeoutCause attach a cause to the deadline. errgroup.WithContext uses WithCancelCause internally, so Cause of a group's ctx is the first error.
1 ctx, cancel := context.WithCancelCause(parent)
2 child, c2 := context.WithTimeout(ctx, time.Hour)
3 cancel(errors.New("payment provider down"))
4 child.Err() -> context canceled
5 context.Cause(child) -> payment provider down (inherited)
6 cancel(errors.New("x")) -> ignored: first cancellation winsReal scenario: a shutdown that cancels in-flight work with ErrShutdown so logs do not show a thousand mysterious "context canceled" lines; an errgroup whose siblings log which sibling failed; a deadline named per budget (ErrDBBudget, ErrCheckoutBudget) so a dashboard can group timeouts by layer.
| You want | Call | Err() afterwards | Cause() afterwards |
|---|---|---|---|
| Plain cancel | cancel() from WithCancel | Canceled | Canceled |
| Cancel with a reason | cancel(err) from WithCancelCause | Canceled | err |
| Deadline with a reason | WithTimeoutCause(ctx, d, err), timer fires | DeadlineExceeded | err |
| Deadline, cancelled early | WithTimeoutCause, you call cancel | Canceled | Canceled |
| Detached | WithoutCancel(ctx) | nil forever | nil forever |
Fix / how to use it: log context.Cause(ctx) next to err, return ctx.Err() (or wrap it) to callers so classification by errors.Is stays stable. The tree tests above assert each row of this table.
Cooperative cancellation Must-know
In plain words: Cancel is a request. It closes a channel; it does not interrupt the CPU. Your loop stops only at a point where it checks ctx.Err(), selects on ctx.Done(), or calls something that does.
Common misunderstanding: "My worker got the canceled context, so it stopped." If the loop body is for _, row := range rows { process(row) } and process never looks at ctx, the worker finishes all rows after the user left. Likewise time.Sleep cannot be interrupted; a select with a timer and ctx.Done() can.
Definition: a function cooperates when every potentially long step is one of: a call that takes ctx (I/O, RPC, SQL), a select that includes case <-ctx.Done():, or a cheap if err := ctx.Err(); err != nil { return err } between CPU-bound iterations. grpc.io says the same for servers: "the server application is responsible for stopping any activity it has spawned to service the RPC".
caller worker loop (checks between items)
1 go Process(ctx, items) item 0 ... done
2 item 1 ... (cancel arrives during item 1)
3 cancel() item 1 finishes: no preemption
4 ctx.Err() != nil -> return 2, context.Canceled
ProcessIgnoring: items 2..4 still run, returns 5Real scenario: an image-resize batch that keeps resizing after the upload was aborted; a report generator that keeps scanning a million rows after a dashboard tab closed; a retry loop that sleeps through shutdown; a long-poll handler that waits on a channel without ctx.Done().
| Blocking point | Cancellable by ctx? | How |
|---|---|---|
time.Sleep(d) | No | select on time.NewTimer(d).C and ctx.Done() |
| Channel send/receive | Only in select | Add case <-ctx.Done(): |
sync.Mutex.Lock, WaitGroup.Wait | No | Keep critical sections short; use a channel semaphore if you must wait |
net.Conn.Read | Not directly | context.AfterFunc + SetReadDeadline (see AfterFunc) |
http.Client.Do | Yes | Request built with NewRequestWithContext |
sql.DB.QueryContext | Yes | Driver cancels or breaks the connection |
exec.CommandContext | Yes | Kills the process (see OS Processes) |
| Pure CPU loop | No | Check ctx.Err() every N iterations |
Fix / how to use it: the cooperative snippet shows the three shapes: a check between items, a ticker loop that selects on Done, and a generic Send that never blocks forever. select itself is taught in select.
// Package cooperative shows that cancellation is a request, not a kill:
// a loop stops only where it checks ctx.
package cooperative
import (
"context"
"time"
)
// Item is one unit of a batch job.
type Item struct{ ID int }
// ProcessIgnoring never looks at ctx inside the loop: canceling the caller
// changes nothing until the whole batch has finished.
func ProcessIgnoring(ctx context.Context, items []Item, work func(Item)) int {
n := 0
for _, it := range items {
work(it)
n++
}
return n
}
// Process checks ctx between items and returns how many were done plus the
// reason it stopped. Cheap check: ctx.Err() is an atomic load.
func Process(ctx context.Context, items []Item, work func(Item)) (int, error) {
for i, it := range items {
if err := ctx.Err(); err != nil {
return i, err
}
work(it)
}
return len(items), nil
}
// Poll repeats fn every interval until ctx is done. It uses one Ticker for the
// whole loop instead of time.After per iteration.
func Poll(ctx context.Context, interval time.Duration, fn func(context.Context) bool) error {
tick := time.NewTicker(interval)
defer tick.Stop()
for {
if fn(ctx) {
return nil
}
select {
case <-ctx.Done():
return ctx.Err()
case <-tick.C:
}
}
}
// Send delivers v unless ctx ends first, so a producer never blocks forever on
// a consumer that has gone away.
func Send[T any](ctx context.Context, out chan<- T, v T) error {
select {
case out <- v:
return nil
case <-ctx.Done():
return ctx.Err()
}
}package cooperative
import (
"context"
"errors"
"testing"
"time"
)
func items(n int) []Item {
s := make([]Item, n)
for i := range s {
s[i] = Item{ID: i}
}
return s
}
func TestIgnoringRunsToTheEnd(t *testing.T) {
ctx, cancel := context.WithCancel(t.Context())
n := ProcessIgnoring(ctx, items(5), func(it Item) {
if it.ID == 1 {
cancel()
}
})
if n != 5 {
t.Fatalf("n = %d, want 5 (cancel was ignored)", n)
}
}
func TestProcessStopsAtNextCheck(t *testing.T) {
ctx, cancel := context.WithCancel(t.Context())
n, err := Process(ctx, items(5), func(it Item) {
if it.ID == 1 {
cancel()
}
})
if n != 2 || !errors.Is(err, context.Canceled) {
t.Fatalf("n=%d err=%v, want 2 and context.Canceled", n, err)
}
}
func TestPollReturnsDeadlineExceeded(t *testing.T) {
ctx, cancel := context.WithTimeout(t.Context(), 30*time.Millisecond)
defer cancel()
err := Poll(ctx, 5*time.Millisecond, func(context.Context) bool { return false })
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("err = %v", err)
}
if err.Error() != "context deadline exceeded" {
t.Fatalf("text = %q", err.Error())
}
}
func TestSendDoesNotBlockForever(t *testing.T) {
ctx, cancel := context.WithTimeout(t.Context(), 10*time.Millisecond)
defer cancel()
out := make(chan int) // nobody reads
if err := Send(ctx, out, 1); !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("err = %v", err)
}
}Propagation rules: first parameter ctx, no structs, no nil Must-know
In plain words: Every function that blocks or calls something that blocks takes ctx context.Context as its first parameter and passes it on. You do not keep a context in a struct field, and you never pass nil.
Common misunderstanding: "Storing ctx in my service struct saves typing." It ties the lifetime of a long-lived object to one request, or worse, mixes two scopes. The Go blog: "when you store the context in a struct, you obscure lifetime to the callers, or worse intermingle two scopes together in unpredictable ways." The exception is a short-lived, request-scoped object (like http.Request itself), and even net/http chose it only for backward compatibility.
Definition: the package doc lists the rules: "Do not store Contexts inside a struct type; instead, pass a Context explicitly to each function that needs it... The Context should be the first parameter, typically named ctx", "Do not pass a nil Context, even if a function permits it. Pass context.TODO if you are unsure", and "Use context Values only for request-scoped data". The Code Review Comments add "Don't create custom Context types or use interfaces other than Context in function signatures." Constructors panic on a nil parent: cannot create context from nil parent.
1 HTTP edge func (h *Handler) ServeHTTP(w, r) ctx := r.Context()
2 service func (s *Checkout) Place(ctx, cart) passes ctx
3 repository func (r *Orders) Insert(ctx, order) db.ExecContext(ctx, ...)
4 client func (p *Payments) Charge(ctx, amount) NewRequestWithContext(ctx, ...)
5 goroutine go s.audit(ctx, ...) same ctx or WithoutCancel(ctx)
one tree from 1 to 5; no layer invents a new rootReal scenario: a repository with Find(id) that hides a Background() inside; a worker struct with ctx set in New that never notices the request ended; a middleware that passes nil because "the callee does not use it yet" and later panics; a method set that must match io.Reader and therefore cannot take ctx (wrap with AfterFunc or a deadline instead).
| Rule | Source | Checked by |
|---|---|---|
ctx first, named ctx | context package doc, CodeReviewComments | revive context-as-argument (golangci-lint) |
| No ctx in structs | package doc, "Contexts and structs" blog | containedctx linter |
| Never nil | package doc | Runtime panic in With* constructors |
| Always call cancel | package doc, Go 1.7 notes | go vet lostcancel |
| Do not start a new root in a request path | CodeReviewComments | contextcheck linter |
| Typed, unexported keys | WithValue doc | staticcheck SA1029 for built-in key types |
Fix / how to use it: if you must keep an API without ctx for compatibility, add a FooContext(ctx, ...) twin (as database/sql did) and make the old one call it with context.Background(); the blog recommends that over a struct field.
Server side: r.Context and client disconnect Must-know
In plain words: In a net/http handler, r.Context() is canceled when the client goes away or when your handler returns. Pass it down and your database query stops when the user closes the tab.
Common misunderstanding: "Client disconnect is detected immediately." For HTTP/1.1 the server notices when its background read on the connection hits EOF; for HTTP/2 a RST_STREAM cancels one stream. A client behind a proxy that keeps the upstream connection open may never look disconnected. And the context is also canceled when ServeHTTP returns, so goroutines you started with r.Context() die with the response.
Definition: Request.Context doc: "For incoming server requests, the context is canceled when the client's connection closes, the request is canceled (with HTTP/2), or when the ServeHTTP method returns." The root of every request context is Server.BaseContext ("If BaseContext is nil, the default is context.Background()"), refined per connection by ConnContext. The context carries http.ServerContextKey and http.LocalAddrContextKey values.
browser net/http server handler goroutine
1 GET /report ───────────▶ conn, ctx from BaseContext ctx := r.Context()
2 QueryContext(ctx, slowSQL)
3 closes tab ── FIN ───────▶ background read sees EOF
4 cancel(request ctx) ──────▶ ctx.Done() closed
5 driver cancels query, returns
6 err: context canceledReal scenario: an expensive search aborted by a user typing the next character (typeahead); a report export the user gave up on; a long-poll endpoint whose client navigated away; a mobile client that lost signal mid-upload.
| Server feature | Effect on r.Context() |
|---|---|
| Client closes connection (HTTP/1.1) | Canceled when the server's background read sees it |
RST_STREAM (HTTP/2) | That stream's context canceled |
| Handler returns | Canceled (do not use it in goroutines that outlive the handler) |
Server.Shutdown(ctx) | Does not cancel active requests; waits for them. Use BaseContext + your own cancel to signal them |
ReadTimeout/WriteTimeout | Close the connection; not exposed as a ctx deadline |
http.TimeoutHandler | Replaces ctx with a WithTimeout child |
Fix / how to use it: pass r.Context() into every call, treat context.Canceled after a disconnect as INFO not ERROR, and if the work must finish anyway (an audit write), detach explicitly with WithoutCancel. The propagation test below proves that a client giving up after 50 ms cancels the server-side context.
Client side: NewRequestWithContext Must-know
In plain words: Build outgoing requests with http.NewRequestWithContext(ctx, ...). Then the dial, the TLS handshake, waiting for headers and reading the body all stop when ctx does.
Common misunderstanding: "Setting http.Client.Timeout is enough." It is a separate timer per request that knows nothing about the caller's budget or the client's disconnect. And http.NewRequest (no ctx) silently uses context.Background().
Definition: "For an outgoing client request, the context controls the entire lifetime of a request and its response: obtaining a connection, sending the request, and reading the response headers and body." Errors come back wrapped in *url.Error, so errors.Is(err, context.DeadlineExceeded) works on Get "https://...": context deadline exceeded. Client.Timeout errors carry (Client.Timeout exceeded while awaiting headers) and are net.Error with Timeout() == true.
1 ctx, cancel := WithTimeout(r.Context(), 300ms); defer cancel()
2 req := NewRequestWithContext(ctx, POST, url, body)
3 resp, err := client.Do(req) dial + TLS + write + wait headers: all under ctx
4 io.ReadAll(resp.Body) body read: still under ctx
5 return cancel() releases the timer
at 300ms anywhere in 3-4: err wraps context.DeadlineExceeded, connection discardedReal scenario: a payment API call bounded inside a checkout; a webhook delivery worker that must stop on shutdown; an S3 upload through the AWS SDK for Go v2 (whose every operation takes ctx first); a fan-out to three pricing partners.
| Setting | Scope | Knows the caller's deadline? |
|---|---|---|
NewRequestWithContext(ctx, ...) | One request, including body read | Yes |
http.Client.Timeout | One request, including body read | No |
Transport.DialContext (via net.Dialer.Timeout) | Connect only | Through ctx, yes |
Transport.TLSHandshakeTimeout | TLS only (default 10 s in DefaultTransport) | No |
Transport.ResponseHeaderTimeout | Waiting for headers | No |
Fix / how to use it: always NewRequestWithContext; keep Client.Timeout as a generous backstop only; read and close the body under the same ctx. The After snippet does exactly this.
http.TimeoutHandler and server timeouts Important
In plain words: http.TimeoutHandler(h, 2*time.Second, "too slow") answers 503 with your message if h has not finished in two seconds and cancels the context it gave h.
Common misunderstanding: "TimeoutHandler stops my handler." It cannot; it stops waiting for it, answers on its behalf, and makes later writes fail with http.ErrHandlerTimeout (http: Handler timeout). Your handler still has to watch ctx.Done() to stop working. It also does not support Flusher or Hijacker, so it is wrong for streaming and WebSockets.
Definition: "if a call runs for longer than its time limit, the handler responds with a 503 Service Unavailable error and the given message in its body... After such a timeout, writes by h to its ResponseWriter will return ErrHandlerTimeout." It buffers the inner handler's output, so nothing reaches the client until the handler finishes.
t=0 TimeoutHandler: ctx, cancel := WithTimeout(r.Context(), 20ms); go h(w', r.WithContext(ctx))
t=20ms timer fires: cancel(); write 503 "request budget exhausted"
t=20ms h sees ctx.Done(), tries to write: io.WriteString -> http: Handler timeoutReal scenario: a JSON API with a hard 2 s SLO; a legacy handler you cannot easily change; a gateway that must answer with its own body rather than a dropped connection.
| Tool | Answers the client | Cancels handler ctx | Works with streaming |
|---|---|---|---|
http.TimeoutHandler | 503 + message | Yes | No (Flusher unsupported) |
Your own WithTimeout middleware | Whatever your handler writes (504 in the snippet) | Yes | Yes |
Server.WriteTimeout | Connection closed, no response | No | Cuts long streams |
http.ResponseController.SetWriteDeadline (1.20) | Per-request write deadline | No | Yes |
Fix / how to use it: prefer a middleware that applies a WithTimeout budget and lets the handler map DeadlineExceeded to 504; use TimeoutHandler when you want a guaranteed answer from a handler you do not trust.
Deadline propagation across services and gRPC deadlines Must-know
In plain words: When service A calls B with 1.2 s left, B should not take 5 s. Propagation means B learns how much time A has left and applies it to its own context, so every hop stops at the same moment.
Common misunderstanding: "Send the absolute deadline in a header." The two hosts' clocks differ; grpc.io: "Since a deadline is set point in time, propagating it as-is to a server can be problematic as the clocks on the two servers might not be synchronized. To address this gRPC converts the deadline to a timeout from which the already elapsed time is already deducted." Send a duration, not a timestamp.
Definition: gRPC carries the remaining time in the grpc-timeout request header (units H, M, S, m, u, n in grpc-go). In grpc-go, a client stub takes ctx and sends ctx.Deadline() as that header; the server stub gives your method a ctx with that deadline, and if you pass that ctx to the next client call the budget propagates automatically (grpc.io: enabled by default "in others it is enabled by default (e.g. Java and Go)"). "By default, gRPC does not set a deadline", so the first hop must. A passed deadline is codes.DeadlineExceeded (4) on the client, and the server cancels the call (CANCELLED, code 1). status.FromContextError maps the two context errors to those codes. Plain HTTP has no standard for this, so the snippet uses an X-Timeout-Ms header with the same rule.
1 client ctx deadline 2.0s ──── grpc-timeout: 2000m ────▶ gateway
2 gateway spends 0.3s; ctx.Deadline() left 1.7s ─ 1700m ─▶ orders
3 orders spends 0.5s; left 1.2s ─ 1200m ─▶ inventory
4 inventory still working at t=2.0s: ctx.Done() closed on every hop
5 client rpc error: code = DeadlineExceeded desc = context deadline exceeded
without propagation inventory would keep going with its own 5s defaultReal scenario: a mobile app with a 3 s budget calling a BFF that fans out to four services; a payment flow where the provider call must leave time to write the outcome; batch jobs that call internal APIs and should not be stuck behind interactive traffic budgets; a service mesh retrying on behalf of a client that already gave up.
| Transport | How the budget travels | Go API | Expired error |
|---|---|---|---|
| gRPC (grpc-go) | grpc-timeout header, automatic from ctx | Pass incoming ctx to outgoing stub | codes.DeadlineExceeded |
| HTTP (net/http) | Nothing standard; custom header | Outgoing + Middleware in the snippet | context.DeadlineExceeded wrapped in *url.Error |
| Messaging (RabbitMQ, Kafka) | Message TTL / expiration, or a deadline field in the envelope | Consumer derives ctx from it | Consumer drops or dead-letters |
| Database | statement_timeout, SET LOCAL per transaction | ctx + driver | SQLSTATE 57014 canceling statement due to statement timeout (PostgreSQL) |
Fix / how to use it: the first hop sets a deadline, every hop forwards what is left minus a small reserve, every hop caps an inbound budget by its own maximum, and nobody sends a request that cannot finish.
// Package propagation carries a deadline across an HTTP hop the way gRPC does
// with grpc-timeout: send the remaining budget as a duration (not a wall-clock
// time, so clock skew does not matter), and derive a context from it on the
// receiving side.
package propagation
import (
"context"
"net/http"
"strconv"
"time"
)
// Header carries the remaining budget in milliseconds.
const Header = "X-Timeout-Ms"
// reserve is kept back for the network and for writing our own response.
const reserve = 5 * time.Millisecond
// Outgoing builds a request whose context and header agree on the budget.
func Outgoing(ctx context.Context, method, url string) (*http.Request, error) {
req, err := http.NewRequestWithContext(ctx, method, url, nil)
if err != nil {
return nil, err
}
if dl, ok := ctx.Deadline(); ok {
left := time.Until(dl) - reserve
if left <= 0 {
return nil, context.DeadlineExceeded // do not send a request that cannot finish
}
req.Header.Set(Header, strconv.FormatInt(left.Milliseconds(), 10))
}
return req, nil
}
// Middleware applies an inbound budget, capped by max, to r.Context().
func Middleware(max time.Duration, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
budget := max
if ms, err := strconv.ParseInt(r.Header.Get(Header), 10, 64); err == nil && ms > 0 {
if d := time.Duration(ms) * time.Millisecond; d < budget {
budget = d
}
}
ctx, cancel := context.WithTimeout(r.Context(), budget)
defer cancel()
next.ServeHTTP(w, r.WithContext(ctx))
})
}
// Timeouts wraps h with http.TimeoutHandler, which answers 503 with msg once
// dt passes and makes later writes by h fail with http.ErrHandlerTimeout.
func Timeouts(h http.Handler, dt time.Duration) http.Handler {
return http.TimeoutHandler(h, dt, "request budget exhausted\n")
}package propagation
import (
"context"
"errors"
"io"
"net/http"
"net/http/httptest"
"strconv"
"testing"
"time"
)
func TestBudgetShrinksAcrossTheHop(t *testing.T) {
budgets := make(chan time.Duration, 1)
srv := httptest.NewServer(Middleware(10*time.Second, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
dl, _ := r.Context().Deadline()
budgets <- time.Until(dl)
})))
defer srv.Close()
ctx, cancel := context.WithTimeout(t.Context(), 300*time.Millisecond)
defer cancel()
req, err := Outgoing(ctx, http.MethodGet, srv.URL)
if err != nil {
t.Fatal(err)
}
ms, _ := strconv.Atoi(req.Header.Get(Header))
if ms <= 0 || ms > 300 {
t.Fatalf("header = %d ms", ms)
}
resp, err := srv.Client().Do(req)
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
got := <-budgets
if got <= 0 || got > 300*time.Millisecond {
t.Fatalf("server budget = %v, want (0, 300ms]", got)
}
}
func TestExpiredBudgetIsNotSent(t *testing.T) {
ctx, cancel := context.WithTimeout(t.Context(), time.Millisecond)
defer cancel()
time.Sleep(10 * time.Millisecond)
if _, err := Outgoing(ctx, http.MethodGet, "http://192.0.2.1/"); !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("err = %v", err)
}
}
func TestClientDisconnectCancelsServerContext(t *testing.T) {
canceled := make(chan error, 1)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
<-r.Context().Done()
canceled <- r.Context().Err()
}))
defer srv.Close()
ctx, cancel := context.WithTimeout(t.Context(), 50*time.Millisecond)
defer cancel()
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, srv.URL, nil)
_, err := srv.Client().Do(req)
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("client err = %v", err)
}
select {
case err := <-canceled:
if !errors.Is(err, context.Canceled) {
t.Fatalf("server saw %v, want context.Canceled", err)
}
case <-time.After(2 * time.Second):
t.Fatal("server context was not canceled after the client left")
}
}
func TestTimeoutHandlerAnswers503(t *testing.T) {
writeErr := make(chan error, 1)
h := Timeouts(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
<-r.Context().Done() // TimeoutHandler cancels the inner context
_, err := io.WriteString(w, "too late")
writeErr <- err
}), 20*time.Millisecond)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/", nil))
if rec.Code != http.StatusServiceUnavailable || rec.Body.String() != "request budget exhausted\n" {
t.Fatalf("code=%d body=%q", rec.Code, rec.Body.String())
}
if err := <-writeErr; !errors.Is(err, http.ErrHandlerTimeout) {
t.Fatalf("late write err = %v", err)
}
}Context in database calls: QueryContext, BeginTx, pgx Must-know
In plain words: Use the ...Context methods (QueryContext, QueryRowContext, ExecContext, BeginTx, PrepareContext, PingContext). When ctx ends, the call returns and the driver either asks the server to cancel the statement or abandons the connection.
Common misunderstanding: "Cancelling the ctx rolls back my committed transaction" or "cancelling stops the query on the server for free." database/sql rolls back an open transaction whose ctx is canceled ("If the context is canceled, the sql package will roll back the transaction. Tx.Commit will return an error if the context provided to BeginTx is canceled"), but what happens on the server depends on the driver. pgx v5's default BuildContextWatcherHandler is a DeadlineContextWatcherHandler that "handles canceled contexts by setting a deadline on a net.Conn", which breaks that connection; the optional CancelRequestContextWatcherHandler "handles canceled contexts by sending a cancel request to the server". Either way the pool loses or recycles a connection, so a storm of cancellations is also a storm of reconnects.
Definition: every database/sql method has a ctx twin; the plain ones call it with context.Background(). The ctx bounds waiting for a pool connection as well as the query. A driver that implements driver.QueryerContext/ExecerContext receives the ctx; pgx wraps context errors as timeout: context deadline exceeded (errTimeout, which unwraps to the context error).
Go (pgx) PostgreSQL backend pid 4242
1 QueryContext(ctx 500ms, slowSQL) ───────▶ executing
2 t=500ms ctx done
3 default: SetDeadline(now) on net.Conn (still executing until it notices the socket)
or CancelRequest handler: new conn ──────▶ CancelRequest(pid 4242, secret key)
4 ERROR 57014 canceling statement due to user request
5 returns timeout: context deadline exceeded; conn closed (default) or reusableReal scenario: a dashboard query that should die when the tab closes; a migration step with a hard time limit; a transaction that must roll back if the HTTP request is aborted half-way; a connection pool exhausted because canceled queries kept running server-side.
| Driver / layer | What ctx cancellation does | Server sees |
|---|---|---|
database/sql pool | Stops waiting for a free connection; rolls back an open Tx | Depends on driver |
| pgx v5 default | Sets a past deadline on the socket: connection unusable, closed | Disconnect; backend ends the query when it notices |
pgx v5 CancelRequestContextWatcherHandler | Sends a PostgreSQL CancelRequest on a new connection, deadline as fallback | ERROR: canceling statement due to user request (57014) |
lib/pq | Sends a CancelRequest | Same 57014 |
go-sql-driver/mysql | Closes the connection (no KILL QUERY) | Query may keep running until it notices |
PostgreSQL statement_timeout | Independent server-side limit | canceling statement due to statement timeout (57014) |
Fix / how to use it: pass ctx to every call, keep a server-side statement_timeout as a backstop for drivers that only drop the socket, and size the pool (see Connection Pooling) for reconnects after cancellations. The snippet uses a fake driver so the database/sql behaviour is testable without a server; driver internals are in database/sql & pgx.
// Package dbctx passes ctx into every database/sql call. With a real driver
// (pgx stdlib, lib/pq, go-sql-driver/mysql) the same calls cancel the query on
// the server or break the connection; the test uses a fake driver so the
// database/sql behaviour can be observed without a server.
package dbctx
import (
"context"
"database/sql"
"time"
)
// Orders reads the orders table.
type Orders struct {
DB *sql.DB
Timeout time.Duration
}
// Count runs one query bounded by the caller's ctx and r.Timeout.
func (r *Orders) Count(ctx context.Context, customerID int64) (int64, error) {
ctx, cancel := context.WithTimeout(ctx, r.Timeout)
defer cancel()
var n int64
err := r.DB.QueryRowContext(ctx,
`SELECT count(*) FROM orders WHERE customer_id = $1`, customerID).Scan(&n)
return n, err
}
// MarkPaid uses BeginTx: if ctx ends before Commit, database/sql rolls back.
func (r *Orders) MarkPaid(ctx context.Context, orderID int64) error {
tx, err := r.DB.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback() // no-op after a successful Commit
if _, err := tx.ExecContext(ctx,
`UPDATE orders SET status = 'paid' WHERE id = $1`, orderID); err != nil {
return err
}
return tx.Commit()
}The statement the repository runs, and the server-side backstop that bounds it even when a client only drops the socket:
-- schema the repository reads and writes
CREATE TABLE orders (
id bigint PRIMARY KEY,
customer_id bigint NOT NULL,
status text NOT NULL DEFAULT 'new'
);
-- per-role backstop: no statement from the API runs longer than 5 s
ALTER ROLE api SET statement_timeout = '5s';
-- per-transaction override inside BeginTx
SET LOCAL statement_timeout = '500ms';
-- what is still running after clients gave up?
SELECT pid, state, now() - query_start AS running_for, left(query, 60) AS query
FROM pg_stat_activity
WHERE datname = current_database() AND state = 'active'
ORDER BY running_for DESC;
-- cancel one statement by hand (the same CancelRequest a driver sends)
SELECT pg_cancel_backend(4242);Context values: request-scoped data only Must-know
In plain words: A context can carry a few values that belong to this request and must cross API boundaries untouched: the request id, the authenticated principal, the trace span, maybe a tenant id. Each value is stored under a key type that only its own package can construct.
Common misunderstanding: "Context values are a dependency-injection container." Putting the logger, the DB pool or a config struct in ctx hides dependencies from signatures, makes them untyped and makes tests guess what to put in. The doc's rule: "Use context Values only for request-scoped data that transits processes and APIs, not for passing optional parameters to functions." A second one: "a string key is fine". It is not: "The provided key must be comparable and should not be of type string or any other built-in type to avoid collisions between packages using context."
Definition: WithValue(parent, key, val) returns a valueCtx node; ctx.Value(key) compares with == from the newest node up to the root. The doc recommends an unexported key type and typed accessors (NewContext/FromContext), and notes that keys "often have concrete type struct{}" to avoid allocating. Constructors panic with nil key or key is not comparable. Values survive cancellation and WithoutCancel.
1 middleware ctx = WithRequestID(r.Context(), "r-42") valueCtx{requestIDKey{}: r-42}
2 auth ctx = WithPrincipal(ctx, &Principal{"user:7"}) valueCtx{principalKey{}: ...}
3 otel ctx = trace.ContextWithSpan(ctx, span) valueCtx{otel key: span}
4 repository values.RequestID(ctx) -> "r-42" walks 3 nodes up
5 other pkg ctx.Value("requestIDKey") -> nil different key type, no collisionReal scenario: the request id echoed in every log line and in the response header; the principal checked by an authorization layer deep in the service; the OpenTelemetry span that links an outgoing HTTP call to its parent trace (OpenTelemetry Go stores spans in ctx exactly this way); a tenant id used by a repository to pick a schema.
| Belongs in ctx | Does not belong in ctx | Why not |
|---|---|---|
| Request id, correlation id | Logger (*slog.Logger) | A dependency: inject it; let a handler read the ids from ctx |
| Authenticated principal, roles | Database pool, HTTP client | Dependencies with lifetimes longer than a request |
| Trace span, baggage | Config, feature flags loaded at start | Process-scoped, not request-scoped |
| Tenant id (if every layer needs it) | Optional function parameters | Hidden, untyped arguments |
| Deadline-related metadata from upstream | Mutable maps you write to later | Data races; contexts are meant to be immutable |
Fix / how to use it: one unexported key type per value, an exported WithX/X accessor pair, and a test that a string key with the same name cannot collide.
// Package values carries request-scoped data with unexported key types and
// typed accessors. Dependencies and configuration do not belong here.
package values
import (
"context"
"crypto/rand"
"encoding/hex"
"net/http"
)
// Unexported key types: no other package can construct these keys, so no
// other package can collide with or overwrite the values.
type requestIDKey struct{}
type principalKey struct{}
// Principal is the authenticated caller of this request.
type Principal struct {
Subject string
Roles []string
}
// WithRequestID returns a child context carrying id.
func WithRequestID(ctx context.Context, id string) context.Context {
return context.WithValue(ctx, requestIDKey{}, id)
}
// RequestID returns the id, or "" when none was set.
func RequestID(ctx context.Context) string {
id, _ := ctx.Value(requestIDKey{}).(string)
return id
}
// WithPrincipal returns a child context carrying p.
func WithPrincipal(ctx context.Context, p *Principal) context.Context {
return context.WithValue(ctx, principalKey{}, p)
}
// PrincipalFrom reports the caller, if the auth middleware set one.
func PrincipalFrom(ctx context.Context) (*Principal, bool) {
p, ok := ctx.Value(principalKey{}).(*Principal)
return p, ok && p != nil
}
// RequestIDMiddleware trusts an inbound X-Request-Id only if it looks sane and
// otherwise mints one, then echoes it on the response.
func RequestIDMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
id := r.Header.Get("X-Request-Id")
if len(id) == 0 || len(id) > 64 {
var b [8]byte
rand.Read(b[:])
id = hex.EncodeToString(b[:])
}
w.Header().Set("X-Request-Id", id)
next.ServeHTTP(w, r.WithContext(WithRequestID(r.Context(), id)))
})
}package values
import (
"context"
"net/http"
"net/http/httptest"
"strconv"
"testing"
)
type otherKey string // what a careless package might use
func TestStringKeysDoNotCollideWithTypedKeys(t *testing.T) {
ctx := WithRequestID(t.Context(), "r-1")
ctx = context.WithValue(ctx, otherKey("requestIDKey"), "spoofed")
if got := RequestID(ctx); got != "r-1" {
t.Fatalf("RequestID = %q", got)
}
}
func TestMissingValuesAreZero(t *testing.T) {
if RequestID(t.Context()) != "" {
t.Fatal("want empty id")
}
if _, ok := PrincipalFrom(t.Context()); ok {
t.Fatal("want no principal")
}
}
func TestMiddlewareSetsAndEchoesID(t *testing.T) {
var seen string
h := RequestIDMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
seen = RequestID(r.Context())
}))
rec := httptest.NewRecorder()
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/", nil)
req.Header.Set("X-Request-Id", "abc123")
h.ServeHTTP(rec, req)
if seen != "abc123" || rec.Header().Get("X-Request-Id") != "abc123" {
t.Fatalf("seen=%q header=%q", seen, rec.Header().Get("X-Request-Id"))
}
}
func BenchmarkValueDepth(b *testing.B) {
for _, depth := range []int{1, 10, 100} {
ctx := WithRequestID(context.Background(), "r-1")
for i := 0; i < depth; i++ {
ctx = context.WithValue(ctx, otherKey("k"), i)
}
b.Run("depth="+strconv.Itoa(depth), func(b *testing.B) {
for b.Loop() {
_ = RequestID(ctx)
}
})
}
}slog context handlers Important
In plain words: slog passes the context to the handler on every InfoContext, ErrorContext and LogAttrs(ctx, ...) call. A small wrapper handler can read the request id and principal from ctx and add them to the record, so you never pass them by hand.
Common misunderstanding: "Put the logger in the context." Keep the logger as a dependency; put the data in ctx. Another: "log calls are skipped once the ctx is canceled." The Handler doc says the context argument "is present solely to provide Handlers access to the context's values. Canceling the context should not affect record processing."
Definition: slog.Handler has Enabled(context.Context, Level) and Handle(context.Context, Record) error. Logger.Info passes context.Background(); InfoContext(ctx, ...) passes yours. Wrappers must also implement WithAttrs and WithGroup to stay in the chain. OpenTelemetry's slog bridge uses the same mechanism to add trace and span ids.
1 log.InfoContext(ctx, "order placed", "order", 1001)
2 Logger -> Handler{base}.Handle(ctx, record)
3 wrapper: values.RequestID(ctx) -> r-42; PrincipalFrom(ctx) -> user:7
4 base TextHandler writes: level=INFO msg="order placed" order=1001 request_id=r-42 principal=user:7Real scenario: every log line of a request joinable by request_id in Loki or Elasticsearch; audit logs that must record the principal; logs and traces correlated by trace id; a background job that logs with the request id of the HTTP call that enqueued it.
| Call | ctx handler sees | Request ids in output |
|---|---|---|
log.Info(...) | context.Background() | No |
log.InfoContext(ctx, ...) | Your ctx | Yes |
log.LogAttrs(ctx, level, ...) | Your ctx | Yes |
log.With("k", v).InfoContext(ctx, ...) | Your ctx (wrapper kept by WithAttrs) | Yes |
Fix / how to use it: use the ...Context variants everywhere a ctx exists; a linter rule (sloglint context: scope) can enforce it.
// Package slogctx adds request-scoped attributes from the context to every
// log record. The logger stays a dependency; only the per-request data rides
// in ctx.
package slogctx
import (
"context"
"log/slog"
"academy/context/values"
)
// Handler wraps another slog.Handler and appends request_id and principal
// when the *Context logging methods are used.
type Handler struct{ slog.Handler }
// Handle implements slog.Handler.
func (h Handler) Handle(ctx context.Context, r slog.Record) error {
if id := values.RequestID(ctx); id != "" {
r.AddAttrs(slog.String("request_id", id))
}
if p, ok := values.PrincipalFrom(ctx); ok {
r.AddAttrs(slog.String("principal", p.Subject))
}
return h.Handler.Handle(ctx, r)
}
// WithAttrs keeps the wrapper when callers use logger.With.
func (h Handler) WithAttrs(as []slog.Attr) slog.Handler {
return Handler{h.Handler.WithAttrs(as)}
}
// WithGroup keeps the wrapper when callers use logger.WithGroup.
func (h Handler) WithGroup(name string) slog.Handler {
return Handler{h.Handler.WithGroup(name)}
}package slogctx
import (
"bytes"
"log/slog"
"strings"
"testing"
"academy/context/values"
)
func TestInfoContextAddsRequestAttrs(t *testing.T) {
var buf bytes.Buffer
base := slog.NewTextHandler(&buf, &slog.HandlerOptions{
ReplaceAttr: func(_ []string, a slog.Attr) slog.Attr {
if a.Key == slog.TimeKey {
return slog.Attr{} // stable output for the test
}
return a
},
})
log := slog.New(Handler{base})
ctx := values.WithRequestID(t.Context(), "r-42")
ctx = values.WithPrincipal(ctx, &values.Principal{Subject: "user:7"})
log.InfoContext(ctx, "order placed", "order", 1001)
log.Info("no ctx, no ids")
got := buf.String()
want := "level=INFO msg=\"order placed\" order=1001 request_id=r-42 principal=user:7\n" +
"level=INFO msg=\"no ctx, no ids\"\n"
if got != want {
t.Fatalf("got:\n%s\nwant:\n%s", got, want)
}
if strings.Count(got, "request_id") != 1 {
t.Fatal("plain Info must not see the request id")
}
}errgroup.WithContext Must-know
In plain words: errgroup.WithContext(ctx) gives you a group and a derived ctx. Run tasks with g.Go; the first task that returns an error cancels the ctx, so the others can stop; g.Wait() returns that first error.
Common misunderstanding: "The group cancels the other goroutines." It cancels their ctx; they stop only if they cooperate. Another trap: using the outer ctx inside g.Go instead of the derived one, so siblings never see the cancellation. And the derived ctx is canceled when Wait returns, so do not use it after Wait.
Definition: "The derived Context is canceled the first time a function passed to Go returns a non-nil error or the first time Wait returns, whichever occurs first." In golang.org/x/sync v0.19.0 WithContext is implemented with context.WithCancelCause, so context.Cause(ctx) inside a sibling returns the first error. SetLimit(n) bounds concurrency; worker-pool design is in Worker Pools, Pipelines & errgroup.
1 g, ctx := errgroup.WithContext(parent)
2 g.Go(product) g.Go(price) g.Go(reviews)
3 price returns errPrice ──▶ cancel(errPrice)
4 product, reviews: <-ctx.Done(); Cause(ctx) == errPrice; return ctx.Err()
5 g.Wait() == errPrice (first error, not the siblings' context canceled)Real scenario: a product page assembled from three services; uploading parts of a file in parallel; validating a batch where one bad record aborts the rest; starting an HTTP server and a consumer together and stopping both when either fails.
| Tool | Cancels siblings | Returns | Limit |
|---|---|---|---|
sync.WaitGroup | No | Nothing | No |
errgroup.Group{} (zero) | No | First error | SetLimit |
errgroup.WithContext | Yes, via ctx (with cause) | First error | SetLimit |
Hand-made WithCancel + channel | Yes | What you build | What you build |
Fix / how to use it: shadow the name on purpose (g, ctx := errgroup.WithContext(ctx)) so the outer ctx cannot be used by mistake inside the group.
// Package errgroupctx fans out three lookups for one page; the first failure
// cancels the siblings through the group's context.
package errgroupctx
import (
"context"
"fmt"
"golang.org/x/sync/errgroup"
)
// Fetcher is one downstream call that honours ctx.
type Fetcher func(ctx context.Context) (string, error)
// Page holds the three parts of a product page.
type Page struct{ Product, Price, Reviews string }
// Load runs the fetchers concurrently. errgroup.WithContext derives ctx with
// WithCancelCause, so context.Cause(ctx) is the first error after a failure.
func Load(ctx context.Context, product, price, reviews Fetcher) (Page, error) {
g, ctx := errgroup.WithContext(ctx) // shadowing on purpose: use only the group's ctx below
var p Page
g.Go(func() (err error) { p.Product, err = product(ctx); return })
g.Go(func() (err error) { p.Price, err = price(ctx); return })
g.Go(func() (err error) { p.Reviews, err = reviews(ctx); return })
if err := g.Wait(); err != nil {
return Page{}, fmt.Errorf("load page: %w", err)
}
return p, nil
}package errgroupctx
import (
"context"
"errors"
"testing"
"time"
)
var errPrice = errors.New("price service: 500")
func TestFirstErrorCancelsSiblings(t *testing.T) {
sawCancel := make(chan error, 2)
slow := func(ctx context.Context) (string, error) {
select {
case <-time.After(5 * time.Second):
return "late", nil
case <-ctx.Done():
sawCancel <- context.Cause(ctx)
return "", ctx.Err()
}
}
failing := func(ctx context.Context) (string, error) { return "", errPrice }
start := time.Now()
_, err := Load(t.Context(), slow, failing, slow)
if !errors.Is(err, errPrice) {
t.Fatalf("err = %v", err)
}
if time.Since(start) > time.Second {
t.Fatal("siblings were not canceled")
}
for range 2 {
if c := <-sawCancel; !errors.Is(c, errPrice) {
t.Fatalf("sibling cause = %v, want the price error", c)
}
}
}
func TestAllSucceed(t *testing.T) {
ok := func(s string) Fetcher { return func(context.Context) (string, error) { return s, nil } }
p, err := Load(t.Context(), ok("p"), ok("9.99"), ok("5*"))
if err != nil || p != (Page{"p", "9.99", "5*"}) {
t.Fatalf("p=%+v err=%v", p, err)
}
}context.AfterFunc Important
In plain words: context.AfterFunc(ctx, f) runs f in its own goroutine when ctx is canceled. Use it to wake up something that does not understand contexts: set a deadline on a socket, broadcast a sync.Cond, close a resource.
Common misunderstanding: "stop() waits for f." It does not: "The stop function does not wait for f to complete before returning." If stop() returns false, f has started (or was already stopped) and you must coordinate with it yourself, which is why the snippet resets the deadline in that case.
Definition: AfterFunc(ctx, f) (stop func() bool). "If ctx is already canceled, AfterFunc calls f immediately in its own goroutine." Several registrations are independent. Calling stop "stops the association of ctx with f. It returns true if the call stopped f from being run." It costs no goroutine while waiting (it registers as a child of the cancel tree).
1 stop := context.AfterFunc(ctx, func() { conn.SetReadDeadline(time.Now()) })
2 n, err := conn.Read(buf) blocks: Read knows nothing about ctx
3 ctx canceled ──▶ f runs ──▶ deadline in the past ──▶ Read returns os.ErrDeadlineExceeded
4 ReadContext maps it to context.Cause(ctx)
5 defer: stop() == false, so reset the deadline for the next callerReal scenario: a custom TCP protocol client (net.Conn has deadlines, not ctx); waking goroutines waiting on a sync.Cond when a request ends; releasing a lease when the owning ctx ends; closing a file watcher handle on shutdown.
| Need | Without AfterFunc | With AfterFunc |
|---|---|---|
Interrupt net.Conn.Read | Extra goroutine with select on Done | One registration, no goroutine while idle |
Wake sync.Cond.Wait | Hard to do correctly | cond.Broadcast() in f (the pattern in the package example) |
| Merge two contexts' cancellation | Goroutine per merge | AfterFunc(b, cancelA) |
Fix / how to use it:
// Package afterfunc connects ctx to an API that knows nothing about contexts.
// A net.Conn read blocks until data or a deadline; context.AfterFunc turns
// cancellation into an immediate deadline.
package afterfunc
import (
"context"
"errors"
"net"
"os"
"time"
)
// ReadContext reads from conn but returns early when ctx is done.
func ReadContext(ctx context.Context, conn net.Conn, b []byte) (int, error) {
stop := context.AfterFunc(ctx, func() {
conn.SetReadDeadline(time.Now()) // wakes the blocked Read
})
defer func() {
if !stop() {
// AfterFunc already ran (or is running): clear the deadline so
// the connection stays usable for the next caller.
conn.SetReadDeadline(time.Time{})
}
}()
n, err := conn.Read(b)
if err != nil && errors.Is(err, os.ErrDeadlineExceeded) && ctx.Err() != nil {
return n, context.Cause(ctx) // report why, not the mechanism
}
return n, err
}package afterfunc
import (
"context"
"errors"
"net"
"testing"
"time"
)
func TestReadReturnsOnCancel(t *testing.T) {
client, server := net.Pipe()
defer client.Close()
defer server.Close()
ctx, cancel := context.WithTimeout(t.Context(), 20*time.Millisecond)
defer cancel()
buf := make([]byte, 8)
_, err := ReadContext(ctx, client, buf) // nobody writes
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("err = %v", err)
}
}
func TestReadSucceedsAndStopsAfterFunc(t *testing.T) {
client, server := net.Pipe()
defer client.Close()
defer server.Close()
go server.Write([]byte("hi"))
buf := make([]byte, 8)
n, err := ReadContext(t.Context(), client, buf)
if err != nil || string(buf[:n]) != "hi" {
t.Fatalf("n=%d err=%v", n, err)
}
}WithoutCancel and fire-and-forget Must-know
In plain words: Sometimes work must continue after the response is sent: write the audit row, publish the event, warm the cache. context.WithoutCancel(r.Context()) gives you a context that keeps the request's values (request id, trace) but is not canceled when the request is.
Common misunderstanding: "Use context.Background() for background work." That loses the request id and the trace, so the logs of the follow-up work cannot be joined to the request. The opposite mistake is also common: using r.Context() in go audit(r.Context()), which is canceled the moment the handler returns, so the audit write fails with context canceled most of the time.
Definition: "WithoutCancel returns a derived context that points to the parent context and is not canceled when parent is canceled. The returned context returns no Deadline or Err, and its Done channel is nil. Calling Cause on the returned context returns nil." Values still resolve through it. Because it has no deadline, always add your own WithTimeout, and own the goroutine (a WaitGroup you wait on during shutdown) so fire-and-forget does not become fire-and-lose.
1 handler bg.Go(r.Context(), audit) ctx := WithoutCancel(r.Context()); go ...
2 handler writes 201, returns r.Context() canceled
3 audit ctx.Err() == nil; RequestID(ctx) == "r-9"
4 audit WithTimeout(ctx, 10s) bounds it
5 shutdown bg.Wait() before closing the DBReal scenario: an audit log write that must not fail because the user closed the tab; sending a welcome email after signup returns; publishing an OrderPlaced event when you have no outbox (prefer an outbox when it matters); flushing analytics after the response.
| Option | Keeps values | Survives request end | Bounded | Shutdown-safe |
|---|---|---|---|---|
go f(r.Context()) | Yes | No | By request | No |
go f(context.Background()) | No | Yes | No | No |
go f(context.WithoutCancel(r.Context())) | Yes | Yes | No | No |
Background.Go in the snippet | Yes | Yes | WithTimeout | Wait in shutdown |
| Outbox table + relay | Request id stored in the row | Yes, even across crashes | Retries | Yes |
Fix / how to use it:
// Package detach runs follow-up work after the response is sent. The work
// keeps the request's values (request id, trace) but must not inherit its
// cancellation, so it uses context.WithoutCancel plus its own timeout.
package detach
import (
"context"
"sync"
"time"
)
// Auditor records an event; it honours ctx like any downstream call.
type Auditor func(ctx context.Context, event string) error
// Background owns detached goroutines so shutdown can wait for them.
type Background struct {
wg sync.WaitGroup
Timeout time.Duration
}
// Go starts fn detached from reqCtx's cancellation but bounded by b.Timeout.
func (b *Background) Go(reqCtx context.Context, fn func(context.Context)) {
ctx := context.WithoutCancel(reqCtx) // values kept; Done is nil; no deadline
b.wg.Add(1)
go func() {
defer b.wg.Done()
ctx, cancel := context.WithTimeout(ctx, b.Timeout)
defer cancel()
fn(ctx)
}()
}
// Wait blocks until all detached work is finished (call it during shutdown).
func (b *Background) Wait() { b.wg.Wait() }package detach
import (
"context"
"errors"
"testing"
"time"
"academy/context/values"
)
func TestDetachedWorkSurvivesRequestCancel(t *testing.T) {
reqCtx, cancel := context.WithCancel(values.WithRequestID(t.Context(), "r-9"))
var bg Background
bg.Timeout = time.Second
type result struct {
id string
err error
}
done := make(chan result, 1)
bg.Go(reqCtx, func(ctx context.Context) {
time.Sleep(20 * time.Millisecond) // the request has ended by now
done <- result{values.RequestID(ctx), ctx.Err()}
})
cancel() // response written, handler returned
bg.Wait()
r := <-done
if r.id != "r-9" || r.err != nil {
t.Fatalf("id=%q err=%v, want r-9 and nil", r.id, r.err)
}
if context.Cause(context.WithoutCancel(reqCtx)) != nil {
t.Fatal("Cause of a WithoutCancel context must be nil")
}
}
func TestDetachedWorkStillHasABound(t *testing.T) {
var bg Background
bg.Timeout = 10 * time.Millisecond
errc := make(chan error, 1)
bg.Go(t.Context(), func(ctx context.Context) {
<-ctx.Done()
errc <- ctx.Err()
})
bg.Wait()
if err := <-errc; !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("err = %v", err)
}
}Goroutine leaks and timer leaks Must-know
In plain words: A goroutine leaks when it blocks forever: usually a send on a channel nobody reads any more. A context gives every such send a second way out. A timer leaks when you create one per loop iteration and never stop it.
Common misunderstanding: "The garbage collector frees blocked goroutines." It never does; a goroutine blocked on a channel send is live forever, with its stack and everything it references. For timers the story changed in Go 1.23: unreferenced Timers and Tickers "become eligible for garbage collection immediately, even if their Stop methods have not been called", but only "when the main Go program is in a module with a go.mod go line using Go 1.23.0 or later" (the snippets say 1.24). On older go lines, time.After in a hot for-select loop kept every timer alive until it fired. A forgotten cancel() from WithTimeout still keeps the child in its parent's children map until the parent ends.
Definition: a leak is any goroutine whose exit depends on an event that will not happen. With contexts, every blocking point has case <-ctx.Done():, and the owner calls cancel when it stops caring. Test with runtime.NumGoroutine before/after, the goleak package, or a goroutine profile (/debug/pprof/goroutine?debug=2) in production.
LeakyFirst First (with ctx)
1 ch := make(chan string) ctx, cancel := WithCancel(ctx); defer cancel()
2 10 producers start 10 producers start
3 main receives 1 value, returns main receives 1 value, returns -> cancel()
4 9 producers block on ch <- v forever 9 producers: select picks <-ctx.Done(), exit
5 NumGoroutine: +9 per call NumGoroutine: back to baselineReal scenario: "first replica to answer wins" without cancel; a websocket writer goroutine that keeps a reference to a closed connection; a streaming handler whose producer blocks after the client left; memory growing by a few MB per hour with goroutine count growing in step.
| Leak | Symptom | Fix |
|---|---|---|
| Blocked send after caller returned | Goroutine count grows with traffic | select with ctx.Done(), or buffered channel of exact size |
Missing cancel() on WithTimeout | vet lostcancel; child kept until parent ends | defer cancel() |
time.After in a loop (go.mod before 1.23) | Heap holds many timers | time.NewTimer + Stop, or a Ticker |
Goroutine using r.Context() after the handler returned | Work aborted, error logs | WithoutCancel + timeout |
AfterFunc never stopped on a long-lived ctx | Callback list grows | Call stop() when done |
Fix / how to use it:
// Package leak shows the goroutine leak a context prevents: a producer blocked
// on a send that nobody will ever receive.
package leak
import "context"
// LeakyFirst returns the first result and abandons the other producers. Each
// abandoned producer blocks on its send forever.
func LeakyFirst(queries []func() string) string {
ch := make(chan string)
for _, q := range queries {
go func() { ch <- q() }()
}
return <-ch
}
// First returns the first result and cancels the rest; every producer either
// delivers or sees ctx.Done and exits.
func First(ctx context.Context, queries []func(context.Context) string) string {
ctx, cancel := context.WithCancel(ctx)
defer cancel() // tells the losers to stop
ch := make(chan string)
for _, q := range queries {
go func() {
v := q(ctx)
select {
case ch <- v:
case <-ctx.Done():
}
}()
}
return <-ch
}package leak
import (
"context"
"runtime"
"testing"
"time"
)
// settle waits briefly for exiting goroutines to finish.
func settle(want int) int {
deadline := time.Now().Add(time.Second)
n := runtime.NumGoroutine()
for n > want && time.Now().Before(deadline) {
time.Sleep(5 * time.Millisecond)
n = runtime.NumGoroutine()
}
return n
}
func TestFirstDoesNotLeak(t *testing.T) {
before := runtime.NumGoroutine()
qs := make([]func(context.Context) string, 10)
for i := range qs {
qs[i] = func(context.Context) string { return "r" }
}
_ = First(t.Context(), qs)
if after := settle(before); after > before {
t.Fatalf("goroutines: before=%d after=%d", before, after)
}
}
func TestLeakyFirstLeaks(t *testing.T) {
before := runtime.NumGoroutine()
qs := make([]func() string, 10)
for i := range qs {
qs[i] = func() string { return "r" }
}
_ = LeakyFirst(qs)
if after := settle(before); after != before+9 {
t.Fatalf("expected 9 leaked goroutines, before=%d after=%d", before, after)
}
}Testing with t.Context Important
In plain words: Since Go 1.24 every test has t.Context(): a context canceled when the test finishes, just before cleanups run. Use it as the root of everything the test starts.
Common misunderstanding: "context.Background() in tests is fine." It works, but goroutines started by a failed test keep running into the next one; with t.Context() they are told to stop. Also, tests for timeouts should use short real budgets (10 to 50 ms) and assert an upper bound on elapsed time, not exact timings.
Definition: Go 1.24 notes: "The new T.Context and B.Context methods return a context that's canceled after the test completes and before test cleanup functions run." The source adds: "Cleanup functions can wait for any resources that shut down on context.Context.Done before the test or benchmark completes." Go 1.23's httptest.NewRequestWithContext builds a server-side request with your ctx, which is how the handler tests here simulate a client that already left.
1 func TestX(t *testing.T) {
2 ctx := t.Context() live while the test body runs
3 go server.Run(ctx)
4 ...assertions...
5 } test body returns -> ctx canceled -> Cleanup funcs runReal scenario: starting an httptest.Server whose handlers inherit the test's lifetime; consumer loops in integration tests; table tests that each derive a WithTimeout from t.Context(); benchmarks with b.Context().
| Need in a test | Use |
|---|---|
| Root ctx | t.Context() (1.24+) |
| A client that already disconnected | ctx, cancel := WithCancel(t.Context()); cancel() + httptest.NewRequestWithContext |
| An expired budget | WithTimeout(t.Context(), -time.Second) (canceled at once) |
| Deterministic time (1.25+) | testing/synctest bubbles (not used here: snippets target 1.24) |
Fix / how to use it: every test file in this chapter's module uses t.Context(); see Testing & Benchmarking for the rest of the testing package.
Custom Context implementations Good to know
In plain words: You can implement the four methods yourself, but you almost never should; wrap a standard context instead.
Common misunderstanding: "My framework needs its own Context type." CodeReviewComments: "Don't create custom Context types or use interfaces other than Context in function signatures." Frameworks such as Gin pass a *gin.Context that implements context.Context, which is a frequent source of bugs when it is captured by a goroutine after the request ended (Gin documents copying it with c.Copy()).
Definition: a foreign Context type works as a parent, but the package then cannot find a cancelCtx in it and, unless the type implements AfterFunc(func()) func() bool, propagates cancellation with one extra goroutine per child (propagateCancel in the source). Cause falls back to Err for custom implementations.
1 WithCancel(customParent)
2 parentCancelCtx(customParent) -> not found
3 customParent has AfterFunc method? -> use it (no goroutine)
4 otherwise: go func() { select { case <-parent.Done(): child.cancel(...) case <-child.Done(): } }()Real scenario: an RPC framework bridging its own cancellation into Go contexts; Gin and Echo handler contexts; test doubles that record Value lookups.
| Choice | Cost |
|---|---|
| Standard constructors only | None |
Custom type with AfterFunc method | Must get the semantics right |
| Custom type without it | One goroutine per derived child |
Fix / how to use it: convert at the edge (ctx := c.Request.Context() in Gin) and pass a plain context.Context inward.
Mechanics
Data structures Important
The package is about 800 lines. Every constructor returns one of a handful of unexported types, each holding its parent as an embedded Context:
| Type | Built by | Fields that matter | Done() |
|---|---|---|---|
backgroundCtx, todoCtx | Background, TODO | none (emptyCtx) | nil |
cancelCtx | WithCancel, WithCancelCause | mu, done (lazily made channel), children map[canceler]struct{}, err, cause | Own channel |
timerCtx | WithDeadline, WithTimeout (+Cause variants) | embedded cancelCtx, timer *time.Timer, deadline | Own channel |
valueCtx | WithValue | key, val any | Parent's |
withoutCancelCtx | WithoutCancel | parent only | nil |
afterFuncCtx | AfterFunc | embedded cancelCtx, once, f | n/a |
Cancellation, step by step, as in cancelCtx.cancel:
1 lock c.mu; if c.err already set -> unlock, return (first cancel wins)
2 c.err = Canceled or DeadlineExceeded; c.cause = cause or err
3 close(c.done), or store the shared closedchan if Done() was never called
4 for each child in c.children: child.cancel(false, err, cause) (depth-first, under the lock)
5 c.children = nil; unlock
6 if removeFromParent: delete c from parent's children map
7 timerCtx only: stop the timerAttaching a child (propagateCancel): if the parent's Done() is nil (Background, TODO, WithoutCancel) nothing is registered; if the parent is already canceled the child is canceled at once; if a *cancelCtx is found up the chain the child is added to its children map; if the parent implements AfterFunc it is used; otherwise a goroutine waits on both Done channels.
Value lookup is a linked list walk Important
Value loops from the context you hold to the root, comparing key == ctx.key at each valueCtx and skipping cancel and timer nodes. There is no map and no cache, so lookup cost is linear in depth. The benchmark in the values snippet (real run, Go 1.27.4, Apple M4 Pro): 3.8 ns at depth 1, 11 ns at depth 10, 110 ns at depth 100, 0 allocations. A typical request has fewer than ten value nodes, so this never matters, unless someone uses ctx as a map and adds a node per field inside a loop.
Exact error and panic texts Must-know
| Text | Where it comes from |
|---|---|
context canceled | context.Canceled = errors.New("context canceled") |
context deadline exceeded | deadlineExceededError.Error(); also Timeout() == true, Temporary() == true |
cannot create context from nil parent | Panic in every With* constructor |
nil key / key is not comparable | Panics in WithValue |
Get "https://api.example.test/x": context deadline exceeded | *url.Error from http.Client.Do |
net/http: request canceled while waiting for connection | Transport, ctx ended while waiting for a pooled connection |
(Client.Timeout exceeded while awaiting headers) | Suffix added by http.Client when its own Timeout fires |
http: Handler timeout | http.ErrHandlerTimeout, writes after TimeoutHandler fired |
rpc error: code = DeadlineExceeded desc = context deadline exceeded | grpc-go status format rpc error: code = %s desc = %s |
rpc error: code = Canceled desc = context canceled | grpc-go, caller canceled |
timeout: context deadline exceeded | pgx errTimeout, unwraps to the context error |
ERROR: canceling statement due to user request (SQLSTATE 57014) | PostgreSQL after a CancelRequest |
ERROR: canceling statement due to statement timeout (SQLSTATE 57014) | PostgreSQL statement_timeout |
And the String() of a context, handy in debugging (real output):
context.Background | context.TODO
context.Background.WithDeadline(2026-11-26 11:19:37.648652 +0330 +0330 m=+1.000149917 [999.653416ms])
context.Background.WithValue(k, v).WithDeadline(... [...]).WithoutCancelSolving the classic problems
| Bug | Symptom | Fix | Cost |
|---|---|---|---|
| Ignoring ctx in loops | Work continues after cancel | ctx.Err() between items, select on Done | One check per iteration |
context.Background() in a handler or repository | Disconnects and deadlines ignored | Accept ctx and pass it | Signature change |
Timer leak (time.After per iteration, go.mod before 1.23) | Heap growth | NewTimer + Stop, Ticker, or go 1.23+ | None |
Missing cancel() | vet lostcancel, children kept | defer cancel() | None |
| Cancel too early | context canceled on a call that should have worked | Cancel after the last use (including body read) | Care with ownership |
| Shadowing ctx | Inner code uses the wrong (outer or inner) ctx | Shadow on purpose, or name gctx/reqCtx clearly | Naming discipline |
Goroutine using r.Context() after return | Follow-up work fails | WithoutCancel + WithTimeout, owned by a WaitGroup | Shutdown wiring |
| Retrying a canceled call | Work for a caller that left | Classify before retrying | Classification code |
| Logging cancellations as errors | Alert noise on every disconnect | Log Canceled at INFO with Cause | Classification code |
Ignoring ctx in loops
Use the shapes from Cooperative cancellation: a cheap ctx.Err() check between items, select on ctx.Done() wherever you wait, never time.Sleep in a request path.
context.Background in a handler
The Before handler is the classic: NewRequestWithContext(context.Background(), ...) inside Reserve. Its test proves the downstream is called even though the client was already gone.
package before
import (
"context"
"io"
"net/http"
"net/http/httptest"
"sync/atomic"
"testing"
)
// The client is gone before the handler starts, yet the downstream is still
// called: this is the waste the "after" version removes.
func TestBeforeIgnoresClientCancel(t *testing.T) {
var calls atomic.Int32
down := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls.Add(1)
io.WriteString(w, "r-1")
}))
defer down.Close()
ctx, cancel := context.WithCancel(t.Context())
cancel()
h := Handler(&Inventory{BaseURL: down.URL, Client: down.Client()})
h(httptest.NewRecorder(), httptest.NewRequestWithContext(ctx, http.MethodGet, "/?sku=A1", nil))
if n := calls.Load(); n != 1 {
t.Fatalf("downstream calls = %d, want 1 (cancellation ignored)", n)
}
}Cancel too early, and shadowing ctx
// Bug: cancel runs when fetch returns, but the caller still reads resp.Body.
func fetch(ctx context.Context, url string) (*http.Response, error) {
ctx, cancel := context.WithTimeout(ctx, time.Second)
defer cancel() // body reads after return fail with "context canceled"
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
return http.DefaultClient.Do(req)
}
// Fix: read inside the function (as Reserve does), or return the cancel func
// for the caller to call after closing the body.
// Shadowing: the inner := creates a new ctx only inside the if block.
if needCache {
ctx, cancel := context.WithTimeout(ctx, 50*time.Millisecond)
defer cancel()
_ = ctx // used only here; code after the block uses the outer ctx again
}Classify errors for logs, metrics and retries
context.Canceled means the caller stopped caring; retrying is wasted work and logging it as ERROR pages someone for every closed tab. DeadlineExceeded needs one more question: is my own ctx done (the overall budget is spent, give up) or only a per-attempt child (retry if the call is idempotent)? Retry policy itself (backoff, jitter, budgets) is in Timeouts, Retries & Jitter.
// Package classify turns an error into a decision: log level, metric label and
// whether a retry makes sense. Cancellation by the caller is not a failure of
// the callee and must never be retried.
package classify
import (
"context"
"errors"
"log/slog"
"net"
)
// Outcome is what the caller should do with an error.
type Outcome struct {
Label string // metric label
Level slog.Level // log level
Retry bool // safe to retry (for idempotent calls)
}
// Of classifies err in the context ctx of the operation that produced it.
func Of(ctx context.Context, err error) Outcome {
switch {
case err == nil:
return Outcome{"ok", slog.LevelDebug, false}
case errors.Is(err, context.Canceled):
// The caller gave up (client disconnect, sibling failed, shutdown).
return Outcome{"canceled", slog.LevelInfo, false}
case errors.Is(err, context.DeadlineExceeded):
if ctx.Err() != nil {
// Our own (or an inherited) budget is spent: retrying cannot help.
return Outcome{"deadline", slog.LevelWarn, false}
}
// A shorter per-attempt timeout fired; the overall budget remains.
return Outcome{"attempt_timeout", slog.LevelWarn, true}
}
var ne net.Error
if errors.As(err, &ne) && ne.Timeout() {
return Outcome{"net_timeout", slog.LevelWarn, true}
}
return Outcome{"error", slog.LevelError, false}
}package classify
import (
"context"
"errors"
"fmt"
"testing"
"time"
)
func TestOf(t *testing.T) {
live := t.Context()
spent, cancel := context.WithTimeout(t.Context(), -time.Second) // already expired
defer cancel()
cases := []struct {
name string
ctx context.Context
err error
label string
retry bool
}{
{"nil", live, nil, "ok", false},
{"caller canceled", live, fmt.Errorf("query: %w", context.Canceled), "canceled", false},
{"overall budget", spent, context.DeadlineExceeded, "deadline", false},
{"attempt timeout", live, fmt.Errorf("attempt 1: %w", context.DeadlineExceeded), "attempt_timeout", true},
{"other", live, errors.New("boom"), "error", false},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
o := Of(c.ctx, c.err)
if o.Label != c.label || o.Retry != c.retry {
t.Fatalf("got %+v, want label=%s retry=%v", o, c.label, c.retry)
}
})
}
}
func TestDeadlineExceededIsANetTimeout(t *testing.T) {
var te interface{ Timeout() bool }
if !errors.As(context.DeadlineExceeded, &te) || !te.Timeout() {
t.Fatal("context.DeadlineExceeded should report Timeout() == true")
}
}Choosing
| Situation | Use | Extra technique | Reason |
|---|---|---|---|
| Program entry | signal.NotifyContext(context.Background(), ...) | Pass it to servers and workers | One root for shutdown |
| HTTP handler | r.Context() | WithTimeout per downstream call | Disconnect + budget |
| Outgoing HTTP | NewRequestWithContext | Client.Timeout as backstop | Caller's budget applies |
| Outgoing gRPC | Incoming ctx | Set a deadline at the first hop | grpc-timeout propagates |
| SQL | QueryContext/ExecContext/BeginTx | statement_timeout backstop | Driver-dependent server behaviour |
| Parallel calls, all needed | errgroup.WithContext | SetLimit | First error cancels siblings |
| First answer wins | WithCancel + defer cancel() | select on send | No leaked losers |
API without ctx (net.Conn, sync.Cond) | context.AfterFunc | Reset state when stop() is false | Bridges cancellation |
| Work after the response | WithoutCancel + WithTimeout | Owned WaitGroup, or outbox | Keeps ids, survives the request |
| Explaining why | WithCancelCause, WithTimeoutCause | Log context.Cause | Readable logs |
| Request id, principal, trace | WithValue with unexported key | slog wrapper handler | Request-scoped only |
| Tests | t.Context() | Short budgets, upper-bound asserts | Lifetime tied to the test |
In architecture: from a single process to a distributed system
Monolith: one process, one database
Inside one binary, context is plain plumbing: main builds the root from signal.NotifyContext, http.Server.BaseContext returns it so shutdown can reach handlers, each handler passes r.Context() through service and repository layers to QueryContext. The simplest correct monolith has exactly three places that create contexts: main, per-call WithTimeouts, and tests. Everything else accepts and passes. Values hold the request id and the principal; the slog wrapper turns them into log fields. Example: a Laravel-shaped Go monolith where POST /orders has a 2 s budget, the inventory check gets 300 ms and the insert gets 500 ms, and a closed tab aborts the inventory query.
Modular monolith and multiple databases
Module boundaries are function calls, so contexts cross them for free; the risk is a module that "protects" itself by starting from Background() or by storing ctx in a module-level struct. Make the module API take ctx first and own its own sub-budgets (billing.Charge(ctx, ...) derives 1 s for its database). With two databases (orders in PostgreSQL, sessions in Redis), each client gets its own timeout under the same parent, and a canceled request rolls back the open Tx in one and abandons the Redis call in the other. Nothing coordinates the two: context stops work, it does not make two stores atomic (see ACID & Transactions).
Microservices
Across a network, the context object does not travel; its pieces are re-created on the other side. The deadline travels as a duration (grpc-timeout, or a custom header over HTTP), the request id and trace context travel as headers (traceparent from W3C Trace Context via OpenTelemetry propagators), and the principal travels as a token that the next service verifies again rather than trusts. Cancellation travels implicitly: when the caller's ctx ends, grpc-go sends RST_STREAM, the HTTP client closes the connection, and the callee's r.Context() or stream ctx is canceled. Example flow: mobile app (3 s) → BFF (grpc-timeout: 2900m) → orders (2500m) → payments over HTTP (X-Timeout-Ms: 1800) → payment provider; when the provider hangs, every hop's context ends at the same instant, orders maps codes.DeadlineExceeded to a 504, and no hop keeps working for a caller that is gone. What does not survive: WithoutCancel semantics (a detached job on one service is invisible to others), values that were never serialised, and any guarantee that the callee actually stopped (it may have committed just before the cancel arrived, so idempotency keys are still required; see API Idempotency).
Distributed data: replicas, caches, sharded databases, multi-region
A context deadline bounds how long you wait, not what the other side did. A read from a replica that times out may have been answered a millisecond later; a write whose ctx expired during COMMIT may have committed. So: give replica and cache reads short budgets with a fallback (primary or stale value), give writes a budget long enough to finish and treat a timeout on a write as "unknown outcome", resolved by reading back or by an idempotency key. In fan-out queries across shards, errgroup.WithContext with a per-shard timeout and a "partial results allowed" policy keeps one slow shard from defining the p99 (see Latency Budgets & Tail Latency). Across regions, propagate durations, never timestamps, because clocks drift.
Scaling path: 1×, 10×, 100×
| Load | What changes | Context practice |
|---|---|---|
| 1× (one instance) | Bugs are invisible | defer cancel(), ctx first, QueryContext everywhere; vet in CI |
| 10× (a few instances behind a load balancer) | Slow dependencies pile up goroutines and connections | Per-call budgets; classify Canceled as INFO; statement_timeout backstop |
| 100× (many services, retries at several layers) | Retries multiply load; abandoned work dominates | Deadline propagation on every hop; no retry when the overall ctx is done; load shedding when the remaining budget is too small to finish (Load Shedding) |
Lab
1. Run the tests (real)
cd docs/snippets/go/context/go
go vet ./... && go test -race -count=1 ./...
# ok academy/context/after 1.541s
# ok academy/context/afterfunc 1.266s
# ok academy/context/before 1.508s
# ok academy/context/classify 1.405s
# ok academy/context/cooperative 1.243s
# ok academy/context/dbctx 1.316s
# ok academy/context/detach 1.454s
# ok academy/context/errgroupctx 1.201s
# ok academy/context/leak 2.299s
# ok academy/context/propagation 1.405s
# ok academy/context/slogctx 1.419s
# ok academy/context/tree 1.419s
# ok academy/context/values 1.387s2. Watch vet catch a lost cancel (real)
Save this outside the snippet module and run go vet .:
func discard(parent context.Context) {
ctx, _ := context.WithTimeout(parent, time.Second)
fmt.Println(ctx)
}
func somePaths(parent context.Context, fast bool) error {
ctx, cancel := context.WithCancel(parent)
if fast {
return nil
}
defer cancel()
return ctx.Err()
}main.go:10:7: the cancel function returned by context.WithTimeout should be called, not discarded, to avoid a context leak
main.go:15:2: the cancel function is not used on all paths (possible context leak)
main.go:17:3: this return statement may be reached without using the cancel var defined on line 153. Measure value lookup depth (real)
go test -run '^$' -bench BenchmarkValueDepth -benchmem ./values
# cpu: Apple M4 Pro
# BenchmarkValueDepth/depth=1-12 311752888 3.758 ns/op 0 B/op 0 allocs/op
# BenchmarkValueDepth/depth=10-12 100000000 11.01 ns/op 0 B/op 0 allocs/op
# BenchmarkValueDepth/depth=100-12 10830922 109.6 ns/op 0 B/op 0 allocs/op4. Count a goroutine leak (real)
go test -run 'TestLeakyFirstLeaks|TestFirstDoesNotLeak' -v ./leak
# --- PASS: TestFirstDoesNotLeak (goroutines back to baseline)
# --- PASS: TestLeakyFirstLeaks (exactly 9 goroutines stuck on a send)5. Client disconnect against a real server (expected, not run)
Wire the After handler into a main on 127.0.0.1:8080 with a slow inventory stub, then:
curl -m 0.1 'http://127.0.0.1:8080/?sku=A1'
# curl: (28) Operation timed out after 100 milliseconds with 0 bytes received
# server log (expected):
# level=INFO msg="client went away" err="context canceled"6. PostgreSQL cancellation (expected, not run)
Two terminals against a local PostgreSQL. In Go, run QueryContext(ctx, "SELECT pg_sleep(10)") with a 500 ms timeout once with the pgx default handler and once with CancelRequestContextWatcherHandler. In psql, watch pg_stat_activity (query in Database calls):
# default pgx handler: Go returns "timeout: context deadline exceeded" at 0.5s;
# pg_stat_activity shows the backend until it notices the closed socket
# CancelRequest handler: server log shows
# ERROR: canceling statement due to user request
# and the row disappears from pg_stat_activity at onceFor PHP/Laravel developers
PHP-FPM has no equivalent of a cancellation tree, because each request is a process (or worker) that runs one script from top to bottom. What you have instead are process-level limits and a disconnect flag: max_execution_time / set_time_limit() (script execution time), FPM's request_terminate_timeout (kills the worker), and connection handling, which says "The default behavior is however, for your script to be aborted when the remote client disconnects", noticed only when PHP tries to write output, unless ignore_user_abort is set. None of these reach into an outgoing Guzzle call or a running query except as separate per-client timeouts.
// Laravel: each call gets its own timeout; there is no shared budget.
$response = Http::timeout(3)->post($url, $payload); // 3 s, whatever the request has left
DB::statement("SET LOCAL statement_timeout = '500ms'"); // inside DB::transactionLaravel 13's Context facade is the closest thing to context values, and only to that half: its docs say context lets you "capture, retrieve, and share information throughout requests, jobs, and commands", and what you add with Context::add('trace_id', ...) is attached to log entries and carried into queued jobs dispatched from the request (Context::addHidden keeps data out of logs). It has no cancellation and no deadline. In Go terms, Context::add is WithValue plus the slog wrapper handler, and the "dehydrate into the job payload" step is what you do by hand when you copy the request id into a message header.
| Laravel / PHP | Go |
|---|---|
| One process per request, killed by FPM | One goroutine per request, asked to stop by ctx |
max_execution_time, request_terminate_timeout | WithTimeout, http.TimeoutHandler |
ignore_user_abort, connection_aborted() | r.Context().Done() |
Http::timeout(3) | NewRequestWithContext with a derived timeout |
Context::add('trace_id', ...) | WithValue + slog handler |
dispatch(...)->afterResponse() | WithoutCancel + owned goroutine, or an outbox |
Common misconceptions
| Belief | Reality |
|---|---|
| Cancel kills the goroutine | It closes a channel; code must check it |
| A child timeout can extend the parent's | The earlier deadline always wins |
cancel() is optional when work finished | It releases the timer and the parent's reference; vet flags it |
CancelFunc waits for the work to stop | It returns immediately |
ctx.Err() returns my cause | It returns Canceled/DeadlineExceeded; use context.Cause |
context.Background() is a safe default in a handler | It cuts the request off from disconnects and deadlines |
| Storing ctx in a struct is fine | Only for short-lived request-scoped objects; pass it instead |
| Context values are good for dependencies | Request-scoped data only; inject dependencies |
| String keys are fine if unique | Use an unexported key type; collisions are silent |
http.TimeoutHandler stops the handler | It answers 503 and cancels ctx; the handler must cooperate |
| Server shutdown cancels request contexts | Shutdown waits; it does not cancel r.Context() |
| A timed-out write did not happen | Its outcome is unknown; read back or use idempotency keys |
context canceled in logs means a bug | Usually a client disconnect or a failed sibling: INFO |
| Values are lost after cancellation | Values survive cancel and WithoutCancel |
Cheat sheet
| Topic | Remember |
|---|---|
| Signature | func F(ctx context.Context, ...): first, named ctx, never nil |
| Roots | Background in main/tests/server root; TODO as a marker |
| Derive | WithCancel, WithTimeout, WithDeadline; then defer cancel() |
| Shorter wins | A child deadline can only be earlier than its parent's |
| Errors | context.Canceled vs context.DeadlineExceeded; check with errors.Is |
| Why | WithCancelCause/WithTimeoutCause, read with context.Cause |
| Cooperate | ctx.Err() in loops, select on ctx.Done(), pass ctx to I/O |
| HTTP server | r.Context() canceled on disconnect or when the handler returns |
| HTTP client | NewRequestWithContext; Client.Timeout is only a backstop |
| Across services | Send remaining duration (grpc-timeout), not a timestamp |
| SQL | QueryContext/BeginTx; pgx default breaks the conn; keep statement_timeout |
| Values | Unexported key type, typed accessors, request-scoped only |
| Logs | InfoContext + a handler that reads ids from ctx |
| Fan-out | errgroup.WithContext; first error cancels siblings |
| After response | WithoutCancel + WithTimeout + owned goroutine |
| Tests | t.Context() (1.24+) |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — What do Done() and Err() return on context.Background()? Must-know
Answer
Answer: Done() returns nil (a channel that blocks forever, correct because Background is never canceled) and Err() returns nil. Deadline() returns ok == false.
2 — A handler has 800 ms left. It calls context.WithTimeout(ctx, 5*time.Second) for a query. How long can the query run? Must-know
Answer
Answer: At most 800 ms. WithDeadline (and so WithTimeout) never extends a parent's deadline; if the parent's is sooner, the child is equivalent to a WithCancel of the parent.
3 — Why does vet complain about ctx, _ := context.WithTimeout(parent, d) even if the code works? Must-know
Answer
Answer: The discarded cancel func means the child stays registered in its parent and its timer stays armed until the deadline or until the parent ends. lostcancel reports "the cancel function ... should be called, not discarded, to avoid a context leak".
4 — You call cancel(ErrShutdown) on a WithCancelCause context. What do ctx.Err() and context.Cause(ctx) return, and for a grandchild? Good to know
Answer
Answer: ctx.Err() is context.Canceled; context.Cause(ctx) is ErrShutdown. A grandchild created before the cancel inherits both: Err() is Canceled, Cause is ErrShutdown.
5 — Your worker receives a canceled context but still processes all 10,000 items. Why? Must-know
Answer
Answer: Cancellation is cooperative. The loop never calls ctx.Err() or selects on ctx.Done(), and process does not pass ctx to anything that blocks. Add a check between items.
6 — When exactly is r.Context() canceled in a net/http handler, and what does Server.Shutdown do to it? Important
Answer
Answer: When the client's connection closes, when an HTTP/2 stream is reset, or when ServeHTTP returns. Shutdown does not cancel it; it stops accepting and waits for active requests. To signal them, derive BaseContext from a context you cancel yourself.
7 — Why does gRPC send a timeout rather than an absolute deadline to the next server? Important
Answer
Answer: Clocks on the two hosts may differ. Sending the remaining duration, with elapsed time already subtracted, makes the receiving side compute its own local deadline and shields the system from clock skew.
8 — With pgx v5 defaults, what happens to the connection when the ctx of a running query is canceled? Good to know
Answer
Answer: The default DeadlineContextWatcherHandler sets a deadline on the net.Conn, so the call returns and that connection is broken and closed. To ask PostgreSQL to cancel the statement and keep the connection, configure CancelRequestContextWatcherHandler.
9 — Why is type key string; ctx = context.WithValue(ctx, key("user"), u) still weaker than type userKey struct{}? Important
Answer
Answer: Both are distinct from a bare string, but an exported or reused string-based type invites other code in the package (or a copy-paste) to produce an equal key. An unexported struct{} type has exactly one value, cannot be constructed elsewhere, and does not allocate when boxed into any.
10 — You need to write an audit row after the response. Why not go audit(r.Context()), and why not go audit(context.Background())? Important
Answer
Answer: r.Context() is canceled when the handler returns, so the write usually fails with context canceled. Background() loses the request id and trace and has no bound. Use context.WithoutCancel(r.Context()) plus a WithTimeout, in a goroutine whose lifetime shutdown waits for (or write an outbox row in the main transaction).
11 — A retry wrapper sees context.DeadlineExceeded. How does it decide whether to retry? Important
Answer
Answer: Check its own ctx: if ctx.Err() != nil the overall budget is spent and a retry cannot finish, so stop. If only a per-attempt child timed out and the call is idempotent, retry with backoff. Never retry context.Canceled.
12 — What changed in Go 1.24 for tests, and why does it matter for goroutines started by a test? Good to know
Answer
Answer: t.Context() returns a context canceled after the test completes and before cleanup functions run. Goroutines and servers started with it are told to stop when the test ends, instead of running into the next test.
Glossary
| Term | Meaning |
|---|---|
context.Context | Interface carrying a cancellation signal, a deadline and request-scoped values |
Done | Method returning a channel closed when the context is canceled |
Err | Method returning nil, Canceled or DeadlineExceeded |
Deadline | Method returning the time by which work should be canceled, and whether one is set |
Value | Method returning the value for a key, walking up the parents |
context.Background | Empty root context: never canceled, no deadline, no values |
context.TODO | Empty root used as a marker where a real ctx is not yet available |
Cancel func (CancelFunc) | Function returned by With* that cancels the child; idempotent, does not wait |
defer cancel | Idiom that guarantees the cancel func runs when the function returns |
lostcancel | go vet analyzer reporting cancel funcs that are discarded or not called on all paths |
WithCancel | Derives a child with its own cancel func |
WithTimeout | Derives a child canceled after a duration |
WithDeadline | Derives a child canceled at a time, never later than the parent's deadline |
WithCancelCause | Like WithCancel but the cancel func records an error as the cause (Go 1.20) |
context.Cause | Returns the recorded cause, or Err() when none was given |
WithTimeoutCause / WithDeadlineCause | Deadline that records a cause when it fires (Go 1.21) |
WithoutCancel | Child that keeps values but is never canceled and has no deadline (Go 1.21) |
context.AfterFunc | Registers a function to run in its own goroutine after cancellation (Go 1.21) |
context.Canceled | Error context canceled: someone called cancel |
context.DeadlineExceeded | Error context deadline exceeded: a deadline passed; Timeout() is true |
| Cooperative cancellation | Cancellation that takes effect only where the code checks for it |
| Propagation | Passing the same ctx (or a child) down every call and across goroutines |
| First parameter ctx | Convention that ctx is the first parameter and named ctx |
| Deadline propagation | Forwarding the remaining budget to the next service as a duration |
| gRPC deadline | Client-set deadline sent as grpc-timeout; expiry gives DEADLINE_EXCEEDED |
grpc-timeout | gRPC request header with the remaining time and a unit letter |
NewRequestWithContext | Builds an outgoing http.Request whose whole lifetime is bound to ctx |
r.Context | Server request context, canceled on client disconnect or handler return |
| Client disconnect | The client closing the connection or resetting the stream |
BaseContext / ConnContext | http.Server hooks that set the root context per listener and per connection |
http.TimeoutHandler | Handler wrapper that answers 503 after a limit and cancels the inner ctx |
ErrHandlerTimeout | http: Handler timeout, returned to writes after TimeoutHandler fired |
QueryContext | database/sql query bound to ctx; plain Query uses Background |
BeginTx | Starts a transaction rolled back if its ctx is canceled before commit |
| pgx context watcher | pgx mechanism that reacts to ctx cancel by a socket deadline (default) or a CancelRequest |
| CancelRequest | PostgreSQL protocol message that asks the server to cancel a running statement |
statement_timeout | PostgreSQL server-side statement limit, SQLSTATE 57014 when hit |
| Context value | A key/value pair stored with WithValue |
| Request-scoped | Data that belongs to one request and dies with it |
| Unexported key type | Package-private type used as a ctx key so no other package can collide |
| Request id | Identifier of one request, echoed in logs and headers |
| Principal | The authenticated caller of a request |
| Trace span | Unit of a distributed trace, carried in ctx by OpenTelemetry |
| slog context | Passing ctx to slog via InfoContext so a handler can read request values |
| Linked list lookup | Value walking parent pointers one node at a time |
errgroup.WithContext | Group whose derived ctx is canceled by the first error or by Wait |
| Goroutine leak | A goroutine blocked forever on an event that will not happen |
| Timer leak | Timers kept alive by never stopping them (fixed for unreferenced timers in Go 1.23) |
| Fire-and-forget | Work started after the response without the caller waiting for it |
| Retry classification | Deciding retry, log level and metric label from the error and ctx state |
t.Context | Test context canceled after the test completes, before cleanups (Go 1.24) |
| context.Background in handler | The anti-pattern of starting context.Background() inside a request path |
| Laravel Context facade | Laravel 13 API that shares request data with logs and queued jobs; no cancellation |
References
- Sameer Ajmani, "Go Concurrency Patterns: Context", The Go Blog, 29 July 2014: https://go.dev/blog/context
- Jean Barkhuysen, Matt T. Proud, "Contexts and structs", The Go Blog, 24 February 2021: https://go.dev/blog/context-and-structs
contextpackage source and doc comments (Go 1.27): https://go.dev/src/context/context.gonet/httpRequest.Context,NewRequestWithContext: https://go.dev/src/net/http/request.gonet/httpTimeoutHandler,BaseContext,ConnContext: https://go.dev/src/net/http/server.godatabase/sqlQueryContext,BeginTx: https://go.dev/src/database/sql/sql.golog/slogHandlerinterface: https://go.dev/src/log/slog/handler.gotestingT.Context: https://go.dev/src/testing/testing.golostcancelanalyzer: https://go.dev/src/cmd/vendor/golang.org/x/tools/go/analysis/passes/lostcancel/lostcancel.go- Go 1.7 release notes (context in the standard library, vet
-lostcancel): https://go.dev/doc/go1.7 - Go 1.20 release notes (
WithCancelCause,Cause): https://go.dev/doc/go1.20 - Go 1.21 release notes (
WithoutCancel,AfterFunc,WithDeadlineCause,WithTimeoutCause): https://go.dev/doc/go1.21 - Go 1.23 release notes (timer garbage collection,
httptest.NewRequestWithContext): https://go.dev/doc/go1.23 - Go 1.24 release notes (
T.Context,B.Context): https://go.dev/doc/go1.24 - Go 1.25 release notes: https://go.dev/doc/go1.25
- Go Code Review Comments, "Contexts": https://go.dev/wiki/CodeReviewComments
- Effective Go: https://go.dev/doc/effective_go
- Go FAQ: https://go.dev/doc/faq
- The Go Memory Model: https://go.dev/ref/mem
- The Go Programming Language Specification: https://go.dev/ref/spec
- "Go Concurrency Patterns: Pipelines and cancellation", The Go Blog: https://go.dev/blog/pipelines
golang.org/x/sync/errgroupsource: https://github.com/golang/sync/blob/master/errgroup/errgroup.go- gRPC, "Deadlines": https://grpc.io/docs/guides/deadlines/
- gRPC, "Cancellation": https://grpc.io/docs/guides/cancellation/
- grpc-go
status.FromContextError: https://raw.githubusercontent.com/grpc/grpc-go/master/status/status.go - grpc-go status error format: https://raw.githubusercontent.com/grpc/grpc-go/master/internal/status/status.go
- pgx: https://github.com/jackc/pgx
- pgx
pgconncontext watcher handlers: https://raw.githubusercontent.com/jackc/pgx/master/pgconn/pgconn.go - pgx
pgconndefault config: https://raw.githubusercontent.com/jackc/pgx/master/pgconn/config.go - pgx
errTimeout: https://raw.githubusercontent.com/jackc/pgx/master/pgconn/errors.go - PostgreSQL, client connection defaults (
statement_timeout): https://www.postgresql.org/docs/current/runtime-config-client.html - PostgreSQL, server signaling functions (
pg_cancel_backend): https://www.postgresql.org/docs/current/functions-admin.html - PostgreSQL, message flow (cancel requests): https://www.postgresql.org/docs/current/protocol-flow.html
- PHP manual, connection handling: https://www.php.net/manual/en/features.connection-handling.php
- Laravel 13, Context: https://laravel.com/docs/13.x/context
- Go 1.8 release notes (
database/sqlcontext support): https://go.dev/doc/go1.8 - lib/pq
watchCancel/sendCancelRequest: https://raw.githubusercontent.com/lib/pq/master/conn.go - go-sql-driver/mysql
watchCancel/cleanup: https://raw.githubusercontent.com/go-sql-driver/mysql/master/connection.go - golangci-lint linters list (
containedctx,contextcheck,sloglint): https://golangci-lint.run/docs/linters/ - Gin
Context.Copy: https://raw.githubusercontent.com/gin-gonic/gin/master/context.go