I just published a detailed guide on mastering context in Go, sharing my journey and hard-learned lessons. If you still feel context is “optional” or struggle to use it effectively, this is for you!
When reading data with an API just forwarding the request.Context to all calls (maybe adding withTimeout) is usually the right way. You don’t need to do work if the client is not interested in the result anymore.
But with writing calls you should think twice what your desired behavior on cancellation is.
Example: An API call will create a new Post and send an E-Mail about the post being created. Using the context for the database call to create the post is okay, since a cancelled context can cancel the operation. But if the database call succeeded, the E-Mail should be sent, even if the request-context has timed out or was cancelled, since it is part of a logical transaction. In this case the E-Mail should be sent with context.Background() (and a reasonable timeout)