Deadlines and Timeouts with Go Context

Limit how long work can run with WithTimeout and WithDeadline, and find out why a context ended.

Any call that goes over a network can hang. Deadlines turn "might wait forever" into "fails cleanly after a limit". This section covers setting limits and reading the reason a context ended.

WithTimeout and WithDeadline

ctx, cancel := context.WithTimeout(ctx, 2*time.Second)
defer cancel()

When time runs out, ctx.Err() returns context deadline exceeded. A child's deadline can never be later than its parent's.

Only context-aware calls time out:

http.Get ignores your context. Use http.NewRequestWithContext and QueryContext.

Checking Why a Context Ended

errors.Is(err, context.Canceled) vs errors.Is(err, context.DeadlineExceeded), plus WithCancelCause, context.Cause and AfterFunc.

Summary

Put a deadline on every outgoing call, always defer cancel(), and treat caller cancellation differently from timeouts.

context.WithTimeout and WithDeadline in Go

Put a time limit on any operation with context.WithTimeout or WithDeadline, see context deadline exceeded in action, and choose good timeout values.

Checking Why a Context Ended in Go

Tell context.Canceled from context.DeadlineExceeded with errors.Is, attach your own reason with WithCancelCause and context.Cause, and run cleanup with AfterFunc.