Deadlines and cancellation causes
Deadlines and cancellation causes
A deadline is an absolute time; a timeout is a duration relative to creation. WithDeadline and WithTimeout derive contexts whose effective deadline cannot be later than the parent’s. A deadline expiring normally sets Err to context.DeadlineExceeded. Manual cancellation normally sets Err to context.Canceled. Check Done rather than guessing whether a deadline has passed.
package main
import ( "context" "errors" "fmt")
func main() { ctx, cancel := context.WithTimeout(context.Background(), 0) defer cancel() <-ctx.Done() fmt.Println(errors.Is(ctx.Err(), context.DeadlineExceeded))}A zero timeout is already expired, so this example has deterministic output without depending on a short sleep. For real requests choose a budget that fits the operation and parent deadline. Always call cancel even if a timeout will eventually expire. A deadline does not automatically stop a function that ignores context.
Expected output:
trueKeep a useful cancellation reason
package main
import ( "context" "errors" "fmt")
func main() { ctx, cancel := context.WithCancelCause(context.Background()) defer cancel(nil) reason := errors.New("input unavailable") cancel(reason) <-ctx.Done() fmt.Println(ctx.Err() == context.Canceled, errors.Is(context.Cause(ctx), reason))}WithCancelCause and Cause (Go 1.20+) preserve a domain-specific error while Err remains the standard cancellation category. The first cancellation of a context determines its cause; later calls cannot replace it. WithDeadlineCause and WithTimeoutCause (Go 1.21+) attach a cause to expiry, not to manual calls of their returned CancelFunc. Avoid exposing private internal cause messages to end users.
Expected output:
true trueTry it locally
Create a context using WithDeadlineCause with an already-past deadline (time.Unix(0,0)) and a synthetic error "budget exhausted". Print whether Err is DeadlineExceeded and Cause matches your error.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Select and cancellation 06: Deadlines and cancellation causes
Check the lesson objective before moving on.
Can a derived context extend an earlier parent deadline?
After WithCancelCause cancellation with a nonnil error, what does Err return?