Skip to content

Lesson 2 of 9 · 24m

Context Cancellation in Production

Propagate deadlines, cancellation, and request-scoped ownership through concurrent code without turning context into a junk drawer.

context.Context is Go's cancellation nervous system. It is also one of the most abused interfaces in production code. Cancellation is how a caller says, 'the reason for this work no longer exists.' Ignoring that signal turns user timeouts into background load and rolling deploys into goroutine leaks.

Cancellation flows downstream

A parent cancels children. Children do not cancel their parent, and siblings should not surprise one another unless a supervisor makes that contract explicit:

func handle(ctx context.Context, req Request) error {
    ctx, cancel := context.WithTimeout(ctx, 750*time.Millisecond)
    defer cancel()
    row, err := db.GetOrder(ctx, req.OrderID)
    if err != nil { return err }
    return cache.Warm(ctx, row)
}

defer cancel() is not ceremony. It releases timer and cancellation resources even when the operation succeeds. The go vet lostcancel check exists because this leak is easy to write and hard to notice.

Check cancellation at interruption points

Check context before waiting, starting another expensive batch, or continuing a long loop:

for _, key := range keys {
    if err := ctx.Err(); err != nil { return err }
    if err := writeOne(ctx, key); err != nil { return err }
}

Do not sprinkle checks after every arithmetic operation. Cancellation is cooperative, so a tight CPU-bound loop still needs periodic checks or bounded chunks.

Select cancellation beside channel operations

A goroutine blocked on send or receive must also listen for cancellation:

select {
case out <- result:
case <-ctx.Done():
    return ctx.Err()
}

Without the second case, cancellation cannot reach a goroutine parked on a channel. Downstream stopped reading, upstream keeps trying to send, and shutdown waits forever.

Context is not configuration

context.WithValue is for request-scoped values that genuinely cross API boundaries: trace IDs, authentication identity, perhaps correlation IDs. It is not for database handles, loggers, or feature flags. Explicit parameters expose dependencies; context smuggling re-creates global variables with worse type checking.

Field notes

  • context.Background() belongs at roots and tests, not deep inside a request where cancellation is inconvenient.
  • context.TODO() is a design marker. Leaving it in production means the ownership boundary is unfinished.
  • Context cancellation does not close network connections by magic; clients and drivers must implement it.
  • Deadlines are budgets. Nested timeouts should shrink remaining time, not mysteriously extend it.

Was this lesson helpful?

Sign in to rate