context.Background

July 4, 2025

After this detour through context key types, let’s get back to the GoDoc for our context package. Next up: context.Background():

func Background

func Background() Context

Background returns a non-nil, empty Context. It is never canceled, has no values, and has no deadline. It is typically used by the main function, initialization, and tests, and as the top-level Context for incoming requests.

Why would you ever want a context that essentially does nothing? Never canceled. No values. No deadline.

The background context can serve as a stand-in for any function that requires a context argument, when you don’t want the function to cancel, or read values from the context. Use this instead of nil. Never pass a nil context—even if you’re the author of the code, and know it’s safe to do so. Why? Well most important, it’s usually not safe to do so:

<- ctx.Done() // Will panic if ctx is nil

Second, it’s non-idiomatic. Stated early on in the GoDoc:

Do not pass a nil Context, even if a function permits it.

The second use of the background context, is as the first context in chain, which adds cancelation or values:

ctx = context.WithTimeout(context.Background(), 60 * time.Second)

Although frequently, the background context instantiation, and the chain addition, happen in very different parts of the code.


Share this

Direct to your inbox, daily. I respect your privacy .

Unsure? Browse the archive .

Get daily content like this in your inbox!

Subscribe