Go context lets you cancel slow work, set deadlines and pass request details through your program. In this post, you will learn how to create one, stop goroutines with it and avoid the usual mistakes. Each idea comes with a short example that you can run yourself.
It works hand in hand with goroutines and channels. So if those feel new, first read goroutines in Go for beginners and channels in Go with examples. We will also use select, which you met in the channels lesson.
What Is Go Context?
It is a small value from the standard context package. It carries three things: a cancel signal, an optional deadline and a few request-scoped values. You pass it as the first argument to any function that might take a while.
Think of ordering food in an app. If you cancel the order, the restaurant and the delivery rider must both stop. Similarly, Go context sends one stop signal to every goroutine working on the same request.
Why Go Context Matters
Imagine a web request that calls a database and two other services. Then the user closes the browser tab. Without one, all that work keeps running and wastes memory. With a context, every step notices the cancel and stops early. This also protects your server under heavy load, because cancelled requests free their memory quickly.
Creating a Go Context
context.Background
Every tree of these values starts from a root. Usually that root is context.Background(), which never cancels on its own. Then you wrap it to add a cancel signal or a deadline.
WithCancel: Stop Work on Demand
ctx, cancel := context.WithCancel(context.Background())
go func() {
time.Sleep(50 * time.Millisecond)
cancel()
}()
<-ctx.Done()
fmt.Println("cancelled:", ctx.Err()) // cancelled: context canceled
The function returns a new ctx and a cancel function. When you call cancel(), the Done() channel closes. As a result, anything waiting on it wakes up at once. For example, a search box can cancel the old search when the user types a new letter.
WithTimeout: Stop Slow Work
func slowTask(ctx context.Context) error {
select {
case <-time.After(2 * time.Second):
fmt.Println("task finished")
return nil
case <-ctx.Done():
return ctx.Err()
}
}
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
err := slowTask(ctx)
fmt.Println("error:", err) // error: context deadline exceeded
fmt.Println(errors.Is(err, context.DeadlineExceeded)) // true
The task needs two seconds, but ctx allows only 100 milliseconds. So the ctx.Done() case wins the select, and the task stops early. The diagram below shows this race.

The timeout fires at 100 ms, Done() closes, and slowTask returns before its 2 second job ends.
Listening for ctx.Done()
Cancelling does not stop your code by magic. Instead, your function must check ctx.Done(), usually inside a select or a loop. Most standard library functions that do network work, such as http.NewRequestWithContext, already check it for you.
In a web server, every request already carries a Go context. You get it with r.Context(), and it cancels on its own when the client disconnects. So pass it down to database calls and other services. That way, a closed browser tab stops all the work behind it.
Passing Values with WithValue
type ctxKey string
ctx := context.WithValue(context.Background(), ctxKey("requestID"), "abc-123")
fmt.Println(ctx.Value(ctxKey("requestID"))) // abc-123
In short, use WithValue only for small request details, like a request ID or a user ID. Also, define your own key type, because plain strings can clash with keys from other packages.
Go Context Best Practices
- Pass it as the first parameter, named
ctx. - Always call
defer cancel()right after creating one. - Never store ctx inside a struct field.
- Never pass
nil, so usecontext.TODO()if you are unsure.
Common Mistakes with Go Context
| Problem you see | Why it happens | How to fix it |
|---|---|---|
| go vet: the cancel function returned by context.WithTimeout should be called, not discarded | The code threw cancel away with _. | Keep it and add defer cancel(). |
| Work keeps running after timeout | The function never checks ctx.Done(). | Select on ctx.Done(). |
| Value returns nil | The key type does not match. | Use the same custom key type. |
Forgetting cancel leaks resources until the timeout ends. These questions are popular in backend interviews, so practise with my Go interview questions and answers.
Official Resources
These pages come straight from the Go team, so they are always accurate and up to date.
- context package documentation
- Go blog: Go Concurrency Patterns: Context
- Go blog: Contexts and structs
Quick Recap
- Go context carries cancel signals, deadlines and small request values.
- Start from context.Background() and wrap it.
- WithCancel stops work on demand, and WithTimeout stops slow work.
- Your code must listen on ctx.Done() to stop early.
- Always defer cancel() and pass ctx as the first parameter.
What’s Next?
You have finished the core concurrency tools. Next, we will write one function that works for many types using generics.
Coming soon: Go Generics Explained with Examples


