My account

The context package

The context package tells running work "you are not needed anymore". A tree of contexts carries cancellation and deadlines from a request to all its child work. If you understand WithCancel and WithTimeout, calling cancel, passing r.Context to the database, listening to ctx.Done, the cause of a cancellation, WithoutCancel and the right use of values, you can answer most interview questions.

Not reviewedWritten with AI helpReading time: 18 minOnline shop exampleGo 1.25 code

Author: bezzad

Contents

The problem: work that nobody waits for

The order service of our shop has these reports:

  1. The “My orders” page sometimes takes 10 seconds. Users close the page, but the database still runs their queries.
  2. The payment provider sometimes does not answer. The payment request stays open for minutes and holds a connection and a goroutine.
  3. The number of goroutines in the service grows every day, and memory is never freed.

All three have one root: work goes on even though nobody waits for its result anymore. The context package was made for exactly this.

What does a context do?

A context carries three things from the caller down to the lower work:

  1. A cancel signal: “not needed anymore, stop.”
  2. A deadline: “finish by this time, or stop.”
  3. Request-scoped values: like a request id for the logs.

The context.Context type is an interface with four methods: Done returns a channel that is closed on cancel, Err says why it was cancelled, Deadline returns the deadline, and Value finds a value.

The context tree

Every context is made from a parent. The root is usually context.Background. The HTTP server makes a context for each request, and we make children from it:

ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
defer cancel()
  1. Cancellation goes down. When a context is cancelled, all its children are cancelled too.
  2. Cancellation never goes up. Cancelling a child has no effect on its parent or on sibling branches.
  3. A child can not extend the deadline. If the parent has 1 second left, a child with 5 seconds is still cancelled after 1 second.
App rootcontext.Background()HTTP requestr.Context()WithTimeout(ctx, 2s)Time is upWithValue(ctx, reqID)Stays aliveDatabase queryCanceledPayment gatewayCanceledWrite a logKeeps goingCancel goes from a parent to all its children, never up and never sideways.
The two-second deadline ends, and all its children, the database query and the payment request, are cancelled. The parent and the side branch stay alive.

Constructors and calling cancel

There are four main constructors:

Constructor When it is cancelled Example use
WithCancel when you call cancel stopping several workers together
WithTimeout after a duration, or with cancel a 2-second limit for the payment provider
WithDeadline at a given time, or with cancel finishing a nightly job by a fixed time
WithValue never by itself storing the request id
  1. The first three also return a cancel function. Always call it, usually with defer right after you create the context.
  2. If cancel is not called, the child context and its link to the parent stay in memory until the parent is cancelled or the timer fires. The go vet tool (the lostcancel check) finds this mistake.
  3. Calling cancel after the work is done is safe. Calling it several times is fine too.

Rules of use

  1. The first parameter of every function that does I/O or may take time is a context named ctx.
  2. Do not store a context in a struct. Pass it on each call. Each request has its own context.
  3. Never pass nil. If you do not know yet which context is right, use context.TODO so you can find it later.
  4. In a handler, start from r.Context, not from context.Background.

From the HTTP request to the database

Our first bug was this: the handler used context.Background for the query. The fix is to carry the request’s context all the way to the database:

func (h *Handler) ListOrders(w http.ResponseWriter,
	r *http.Request) {
	ctx, cancel := context.WithTimeout(r.Context(),
		3*time.Second)
	defer cancel()

	orders, err := h.store.Orders(ctx, r.PathValue("user"))
	if errors.Is(err, context.DeadlineExceeded) {
		http.Error(w, "try again", http.StatusServiceUnavailable)
		return
	}
	if err != nil {
		http.Error(w, "server error",
			http.StatusInternalServerError)
		return
	}
	writeJSON(w, orders)
}

func (s *Store) Orders(ctx context.Context,
	user string) ([]Order, error) {
	rows, err := s.db.QueryContext(ctx,
		"SELECT id FROM orders WHERE user_id = $1", user)
	if err != nil {
		return nil, fmt.Errorf("query orders: %w", err)
	}
	defer rows.Close()
	// scan rows ...
}
  1. When the user closes the page, the server sees the closed connection and cancels the request context.
  2. Because the query has the same context, the database driver stops the query and the connection goes back to the pool.
  3. The 3-second limit stops queries that take too long even while the user is waiting.
User's browserOrders handlerDatabaseGET /ordersQueryContext(ctx)Closes the pageConnection closedContext canceled, query stopscontext.CanceledDB connection is free again
The user closes the page. The request context is cancelled, the database query stops, and the database connection is freed.

Listening for cancellation

Standard packages like database/sql and net/http listen to the context themselves. But in your own code, you must check it yourself.

In a long loop, check ctx.Err before each step:

func exportAll(ctx context.Context, ids []int64) error {
	for _, id := range ids {
		if err := ctx.Err(); err != nil {
			return err // stop early: cancelled or timed out
		}
		if err := exportOne(ctx, id); err != nil {
			return err
		}
	}
	return nil
}

In a goroutine that reads from a channel, put ctx.Done next to the channel in a select:

func worker(ctx context.Context, jobs <-chan Order) {
	for {
		select {
		case <-ctx.Done():
			return
		case o, ok := <-jobs:
			if !ok {
				return
			}
			process(ctx, o)
		}
	}
}

After cancellation, the Err method returns one of two errors:

  1. The context.Canceled error means someone called cancel, or the user left.
  2. The context.DeadlineExceeded error means the deadline passed.

The cause of a cancellation

Sometimes you want to know why it was cancelled. Since Go 1.20 the WithCancelCause function, and since Go 1.21 the WithTimeoutCause function, take a cause error. The context.Cause function returns it:

var errPaymentSlow = errors.New("payment provider too slow")

func charge(ctx context.Context, orderID int64) error {
	ctx, cancel := context.WithTimeoutCause(ctx,
		2*time.Second, errPaymentSlow)
	defer cancel()

	err := callProvider(ctx, orderID)
	if errors.Is(err, context.DeadlineExceeded) {
		err = context.Cause(ctx) // errPaymentSlow
	}
	return err
}

Now the log says “payment provider too slow” instead of “context deadline exceeded”. The Err method still returns DeadlineExceeded, so old code keeps working.

Goroutine leaks

This is our third bug. Someone built a timeout with a goroutine and a channel:

// Bad: the goroutine can block forever
func quote(ctx context.Context, o Order) (string, error) {
	ch := make(chan string)
	go func() {
		ch <- slowCarrierQuote(o) // no ctx
	}()
	select {
	case ref := <-ch:
		return ref, nil
	case <-ctx.Done():
		return "", ctx.Err()
	}
}
  1. When the deadline passes, the function returns, and nobody reads from ch anymore.
  2. The channel is unbuffered, so the goroutine waits on its send forever.
  3. Go never collects a blocked goroutine. Its memory is never freed, and their number grows every day.

Fix one: give the context to the work itself, so the work stops. Fix two, if the library does not take a context: make the channel with one free slot, so even a late send succeeds and the goroutine ends.

Bad: unbuffered channelGood: room for one valueThe callerreturns when time is upchan stringNobody readsThe goroutine waits foreverch <- refIts memory is never freedThe callerreturns when time is upmake(chan result, 1)The goroutine sends and endsch <- resIts memory is freed
Unbuffered channel: the function returns and the goroutine waits forever. Channel with one free slot: the goroutine puts its answer and ends.

Work after the response: WithoutCancel

Sometimes a short job is needed after we answer the user, like writing an audit log. If you pass the request context, it is cancelled when the handler ends. If you pass context.Background, you lose the request id and the other values.

Since Go 1.21 the WithoutCancel function solves this. It keeps the values, but not the parent’s cancellation and deadline:

func audit(ctx context.Context, o Order) {
	ctx = context.WithoutCancel(ctx) // keeps values only
	go func() {
		ctx, cancel := context.WithTimeout(ctx,
			10*time.Second)
		defer cancel()
		slog.InfoContext(ctx, "audit", "order", o.ID,
			"request", RequestID(ctx))
	}()
}
  1. Always add a new deadline to it, or the background work has no limit at all.
  2. For important work (like sending a receipt email), do not rely on a goroutine. If the pod shuts down, the work is lost. Write it to the database or to a queue.

The same version added the AfterFunc function. It registers a function that runs after a context is cancelled. It is useful to connect cancellation to APIs that do not know about context.

Values in a context

The WithValue function is for data that belongs to the request itself and crosses API boundaries, like a request id or the signed-in user:

type ctxKey int

const requestIDKey ctxKey = 0

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

func RequestID(ctx context.Context) string {
	id, _ := ctx.Value(requestIDKey).(string)
	return id
}
  1. Make the key from a private type, not a string. This stops keys from different packages from clashing.
  2. Write two helper functions, so the rest of the code never sees the key.
  3. Do not put normal parameters in a context, like a database connection, config or a logger. Make them explicit function parameters or struct fields. A context value is hidden, and the compiler does not check its type.

Common mistakes

Mistake Result The right way
Using context.Background in a handler Work goes on after the user leaves. Start from r.Context.
Not calling cancel Resources stay until the parent is cancelled or the timer fires. A deferred cancel right after creation
Storing a context in a struct All requests share one context. Pass it as the first parameter.
Passing nil A panic inside libraries Use context.TODO.
A long loop that never checks ctx Cancellation has no effect. Check ctx.Err or ctx.Done.
An unbuffered channel for a timeout A goroutine leak Give the context to the work, or a buffer of 1.
Passing the request context to background work The work is cancelled when the handler ends. WithoutCancel plus a new deadline
Putting config or a logger in a context Hidden dependencies with no type check An explicit parameter or a struct field

Summary in seven lines

  1. A context carries cancellation, a deadline and request values down to the lower work.
  2. Cancellation goes from a parent to all its children, but never up.
  3. Every WithCancel or WithTimeout has a cancel that you must always call with defer.
  4. In a handler, start from r.Context and carry ctx to the database and the HTTP client.
  5. In your own code, listen to ctx.Done and ctx.Err, and use Cause for a better message.
  6. A goroutine that waits on an unbuffered channel leaks. Stop the work with the context.
  7. WithoutCancel is for short work after the response. Context values are only for request data.

Done reading this lesson?Mark it as finished so it shows in your lessons list and report card.