Context Lifecycle

In general a context is:

  • created by incoming requests to a server
  • accepted by outgoing requests
  • propagated between them

This means the context is passed through the functions rather than being stored in the struct. Typically it is the first argument in a function ctx asf

Cancelling Context

There’s three main ways to cancel context in Golang. The one you pick depends on whether you want to do the cancellation yourself or let it get cancelled automatically at a certain time.

func WithCancel(parent Context) (Context, CancelFunc)

This is the one where you’ve to figure out for yourself when the context should be cancelled. You pass in the ctx and get back a ctx and a cancel() function.

func WithDeadline(parent Context, t time.Time) (Context, CancelFunc)

This works by passing in the exact time the context should be cancelled at

func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc)

WithTimeout() - this is just a wrapper on the previous one but instead of an exact time you pass in a duration, after which the context will be cancelled at

What happens when cancel is called?

Calling Cancel stops the process and releases the resources associated with the context.

Why do WithTimeout and WithDeadline return a CancelFunc?

If the process finishes earlier than the Deadline or Timeout then you want to release the resources as soon as possible, rather than waiting for the deadline to pass.

Resources

https://pkg.go.dev/context https://go.dev/blog/context-and-structs https://go.dev/blog/context https://www.prakharsrivastav.com/posts/golang-context-and-cancellation

More Questions

  • How does a child Goroutine listen for cancellation?
  • How does cancellation propagate down the call chain