1. Why do we need context: “I changed my mind” as part of the program
When you write learning programs, it feels like code always runs “whoosh — and it is done”. But in real-world tasks, many operations can take noticeable time: reading a large stream, importing data, a network request, work with the file system, a long computation. And at some point, a human “I changed my mind” appears: the user pressed Ctrl+C, the server closed the connection, a timeout occurred, or there was a switch to another screen in the UI.
Of course, you could say: “Well, let it keep loading.” But the program has memory, descriptors, buffers, and sometimes money too (if you pay for external APIs). So Go provides a standard “common language” to tell functions: stop. This is where context.Context lives: it carries the “cancellation signal” and the reason for stopping across function and package boundaries. And this is not just a “nice-to-have feature”, but the foundation of robust servers and libraries.
The context.Context interface: what matters in it
context.Context is an interface (a contract) that carries information about an operation. At the introductory level, it is enough to think of it as a small object with two useful ideas:
- an operation can have a “canceled” state,
- if it is canceled, we can find out the reason through Err().
The official context description also includes the Done() channel, deadlines, and values, but today we are taking the most practical minimum: Background, TODO, WithCancel, cancel(), and checking Err(). At the same time, it is important to understand the basic principle: a context is not a command to “kill the thread”, but a signal that your function must respect. In other words, cancellation only works where you regularly check the context and voluntarily stop the work.
A small “map of the terrain” table so we do not get confused:
| Thing | What is it? | What does it sound like in plain language? |
|---|---|---|
|
root context | “I am starting the operation from scratch” |
|
a placeholder | “A context is needed, but I have not decided which one yet” |
|
creates a “child” context + cancel() | “Here is an operation that can be canceled manually” |
|
cancellation reason or nil | “Are we canceled? If so — why?” |
2. Basic contexts: Background and TODO
context.Background(): the root of the context tree
Let us start with the simplest and calmest one: context.Background().
It is convenient to think of it as the root point: the “tree” of contexts is built from it. Such a context is never canceled on its own and is usually used in main() or as the “default context” if there is no other one available yet.
A mini-example: we simply ask for Err() — it will return nil, because nothing has been canceled.
package main
import (
"context"
"fmt"
)
func main() {
ctx := context.Background()
fmt.Println(ctx.Err()) // <nil>
}
An important point: Background() is not a magic button. It is just a standard, “eternal” parent. If you create Background() inside every function, cancellation will never propagate “downward”, and the whole point of context will be lost.
context.TODO(): a placeholder during development
context.TODO() is often perceived as “just another Background()”. Technically, in behavior it is similar: also not canceled, Err() is also nil. But in meaning it is different: it is a marker for the programmer and the reviewer — “a context is needed here, but I have not yet figured out where to get it from”.
This is useful in intermediate code when you are still designing the API. For example, you wrote a function that already requires a context, but the call site is not ready yet — put TODO() there and then come back later to “weave in” the real context from the request or CLI command.
package main
import (
"context"
"fmt"
)
func main() {
ctx := context.TODO()
fmt.Println(ctx.Err()) // <nil>
}
A joke, with a grain of truth: TODO() is “a sticky note in the code”. It does not solve the problem, but it makes the problem visible.
4. Cancellation via WithCancel and Err()
context.WithCancel: creating a cancelable context
Now the interesting part: context.WithCancel(parent).
This function takes a parent context and returns two values: a new ctx and a cancel function. When you call cancel(), the context moves into the “canceled” state, and ctx.Err() starts returning the cancellation error.
Mini-example: cancel immediately and print Err().
package main
import (
"context"
"fmt"
)
func main() {
ctx, cancel := context.WithCancel(context.Background())
cancel()
fmt.Println(ctx.Err()) // context canceled
}
Why call cancel() even without explicit cancellation
This is a subtle point that beginners often miss: cancel() should be called (usually via defer cancel()), because there can be internal resources inside the context (internal structures, parent→child links). In good Go style, the one who created WithCancel is also the one who “closes” its life cycle with a call to cancel(). This is similar to defer file.Close(): even if the “file is small”, you still need to close it.
Here is the typical pattern:
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// ... work with ctx ...
How to respect cancellation: checking ctx.Err() in long-running places
If a context can be canceled, a logical question arises: “how does my function know that it has been canceled?”
At the introductory level, the simplest and clearest way is to periodically check ctx.Err() in a loop or between steps of the algorithm. If Err() returned a non-nil value, the work should end, usually by returning the same error.
This is especially convenient in what we already know: in I/O loops (reading chunk by chunk) or in a record-processing loop.
A small “consume the stream in chunks” function that respects cancellation:
package main
import (
"context"
"fmt"
"io"
)
func consume(ctx context.Context, r io.Reader) error {
buf := make([]byte, 4)
for {
if err := ctx.Err(); err != nil {
return err
}
n, err := r.Read(buf)
if n > 0 {
fmt.Printf("got %q\n", buf[:n]) // for example: got "abcd"
}
if err == io.EOF {
return nil
}
if err != nil {
return err
}
}
}
Pay attention to an important habit: we first use buf[:n], and only then decide what to do with err. This works well with cancellation: the context is checked at the “top” of each iteration, while the read remains correct.
5. Embedding context into the API and the application
ctx as the first parameter
In Go there is an established convention: if a function supports cancellation, it accepts ctx context.Context as the first parameter. This is not “style for style’s sake”, but a way to make the code readable: you immediately see that the operation is context-aware and can finish early.
Bad signature (confusing and hides what matters):
func ImportTasks(r io.Reader, ctx context.Context) error { /* ... */ }
Good signature (as is customary in the standard library and most projects):
func ImportTasks(ctx context.Context, r io.Reader) error { /* ... */ }
Another rule closely related to this: do not pass nil instead of a context. If there is “no context”, use context.Background() (or TODO() as a temporary marker). This helps you avoid panic and removes unnecessary branching: the function should not guess what you meant by passing nil.
Mini-example: importing tasks with cancellation
To keep the topic from staying abstract, let us carefully continue our educational task app. Earlier we already had the Task type, and we learned how to print results to io.Writer. Now let us imagine that we have task import from any io.Reader: for example, from memory (bytes.Buffer) or from another source.
We do not use bufio.Scanner (that is a separate topic), so we will use a simple approach: read the stream in chunks, collect it into a bytes.Buffer, and then parse the lines.
First, the model:
package main
type Task struct {
Title string
}
Now the import function that respects cancellation via ctx.Err():
package main
import (
"bytes"
"context"
"fmt"
"io"
"strings"
)
func ImportTasks(ctx context.Context, r io.Reader) ([]Task, error) {
var all bytes.Buffer
buf := make([]byte, 8)
for {
if err := ctx.Err(); err != nil {
return nil, err
}
n, err := r.Read(buf)
if n > 0 {
all.Write(buf[:n])
}
if err == io.EOF {
break
}
if err != nil {
return nil, fmt.Errorf("read tasks: %w", err)
}
}
lines := strings.Split(strings.TrimSpace(all.String()), "\n")
tasks := make([]Task, 0, len(lines))
for _, line := range lines {
if line == "" {
continue
}
tasks = append(tasks, Task{Title: line})
}
return tasks, nil
}
Here are several important ideas that “glue” the whole module together:
- We read as a stream and use only buf[:n], as we agreed earlier.
- We check ctx.Err() on every read iteration. This makes the import “cancelable”, even if io.Reader itself knows nothing about context.
- We wrap the read error with %w, so that higher up the stack it is clear that the failure happened specifically at the read tasks step. This continues the good error style: we add operation context, but do not lose the cause.
Mini-demo where we cancel the operation before it starts:
package main
import (
"bytes"
"context"
"fmt"
)
func main() {
var src bytes.Buffer
src.WriteString("buy milk\nlearn go\n")
ctx, cancel := context.WithCancel(context.Background())
cancel() // canceled in advance
tasks, err := ImportTasks(ctx, &src)
fmt.Println("tasks:", tasks) // tasks: []
fmt.Println("err:", err) // err: context canceled
}
Of course, in a real program cancellation often happens “from outside” (user, server, timeout), but it is important for us to see the mechanism: if the context is canceled, the function stops quickly and predictably.
6. Context tree: cancellation propagates downward
Now let us reinforce one idea that often becomes an “aha moment”: contexts form a tree. If you created a context from a parent, and the parent was canceled, then all the “children” are canceled too. This is the fundamental context model.
In the form of a simple diagram:
flowchart TD
A[context.Background] --> B[WithCancel: ctx1]
B --> C[WithCancel: ctx2]
B --> D[WithCancel: ctx3]
X[cancel ctx1] --> B
B -->|cancellation propagates| C
B -->|cancellation propagates| D
This model is especially useful when one “upper” level starts an operation, and lower levels perform sub-operations. Even without a deep dive into concurrency, you can understand the main point: one cancellation signal should flow cleanly through all functions that participate in the operation.
7. Typical mistakes when working with context
Mistake #1: creating context.Background() inside every function.
It looks harmless: “I need a context, so I created one.” But this breaks the cancellation chain. The caller will cancel its ctx, and your function will keep working because it has a different, eternal Background. The correct path is to accept ctx as a parameter and pass it further down.
Mistake #2: forgetting to call cancel() after WithCancel.
Even if it seems that “everything will finish anyway”, good style is defer cancel() where the context is created. This disciplines the code and helps avoid holding extra internal links and resources longer than needed. It feels like “forgetting to close a file”: sometimes nothing breaks, and sometimes you get very strange effects.
Mistake #3: passing nil instead of a context.
Beginners sometimes think: “if I do not need a context, I will pass nil”. Then someone calls ctx.Err() and gets a panic. In Go the convention is: no context — use context.Background() (or TODO() as a temporary placeholder). That makes the code linear and safe.
Mistake #4: not checking cancellation in long loops.
You added ctx to the signature, proudly passed it through all functions, but forgot to call ctx.Err() anywhere. As a result, cancellation does not work: formally support exists, in practice — it does not. The simplest way to start respecting context is to add a check at “natural points”: on loop iterations, between processing steps, before expensive operations.
Mistake #5: confusing “context” with application data.
There is a temptation to treat context as a “bag where you can shove everything”: current user, currency, sorting settings... But at the introductory level it is better to stay focused: today context is needed for us as a mechanism for canceling an operation. The less you try to turn it into a “global variable on steroids”, the easier it is to maintain the code.
GO TO FULL VERSION