Thuta Learning
Go
AdvancedProgrammingBeginner

Context, Timeouts & Cancellation

GoLesson 2240 min

What you'll walk away with

  • Derive child contexts from context.Background() with WithCancel and WithTimeout, and explain the parent/child link
  • Wait on ctx.Done() in a select and tell context.Canceled from context.DeadlineExceeded via ctx.Err()
  • Explain why defer cancel() belongs right after every context you create
  • Record why work stopped with WithCancelCause and read it back with context.Cause
  • Pass ctx as the first parameter and write code that actually checks for cancellation

Explain it simply

Context in plain language

A context.Context is a signal line that can say 'stop now' to a piece of work. When a request comes in, you create a context and hand it to every function called for that request. When the user closes the page or a time limit runs out, the line is pulled, and every piece of work attached to it learns that it should stop.

Compare it to taking a taxi. Saying 'get me to the airport within 30 minutes or I will get out' is a deadline. Saying 'stop here' halfway is a cancel. The car only stops if the driver listens, though: a context never forces work to stop, the code itself has to check the signal and stop.

Problem → Why → Solution

The problem: work nobody is waiting for any more

A report page runs a database query that takes about thirty seconds. After five seconds the user gets bored, closes the tab and hits refresh ten times. On the server, ten queries whose results nobody will ever read keep holding database connections, and every other user's requests slow down.

report.go
func reportHandler(w http.ResponseWriter, r *http.Request) {
	// r.Context() is ignored: the query keeps running even after
	// the client has disconnected
	rows, err := db.Query("SELECT customer, SUM(total) FROM orders GROUP BY 1")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	defer rows.Close()
	// ...
}

Why a context is needed

You cannot kill a goroutine from the outside; it stops only when it decides to. So Go needs a standard way to pass the news 'it is time to stop' down the call chain. net/http cancels r.Context() when the client disconnects, and database/sql's QueryContext listens for that signal. The two only connect if you pass the context along.

Core concept: the context tree, Done, Err and Cause

Contexts form a tree. The root is context.Background(), and WithCancel(parent), WithTimeout(parent, d) and WithDeadline(parent, t) each return a new child context plus a cancel function. Cancelling a parent cancels all of its descendants; cancelling a child never touches the parent. That is why you can safely add a shorter timeout for one database call underneath the context of the whole request.

ctx.Done() returns a channel that is closed when the context ends, so you can wait on it in a select alongside other channels. ctx.Err() is nil while the context is alive, context.Canceled after a cancel and context.DeadlineExceeded after the deadline passes. A context stops nothing on its own: cancellation is cooperative, so it only works if the function waits on Done, checks Err, or passes ctx on to an API that does, such as QueryContext or NewRequestWithContext.

ConstructorWhen the context ends
WithCancel(parent)cancel() is called, or the parent ends
WithTimeout(parent, d)d elapses, cancel() is called, or the parent ends
WithDeadline(parent, t)the clock reaches t (otherwise like WithTimeout)
WithCancelCause(parent)cancel(err) is called; context.Cause returns err

Write defer cancel() on the line right after you create a context. Cancel stops the timer and removes the child's reference from its parent, so it must run even when the work finishes early; skip it and those resources live until the parent ends. go vet's lostcancel check warns about a forgotten cancel. Calling cancel more than once is safe: every call after the first does nothing.

ctx.Err() only says 'canceled', never why. WithCancelCause(parent) returns a cancel function that takes an error, so cancel(err) records the reason for stopping. ctx.Err() still reports context.Canceled, but context.Cause(ctx) returns that err. For a context with no recorded cause, context.Cause returns the same value as ctx.Err().

See contexts as a tree that grows downward
  1. Derive a context from Background()
  2. Immediately defer cancel()
  3. Pass ctx as the first parameter
  4. Workers select on ctx.Done()
  5. Return ctx.Err() or context.Cause

Cancellation flows down the tree only; a child never stops its parent.

General pattern

go
ctx, cancel := context.WithTimeout(parent, limit)
defer cancel()

func doWork(ctx context.Context, input Input) (Output, error) {
	select {
	case out := <-resultOf(input):
		return out, nil
	case <-ctx.Done():
		return Output{}, ctx.Err() // Canceled or DeadlineExceeded
	}
}

Derive the context from a parent and defer cancel at once. The working function takes ctx as its first parameter, waits for either its result or ctx.Done(), whichever comes first, and returns ctx.Err() when the context ends.

Worked example: checking a context that is already cancelled

This is the smallest form of context cancellation. The context is created with WithCancel and cancel() is called before the select, so the Done channel is already closed. The select therefore picks the Done case and prints context canceled. Remove the cancel() line and Done is still open, so the default case prints working instead: a select with default asks 'have I been told to stop?' without waiting.

go
package main

import (
    "context"
    "fmt"
)

func main() {
    ctx, cancel := context.WithCancel(context.Background())
    cancel()
    select {
    case <-ctx.Done(): fmt.Println(ctx.Err())
    default: fmt.Println("working")
    }
}

Code breakdown

  1. Derive a cancellable contextctx, cancel := context.WithCancel(context.Background())

    Background() is the root context and is never cancelled. WithCancel returns a child of it together with the cancel function that ends that child.

  2. Cancel itcancel()

    Closes the Done channel and sets Err to context.Canceled. Here it is called straight away; in real code you write defer cancel() and some other goroutine or event calls it earlier.

  3. Done is closed, so this case runscase <-ctx.Done(): fmt.Println(ctx.Err())

    A receive from a closed channel succeeds immediately, so this case is ready. The string form of ctx.Err() is context canceled.

  4. Non-blocking fallbackdefault: fmt.Println("working")

    If the context is still alive, default runs and the select does not wait. Loops use this shape, or if ctx.Err() != nil, to ask 'should I keep going?' on every iteration.

You should see
context canceled

WithTimeout: putting a time limit on a slow dependency

query waits for either its result or ctx.Done(), whichever comes first. Every call to lookup creates a fresh context with an 80ms timeout and cleans it up with defer cancel(); putting the defer in a helper instead of directly in a loop makes cancel run at the end of each call. The 10ms query finishes in time and the 200ms query runs past the deadline.

timeout.go
package main

import (
	"context"
	"errors"
	"fmt"
	"time"
)

// query pretends to talk to a database that needs cost to answer.
func query(ctx context.Context, cost time.Duration) (string, error) {
	select {
	case <-time.After(cost):
		return "3 rows", nil
	case <-ctx.Done():
		return "", fmt.Errorf("query: %w", ctx.Err())
	}
}

func lookup(cost time.Duration) {
	ctx, cancel := context.WithTimeout(context.Background(), 80*time.Millisecond)
	defer cancel() // release the timer even when query finishes early

	rows, err := query(ctx, cost)
	if errors.Is(err, context.DeadlineExceeded) {
		fmt.Println(cost, "->", err)
		return
	}
	fmt.Println(cost, "->", rows)
}

func main() {
	lookup(10 * time.Millisecond)
	lookup(200 * time.Millisecond)
}

The output is 10ms -> 3 rows and 200ms -> query: context deadline exceeded. query wraps ctx.Err() with %w, so err == context.DeadlineExceeded would be false, while errors.Is follows the wrap chain and returns true.

WithCancelCause: recording why work stopped

In the program below the parent context is cancelled with the cause ErrTabClosed. The child is derived from the parent, so it is cancelled automatically: both report context canceled from Err, while Cause reports user closed the tab.

cause.go
package main

import (
	"context"
	"errors"
	"fmt"
)

var ErrTabClosed = errors.New("user closed the tab")

func main() {
	ctx, cancel := context.WithCancelCause(context.Background())
	child, stop := context.WithCancel(ctx) // derived from ctx
	defer stop()

	cancel(ErrTabClosed) // cancelling the parent also cancels the child

	<-child.Done()
	fmt.Println("child err:  ", child.Err())
	fmt.Println("parent err: ", ctx.Err())
	fmt.Println("cause:      ", context.Cause(ctx))
	fmt.Println("child cause:", context.Cause(child))
	fmt.Println(errors.Is(context.Cause(ctx), ErrTabClosed))
}

Notice that the child's cause is also user closed the tab: a context cancelled because of its parent inherits the parent's cause. Logging context.Cause(ctx) instead of ctx.Err() gives you a meaningful reason rather than the bare word canceled.

Passing the context through an HTTP handler

To fix the handler from the problem section, use r.Context() as the parent, add a timeout for the query and pass the result to QueryContext. Now the query stops when the client disconnects or after two seconds, whichever happens first. This snippet needs a real database, so it is not run here.

report.go
func reportHandler(w http.ResponseWriter, r *http.Request) {
	ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
	defer cancel()

	rows, err := db.QueryContext(ctx, "SELECT customer, SUM(total) FROM orders GROUP BY 1")
	if errors.Is(err, context.DeadlineExceeded) {
		http.Error(w, "report took too long", http.StatusGatewayTimeout)
		return
	}
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	defer rows.Close()
	// ...
}

In real projects

Context in real projects

In Go server code almost every function that does I/O takes ctx context.Context as its first parameter. A request's context flows in one unbroken line from the handler to the database, the cache and outgoing API calls, and when it ends anywhere, everything downstream stops.

  • Incoming requests: net/http's Request.Context() is cancelled when the client connection closes or when ServeHTTP returns.
  • Outgoing calls: a request built with http.NewRequestWithContext is aborted when its context ends, and database/sql's QueryContext and ExecContext behave the same way.
  • Between services: frameworks such as gRPC carry the deadline from one service to the next, so no service waits longer than the time that is left.
  • Graceful shutdown: signal.NotifyContext gives you a context that is cancelled on Ctrl+C, and server.Shutdown(ctx) uses such a context to wait for in-flight requests within a time limit.

Common mistakes

Common mistakes with context

Never calling cancel

Throwing cancel away, as in ctx, _ := context.WithTimeout(...), leaves the timer and the parent's reference alive until the deadline even after the work is done. Do that on every request and memory creeps upward. go vet flags it with the cancel function is not used; write defer cancel() on the very next line.

Accepting ctx and never checking it

If func work(ctx context.Context) contains nothing but a loop with time.Sleep, it keeps running to the end of the loop even after the timeout. Context is cooperative: check ctx.Err() on every loop iteration, and where you wait, use a select that also waits on ctx.Done() instead of a bare sleep.

Breaking the chain with context.Background() mid-call

When a helper inside a handler creates its own context.Background() instead of receiving r.Context(), the queries below it keep running after the client leaves. Pass ctx down from above, and keep Background() for main, tests and background jobs that have no request. If you are not yet sure which context to use, pass context.TODO() as a placeholder, never nil.

Comparing a wrapped error with ==

Once an error has been wrapped, as in fmt.Errorf("query: %w", ctx.Err()), err == context.DeadlineExceeded is false. Always use errors.Is(err, context.DeadlineExceeded).

Best practices

Best practices

  • Make ctx context.Context the first parameter of a function and never store it in a struct field.
  • Write defer cancel() on the line after every context you create.
  • Use context.WithValue only for request-scoped data such as a request ID, never as a way to pass optional parameters.
  • Log context.Cause(ctx) rather than ctx.Err() so the reason for stopping is visible.

Mini challenge

Mini challenge: stopping an import with a cause

Write importAll, which imports a list of records. It checks the context at the start of every loop turn, and when it meets an empty record it cancels the context with a cause that wraps ErrBadRecord. Also write slowStep, which respects a timeout context.

  • main creates the context with WithCancelCause and writes defer cancel(nil)
  • importAll checks ctx.Err() at the start of every loop turn and returns how many records it imported
  • For an empty record, pass ErrBadRecord as the cause, wrapped with fmt.Errorf and %w
  • slowStep waits on time.After(d) or ctx.Done() with a select and returns context.Cause(ctx)
import.go
package main

import (
	"context"
	"errors"
	"fmt"
	"time"
)

var ErrBadRecord = errors.New("bad record")

// importAll imports records until it is done or ctx is cancelled.
func importAll(
	ctx context.Context, cancel context.CancelCauseFunc, records []string,
) int {
	// TODO: loop over records; stop if ctx.Err() != nil
	// TODO: on an empty record, cancel with a cause wrapping ErrBadRecord
	// TODO: return how many records were imported
	return 0
}

// slowStep waits for d unless ctx ends first.
func slowStep(ctx context.Context, d time.Duration) error {
	// TODO: select on time.After(d) and ctx.Done()
	return nil
}

func main() {
	// TODO: WithCancelCause + defer cancel(nil); import 4 records where the
	//       third is ""; print the count, ctx.Err() and context.Cause(ctx)
	// TODO: WithTimeout(50ms) + defer; call slowStep with 200ms and print
	//       the error and errors.Is(err, context.DeadlineExceeded)
	fmt.Println("todo")
}

Expected: It prints imported: 2, err: context canceled, cause: record 3: bad record, bad record? true and then slow step: context deadline exceeded true.

Show hint

After cancel(fmt.Errorf("record %d: %w", n, ErrBadRecord)), ctx.Err() is no longer nil on the next loop turn, so the loop stops. For a timeout context, context.Cause returns context.DeadlineExceeded.

Show solution
import.go
package main

import (
	"context"
	"errors"
	"fmt"
	"time"
)

var ErrBadRecord = errors.New("bad record")

// importAll processes records until it finishes, hits a bad record, or
// ctx is cancelled. It returns how many records it imported.
func importAll(
	ctx context.Context, cancel context.CancelCauseFunc, records []string,
) int {
	done := 0
	for _, r := range records {
		if err := ctx.Err(); err != nil {
			return done // stop before starting more work
		}
		if r == "" {
			cancel(fmt.Errorf("record %d: %w", done+1, ErrBadRecord))
			continue // the next loop turn sees ctx.Err() and stops
		}
		done++
	}
	return done
}

// slowStep waits for d or for ctx, whichever comes first.
func slowStep(ctx context.Context, d time.Duration) error {
	select {
	case <-time.After(d):
		return nil
	case <-ctx.Done():
		return context.Cause(ctx)
	}
}

func main() {
	ctx, cancel := context.WithCancelCause(context.Background())
	defer cancel(nil)
	n := importAll(ctx, cancel, []string{"ada", "linus", "", "grace"})
	fmt.Println("imported:", n)
	fmt.Println("err:", ctx.Err())
	fmt.Println("cause:", context.Cause(ctx))
	fmt.Println("bad record?", errors.Is(context.Cause(ctx), ErrBadRecord))

	tctx, tcancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
	defer tcancel()
	err := slowStep(tctx, 200*time.Millisecond)
	fmt.Println("slow step:", err, errors.Is(err, context.DeadlineExceeded))
}

Quick quiz 1 / 3

You create child, stop := context.WithCancel(parent) and call stop(). What is parent.Err()?

Quick quiz 2 / 3

func work(ctx context.Context) { for i := 0; i < 10; i++ { time.Sleep(100 * time.Millisecond) } } is called with a 150ms timeout context. How long does work run?

Quick quiz 3 / 3

After ctx, cancel := context.WithCancelCause(bg), you call cancel(ErrQuota). What do ctx.Err() and context.Cause(ctx) return?

What to remember

  • Contexts form a tree derived from Background(), and cancellation flows only downward.
  • Wait on ctx.Done() in a select; ctx.Err() returns Canceled or DeadlineExceeded, and wrapped errors are checked with errors.Is.
  • Write defer cancel() right after creating every context; go vet warns when you forget.
  • Cancellation is cooperative: functions must check ctx or pass it to an API that accepts it.
  • WithCancelCause and context.Cause record why work stopped without changing what ctx.Err() reports.

Go Concurrency Patterns: Context — Go

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.