SyntaxPilot
Courses/Go Programming/Lesson 51
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Go Programming · Lesson 51 of 89

context: cancellation, deadlines and values

context.Context interfacecontext.Backgroundcontext.TODOWithCancelWithTimeoutWithDeadlineWithValue and typed keysDone channelErr (Canceled, DeadlineExceeded)cancellation propagation treeWithCancelCause and context.CauseAfterFuncWithoutCancelcontext rules (first parameter, never store in structs, always call cancel)

These are the notes for Go episode 51. A customer cancels an order, but two cooks keep cooking all the way to "plated the dish": Go has no way to stop a goroutine from outside. A done channel works, but real code also needs a deadline and an order id, passed through every function. You invent context.Context, one value that carries a stop signal, a deadline and values. Then WithCancel, WithTimeout and WithDeadline (context deadline exceeded), the cancellation tree, the go vet warning for a forgotten cancel, WithValue and why string keys collide, WithCancelCause, Cause, AfterFunc and WithoutCancel, a crash from a nil context, and the rules from the context package docs.

All outputs and errors here are from real runs (Go 1.24.7, linux/amd64, a machine with 2 CPUs). Timings and the order of some lines change between runs.

Facts and sources

From the official package documentation, pkg.go.dev/context:

  • "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."
  • "Use context Values only for request-scoped data that transits processes and APIs".
  • "The same Context may be passed to functions running in different goroutines".
  • Canceled is errors.New("context canceled"), "returned by Context.Err when the context is canceled for some reason other than its deadline passing." DeadlineExceeded is returned "when the context is canceled due to its deadline passing" (its message is context deadline exceeded, as the runs below show).
  • WithCancelCause and Cause were added in Go 1.20; AfterFunc, WithoutCancel, WithDeadlineCause and WithTimeoutCause in Go 1.21.
  • WithValue: "The provided key must be comparable and should not be of type string or any other built-in type".
  • "Failing to call the CancelFunc leaks the child and its children until the parent is canceled." "The go vet tool checks that CancelFuncs are used on all control-flow paths."

The problem: work that won't stop

At Raju's restaurant In Go
an order for two dishes a request: one piece of work someone asked for
Raju and Asha each cook one two goroutines
the customer walks out the result is no longer needed
the cooks keep cooking the goroutines keep running
"stop, order cancelled!" reaching every cook cancellation
package main

import (
    "fmt"
    "sync"
    "time"
)

func cook(name string, wg *sync.WaitGroup) {
    defer wg.Done()
    for step := 1; step <= 4; step++ {
        time.Sleep(30 * time.Millisecond) // one cooking step
        fmt.Println(name, "finished step", step)
    }
    fmt.Println(name, "plated the dish")
}

func main() {
    var wg sync.WaitGroup
    wg.Add(2)
    go cook("Raju", &wg)
    go cook("Asha", &wg)
    time.Sleep(50 * time.Millisecond)
    fmt.Println("--- customer cancels the order! ---")
    wg.Wait()
}

Real output:

Raju finished step 1
Asha finished step 1
--- customer cancels the order! ---
Asha finished step 2
Raju finished step 2
Raju finished step 3
Asha finished step 3
Asha finished step 4
Asha plated the dish
Raju finished step 4
Raju plated the dish

Every step after the cancel line is wasted work. Why: Go has no way to kill a goroutine from outside. A goroutine stops only when its own function returns. So it must be told to stop, and it must listen.

The obvious fix grows too big

A done channel (episode 48: closing a channel wakes every receiver) works for the stop signal. But real work also has a time limit ("ready in 30 minutes") and data that travels with it (the order id for every log line). Passing done, deadline and orderID to every function, and from it to every function it calls, is three extra parameters everywhere:

func cook(done <-chan struct{}, deadline time.Time, orderID string, name string) {
    takeFromFridge(done, deadline, orderID)
    fry(done, deadline, orderID)
}

The fix is to bundle the three into one value, passed as one parameter: a context.

func cook(ctx context.Context, name string) {
    takeFromFridge(ctx)
    fry(ctx)
}

context.Context

context.Context is an interface in the standard library's context package:

type Context interface {
    Deadline() (deadline time.Time, ok bool) // when the work must stop, if ever
    Done() <-chan struct{}                    // closed when the work should stop
    Err() error                               // nil while running; then Canceled or DeadlineExceeded
    Value(key any) any                        // a request-scoped value, or nil
}
The order slip Context
travels with the work to every cook passed as the first parameter, ctx
a bell rings: order cancelled Done() is closed; Err() says why
"ready by 8:30" written on it Deadline()
"table 7" written on it Value(key)

Request-scoped data means data that belongs to one request and travels with it: a request id, the logged-in user, a trace id.

Where contexts come from

  • context.Background(): an empty context: never cancelled, no deadline, no values. The root of every tree; use it in main, in tests, and at the top of a request.
  • context.TODO(): also empty. Use it when a function needs a context but you haven't decided yet which one to pass. A to-do note.
  • WithCancel, WithTimeout, WithDeadline, WithValue (and the ...Cause versions) each take a parent context and return a new child context derived from it, with one thing added. The parent is never changed: contexts are immutable (they never change after creation), which is why they're safe to share between goroutines.

WithCancel: cancel by hand

ctx, cancel := context.WithCancel(parent) returns a child context and a CancelFunc: a function that cancels that context. Calling it closes ctx.Done() and makes ctx.Err() return context.Canceled. Calling it again does nothing.

A goroutine listens with select (episode 49): do the next step, or stop when Done is closed.

package main

import (
    "context"
    "fmt"
    "sync"
    "time"
)

func cook(ctx context.Context, name string, wg *sync.WaitGroup) {
    defer wg.Done()
    for step := 1; step <= 4; step++ {
        select {
        case <-time.After(30 * time.Millisecond): // one cooking step
            fmt.Println(name, "finished step", step)
        case <-ctx.Done(): // the order was cancelled
            fmt.Println(name, "stops:", ctx.Err())
            return
        }
    }
    fmt.Println(name, "plated the dish")
}

func main() {
    ctx, cancel := context.WithCancel(context.Background())
    var wg sync.WaitGroup
    wg.Add(2)
    go cook(ctx, "Raju", &wg)
    go cook(ctx, "Asha", &wg)
    time.Sleep(50 * time.Millisecond)
    fmt.Println("--- customer cancels the order! ---")
    cancel() // closes ctx.Done() for everyone
    wg.Wait()
    fmt.Println("after cancel, Err is:", ctx.Err())
}

Real output:

Raju finished step 1
Asha finished step 1
--- customer cancels the order! ---
Raju stops: context canceled
Asha stops: context canceled
after cancel, Err is: context canceled

One cancel() reached both cooks. That's cancellation with context.

WithTimeout and WithDeadline: cancel on time

At the counter In Go
"ready in 30 minutes, or stop" timeout: a duration from now: WithTimeout(parent, 30*time.Minute)
"the shop closes at 11 pm" deadline: a fixed clock time: WithDeadline(parent, t)
time's up Err() returns context.DeadlineExceeded

WithTimeout(parent, d) is exactly WithDeadline(parent, time.Now().Add(d)). You must still call cancel (with defer): it stops the timer early and frees the context as soon as the work is done.

package main

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

// makeBiryani takes 80ms, unless ctx says stop first
func makeBiryani(ctx context.Context) error {
    select {
    case <-time.After(80 * time.Millisecond):
        return nil
    case <-ctx.Done():
        return ctx.Err()
    }
}

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
    defer cancel() // always release the context
    dl, ok := ctx.Deadline()
    fmt.Println("has deadline:", ok, "in about", time.Until(dl).Round(10*time.Millisecond))

    err := makeBiryani(ctx)
    fmt.Println("error:", err)
    fmt.Println("is DeadlineExceeded?", errors.Is(err, context.DeadlineExceeded))

    closing := time.Now().Add(time.Hour) // the shop closes in one hour
    ctx2, cancel2 := context.WithDeadline(context.Background(), closing)
    defer cancel2()
    fmt.Println("before closing time:", makeBiryani(ctx2))
}

Real output:

has deadline: true in about 50ms
error: context deadline exceeded
is DeadlineExceeded? true
before closing time: <nil>

makeBiryani needed 80 ms, the context allowed 50 ms, so it returned the context's error. errors.Is (episode 25) tells you which error it was. Every function that can block for a long time (a database query, a network call, waiting on a channel) should take a ctx and give up when it's done. In the standard library, for example, every *http.Request carries a context, which a handler reads with r.Context().

The cancellation tree

Contexts form a tree. Each With... call makes a child of its parent.

Background
└── order        (WithCancel)
    ├── tandoor  (WithCancel)
    └── fryer    (WithTimeout, 1 hour)
  • Cancelling a parent cancels all its children, and their children: cancellation propagation.
  • Cancelling a child never affects its parent or its siblings.
  • A child's deadline is never later than its parent's: whichever comes first wins.
package main

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

func watch(ctx context.Context, name string) {
    <-ctx.Done()
    fmt.Println("  ", name, "stopped:", ctx.Err())
}

func main() {
    order, cancelOrder := context.WithCancel(context.Background())
    tandoor, cancelTandoor := context.WithCancel(order) // children of order
    fryer, cancelFryer := context.WithTimeout(order, time.Hour)
    defer cancelTandoor()
    defer cancelFryer()
    go watch(tandoor, "tandoor")
    go watch(fryer, "fryer")

    fmt.Println("1) cancel only the tandoor:")
    cancelTandoor()
    time.Sleep(10 * time.Millisecond)
    fmt.Println("   order still alive?", order.Err() == nil)

    fmt.Println("2) cancel the whole order:")
    cancelOrder()
    time.Sleep(10 * time.Millisecond)
    fmt.Println("   order:", order.Err())
}

Real output:

1) cancel only the tandoor:
   tandoor stopped: context canceled
   order still alive? true
2) cancel the whole order:
   fryer stopped: context canceled
   order: context canceled

Always call cancel: the go vet warning

// $ go vet
// ---- main.go ----
package main

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

func fetchMenu() error {
    ctx, _ := context.WithTimeout(context.Background(), time.Second)
    <-ctx.Done()
    return ctx.Err()
}

func main() {
    fmt.Println(fetchMenu())
}

Real output (go vet, the checker that ships with Go):

$ go vet
# shop
# [shop]
./main.go:10:10: the cancel function returned by context.WithTimeout should be called, not discarded, to avoid a context leak

A leak is something that keeps holding memory after you're done with it. A context that is never cancelled stays attached to its parent (with its timer) until the parent is cancelled; with Background as the parent, that's never. The rule: every With... call is followed by defer cancel().

WithValue and typed keys

context.WithValue(parent, key, value) returns a child holding one key and one value. ctx.Value(key) looks in that context, then its parent, and so on up to the root, and returns nil if no one set the key.

The obvious way: string keys

package main

import (
    "context"
    "fmt"
)

// two parts of the app, written by two different people
func addTable(ctx context.Context) context.Context {
    return context.WithValue(ctx, "id", "table-7") // the waiter's id
}
func addPayment(ctx context.Context) context.Context {
    return context.WithValue(ctx, "id", "upi-4512") // the cashier's id
}

func main() {
    ctx := addPayment(addTable(context.Background()))
    fmt.Println("table:", ctx.Value("id")) // the waiter wants the table
}

Real output:

table: upi-4512

The waiter asked for his table and got a payment id: both parts used the key "id", and the newer value hides the older one. No compile error, no warning, wrong data. That's why the docs say keys should not be string or any other built-in type.

The fix: unexported key types

package main

import (
    "context"
    "fmt"
)

type tableKey struct{}   // unexported key types: nobody
type paymentKey struct{} // else can create the same key

func main() {
    ctx := context.WithValue(context.Background(), tableKey{}, "table-7")
    ctx = context.WithValue(ctx, paymentKey{}, "upi-4512")

    fmt.Println("table:", ctx.Value(tableKey{}))
    fmt.Println("payment:", ctx.Value(paymentKey{}))

    tip, ok := ctx.Value("tip").(int) // a key nobody set
    fmt.Println("tip:", tip, ok)
}

Real output:

table: table-7
payment: upi-4512
tip: 0 false
  • tableKey and paymentKey are empty struct types. Values of different types are never equal, so the keys can't collide.
  • They start with a lower-case letter, so they're unexported: no other package can create the same key.
  • Value returns any, so read it with a comma-ok type assertion (episode 22). A missing key gives nil, and the assertion reports false.
  • A common style is to keep the key private and export small helpers: func WithTable(ctx context.Context, t string) context.Context and func Table(ctx context.Context) (string, bool).

Use values only for request-scoped data. Never use them to pass optional function arguments: those belong in the parameter list, where the compiler checks them.

WithCancelCause, Cause, AfterFunc, WithoutCancel

At the counter In Go
"cancelled: the customer left", not just "cancelled" WithCancelCause + context.Cause (Go 1.20)
when cancelled, start the refund context.AfterFunc(ctx, f) (Go 1.21)
the accounts book must still be written context.WithoutCancel(ctx) (Go 1.21)
  • WithCancelCause(parent) returns a cancel that takes an error: the cause. context.Cause(ctx) returns it. ctx.Err() still returns plain context.Canceled, so older code keeps working. Only the first cause is kept.
  • AfterFunc(ctx, f) runs f in its own goroutine once ctx is done. It returns a stop function that cancels the arrangement if f hasn't started.
  • WithoutCancel(parent) returns a child that keeps the parent's values but is never cancelled: for work that must finish even after the request is cancelled, like writing an audit log.
  • WithTimeoutCause and WithDeadlineCause are timers with a cause.
package main

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

var errLeft = errors.New("customer left the shop")

func main() {
    ctx, cancel := context.WithCancelCause(context.Background())
    stop := context.AfterFunc(ctx, func() { // runs once ctx is done
        fmt.Println("AfterFunc: tell the cashier to refund")
    })
    defer stop()

    cancel(errLeft) // cancel, and say WHY
    time.Sleep(10 * time.Millisecond)
    fmt.Println("Err:  ", ctx.Err())
    fmt.Println("Cause:", context.Cause(ctx))

    audit := context.WithoutCancel(ctx) // keeps values, ignores cancel
    fmt.Println("audit Err:", audit.Err())
}

Real output:

AfterFunc: tell the cashier to refund
Err:   context canceled
Cause: customer left the shop
audit Err: <nil>

A nil context crashes

package main

import (
    "context"
    "fmt"
)

func cook(ctx context.Context, dish string) {
    if err := ctx.Err(); err != nil {
        fmt.Println("skip", dish, err)
        return
    }
    fmt.Println("cooking", dish)
}

func main() {
    cook(nil, "dosa")
}

Real output:

panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x28 pc=0x491bba]

goroutine 1 [running]:
main.cook({0x0?, 0x0?}, {0x4b3c73, 0x4})
    main.go:9 +0x3a
main.main()
    main.go:17 +0x25
exit status 2

A nil interface has no methods to call (episode 21). Never pass nil; pass context.TODO() until you know which context belongs there:

package main

import (
    "context"
    "fmt"
)

func cook(ctx context.Context, dish string) {
    if err := ctx.Err(); err != nil {
        fmt.Println("skip", dish, err)
        return
    }
    fmt.Println("cooking", dish)
}

func main() {
    cook(context.TODO(), "dosa") // "not decided yet"
}

Real output:

cooking dosa

The context rules

  1. ctx is the first parameter: func Cook(ctx context.Context, dish string) error.
  2. Never store a context in a struct: pass it to each function that needs it. A context belongs to one request; a struct often lives much longer.
  3. Never pass nil: use context.TODO().
  4. Always call cancel: defer cancel() right after every With... call (go vet checks this).
  5. Values only for request-scoped data, with unexported key types.
  6. A context is safe to share between goroutines, because it never changes.
  7. Check both errors: errors.Is(err, context.Canceled) and errors.Is(err, context.DeadlineExceeded) mean different things.

Mini project: the order tracker

An order context with a 200 ms timeout and an order-id value; three dishes in three goroutines, each with its own child timeout; every log line prints the order id; when one dish fails, the whole order is cancelled with a cause; an AfterFunc starts the refund.

package main

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

type orderKey struct{}

func logf(ctx context.Context, format string, args ...any) {
    id, _ := ctx.Value(orderKey{}).(string)
    fmt.Printf("[%s] "+format+"\n", append([]any{id}, args...)...)
}

func prepare(ctx context.Context, dish string, takes, limit time.Duration) error {
    ctx, cancel := context.WithTimeout(ctx, limit) // each dish has its own limit
    defer cancel()
    select {
    case <-time.After(takes):
        logf(ctx, "%s ready", dish)
        return nil
    case <-ctx.Done():
        return fmt.Errorf("%s: %w", dish, ctx.Err())
    }
}

func main() {
    base := context.WithValue(context.Background(), orderKey{}, "order-42")
    ctx, cancel := context.WithCancelCause(base)
    defer cancel(nil)
    ctx, cancelT := context.WithTimeout(ctx, 200*time.Millisecond)
    defer cancelT()
    stop := context.AfterFunc(ctx, func() { logf(base, "refund started") })
    defer stop()

    dishes := []struct {
        name         string
        takes, limit time.Duration
    }{{"dal", 30 * time.Millisecond, 100 * time.Millisecond},
        {"naan", 60 * time.Millisecond, 40 * time.Millisecond}, // too slow for its limit
        {"biryani", 150 * time.Millisecond, 180 * time.Millisecond}}

    var wg sync.WaitGroup
    for _, d := range dishes {
        wg.Add(1)
        go func() {
            defer wg.Done()
            if err := prepare(ctx, d.name, d.takes, d.limit); err != nil {
                logf(ctx, "failed: %v", err)
                cancel(errors.New("a dish failed: " + err.Error()))
            }
        }()
    }
    wg.Wait()
    time.Sleep(10 * time.Millisecond)
    logf(ctx, "cause: %v", context.Cause(ctx))
}

Real output:

[order-42] dal ready
[order-42] failed: naan: context deadline exceeded
[order-42] failed: biryani: context canceled
[order-42] refund started
[order-42] cause: a dish failed: naan: context deadline exceeded

The naan needed 60 ms but its own limit was 40 ms, so it failed with context deadline exceeded, and its goroutine cancelled the whole order with a cause. The biryani, still cooking, saw the parent's cancel (context canceled). The AfterFunc started the refund, and Cause explains what happened. Note that logf(base, ...) uses base, the context with the value, and context.Cause keeps only the first cause.

Common mistakes (and the real messages)

Mistake Real message / result Why Fix
a goroutine that never checks its context keeps working after the cancel goroutines can't be stopped from outside select on ctx.Done()
ctx, _ := context.WithTimeout(...) go vet: the cancel function returned by context.WithTimeout should be called, not discarded, to avoid a context leak the timer and the child are never freed defer cancel()
context.WithValue(ctx, "id", v) the wrong value, no error string keys collide type idKey struct{}
cook(nil, "dosa") panic: runtime error: invalid memory address or nil pointer dereference nil has no methods context.TODO()
a context stored in a struct field a stale or wrong context it outlives the request pass ctx as a parameter
if err == context.Canceled only timeouts are missed two different errors errors.Is for each
values used as optional parameters hidden inputs, no type checks values are untyped real parameters
ignoring ctx in a long loop cancel takes effect only at the end nobody checks check ctx.Err() each iteration

Practice

  1. Write sleepCtx(ctx, d) error that waits for d or returns early with the context's error.
  2. A parent has a 20 ms timeout; its child asks for one hour. When does the child stop, and what's its Err?
  3. Make a timeout with a cause, "kitchen too slow", and print both Err and Cause.
  4. Rewrite the string-key program so the waiter gets his table, with helper functions WithTable and Table.
Solutions

1. A time.Timer (episode 49) is stopped with defer, so nothing is left running:

package main

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

// sleepCtx waits for d, or returns early with ctx's error
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 ctx.Err()
    }
}

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
    defer cancel()
    fmt.Println("10ms:", sleepCtx(ctx, 10*time.Millisecond))
    fmt.Println("1s:  ", sleepCtx(ctx, time.Second))
}

Real output:

10ms: <nil>
1s:   context deadline exceeded

2. The child can't outlive its parent: its deadline is the parent's.

package main

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

func main() {
    parent, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
    defer cancel()
    child, cancelChild := context.WithTimeout(parent, time.Hour) // asks for an hour
    defer cancelChild()

    d, _ := child.Deadline()
    fmt.Println("child deadline within 20ms?", time.Until(d) <= 20*time.Millisecond)
    <-child.Done()
    fmt.Println("child:", child.Err())
}

Real output:

child deadline within 20ms? true
child: context deadline exceeded

3.

package main

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

func main() {
    ctx, cancel := context.WithTimeoutCause(context.Background(),
        30*time.Millisecond, errors.New("kitchen too slow"))
    defer cancel()
    <-ctx.Done()
    fmt.Println("Err:  ", ctx.Err())
    fmt.Println("Cause:", context.Cause(ctx))
}

Real output:

Err:   context deadline exceeded
Cause: kitchen too slow

4.

package main

import (
    "context"
    "fmt"
)

type tableKey struct{}

// WithTable returns a child context holding the table
func WithTable(ctx context.Context, t string) context.Context {
    return context.WithValue(ctx, tableKey{}, t)
}

// Table reads the table back, and reports whether it was set
func Table(ctx context.Context) (string, bool) {
    t, ok := ctx.Value(tableKey{}).(string)
    return t, ok
}

func main() {
    ctx := WithTable(context.Background(), "table-7")
    ctx = context.WithValue(ctx, "id", "upi-4512") // someone else's string key
    t, ok := Table(ctx)
    fmt.Println("table:", t, ok)
    _, ok = Table(context.Background())
    fmt.Println("no table set:", ok)
}

Real output:

table: table-7 true
no table set: false

Quick quiz

1. A child is made from a parent, and only the parent is cancelled. What do parent.Err() and child.Err() print? (From the video.)

parent, cancelP := context.WithCancel(context.Background())
child, cancelC := context.WithCancel(parent)
defer cancelC()
cancelP()
fmt.Println(parent.Err(), "|", child.Err())

A. context canceled | context canceled · B. context canceled | <nil> · C. <nil> | context canceled · D. <nil> | <nil>

Answer

A. Cancelling a parent cancels every child derived from it.

2. What does ctx.Err() return before the context is cancelled?

Answer

nil.

3. Is it safe to call a CancelFunc twice?

Answer

Yes. After the first call, later calls do nothing.

4. Which context do you pass when a function needs one but you don't know which yet?

Answer

context.TODO(), never nil.

Interview questions

  1. What is context.Context for? Carrying a cancellation signal, a deadline and request-scoped values across API boundaries and goroutines.
  2. How do you stop a goroutine in Go? You can't from outside; the goroutine must check ctx.Done() (or a done channel) and return.
  3. Difference between context.Background() and context.TODO()? Both are empty; Background is the intended root, TODO marks "not decided yet".
  4. WithTimeout vs WithDeadline? A duration from now vs an absolute time; WithTimeout(p, d) is WithDeadline(p, time.Now().Add(d)).
  5. Why must you always call cancel? It releases the child and its timer; otherwise they live until the parent is cancelled (a leak). go vet checks it.
  6. How does cancellation propagate? Down the tree: a parent's cancel reaches all descendants; a child's cancel never reaches its parent.
  7. Why shouldn't context keys be strings? Different packages can pick the same string and overwrite each other; use unexported key types.
  8. Why not store a context in a struct? A context is scoped to one request; a struct usually outlives it, so the stored context goes stale.
  9. How do you tell a timeout from a cancel? errors.Is(err, context.DeadlineExceeded) vs errors.Is(err, context.Canceled); context.Cause gives the custom reason.
  10. When would you use WithoutCancel? For cleanup or audit work that must finish after the request is cancelled, while keeping its values.

Glossary

Term Meaning Example
Cancellation telling running work it's no longer needed, so it can stop early the customer leaves
Request one piece of work someone asked for one web page load, one order
Request-scoped data data that belongs to one request and travels with it a request id
context package the standard library package for cancellation, deadlines and values import "context"
context.Context the interface that carries them: Deadline, Done, Err, Value func f(ctx context.Context)
ctx the conventional name of a context parameter, always first Cook(ctx, "dal")
context.Background() the empty root context, never cancelled in main
context.TODO() an empty placeholder context: "not decided yet" while refactoring
Parent / child context a child is derived from a parent by a With... call child, c := WithCancel(parent)
Derived context another name for a child context
WithCancel returns a child and a CancelFunc ctx, cancel := WithCancel(bg)
CancelFunc a function that cancels its context; safe to call twice defer cancel()
Done() a channel closed when the context is cancelled case <-ctx.Done():
Err() nil while running, then why it stopped context canceled
context.Canceled the error after a cancel() call context canceled
context.DeadlineExceeded the error when the deadline passed context deadline exceeded
Timeout a length of time from now 50 ms
Deadline a fixed point in time 11 pm
WithTimeout a child that cancels itself after a duration WithTimeout(bg, 50*time.Millisecond)
WithDeadline a child that cancels itself at a time WithDeadline(bg, closing)
Deadline() the context's deadline, and whether it has one dl, ok := ctx.Deadline()
Cancellation tree contexts linked parent to child order → tandoor, fryer
Cancellation propagation a parent's cancel flowing down to all its children cancel the order, the fryer stops
Leak something that keeps holding memory or goroutines after it's no longer needed an uncancelled context
go vet Go's built-in checker for suspicious code the lostcancel warning
WithValue a child holding one key and value WithValue(ctx, tableKey{}, "table-7")
Value(key) looks up a key through the chain of parents ctx.Value(tableKey{})
Key collision two parts of a program using the same key by accident two "id" keys
Unexported key type a private type used as a key so no one else can create it type tableKey struct{}
Empty struct a struct type with no fields, size zero struct{}
Comma-ok type assertion v, ok := x.(T): ok is false instead of a panic tip, ok := ctx.Value(k).(int)
WithCancelCause like WithCancel, but cancel takes an error cancel(errLeft)
Cause the error explaining why a context was cancelled context.Cause(ctx)
context.Cause returns the cause, or Err() if none was given customer left the shop
WithTimeoutCause / WithDeadlineCause timers with a cause "kitchen too slow"
AfterFunc runs a function in its own goroutine once the context is done the refund
WithoutCancel a child with the parent's values that is never cancelled the audit log
Immutable never changes after creation contexts
Nil pointer dereference calling through a nil pointer or interface: a panic cook(nil, ...)

Summary

  • Go can't stop a goroutine from outside: work must listen on ctx.Done() and return.
  • A context.Context carries a stop signal, a deadline and request-scoped values; it's always the first parameter, ctx.
  • Background is the root, TODO the placeholder, never nil.
  • WithCancel → cancel() → context canceled; WithTimeout / WithDeadline → context deadline exceeded.
  • Cancellation flows down the tree, never up; always defer cancel() (go vet warns otherwise).
  • WithValue with unexported key types, for request-scoped data only.
  • WithCancelCause + Cause say why; AfterFunc reacts to a cancel; WithoutCancel keeps values without the cancel.

Next episode: concurrency patterns part 1: generators, pipelines and stages, fan-out, fan-in and merging channels, worker pools with job and result channels, bounded parallelism, semaphores from buffered channels, the done channel pattern, and keeping results in order.