1. Request context and its cancellation
If you built a server “on instinct”, the handler looks like an honest worker: it received a request, did the job, and returned a response. But the real world is harsh: the client may close the tab, the mobile network may disappear, a load balancer may cut the connection, while you are still computing, hitting storage, and formatting JSON.
In the end, you spend CPU and memory on a request that no longer exists, and then wonder why the server “does not seem to serve many people”, yet still breathes heavily.
From Go’s point of view, request cancellation is not magic and not a “side effect”. It is a signal that comes through the request’s context.Context. On the server side, Go has long agreed: “if the operation is no longer needed, report it through the context”. This is one of the key elements of reliability: without contexts and deadlines, a server can easily start accumulating work debt and run into resource limits.
What the lifecycle looks like
For visualization, it is useful to keep this lifecycle scheme in mind:
flowchart TD
A[Client sent a request] --> B[Handler received r *http.Request]
B --> C["Take ctx := r.Context()"]
C --> D[Pass ctx into app/storage]
D --> E{Is ctx canceled?}
E -- no --> F[Do the work and respond]
E -- yes --> G[Stop and exit]
What is r.Context() and when is it canceled
r.Context() is the context of a specific HTTP request. You can think of it as “the request lifecycle as a value”. Inside net/http, the context is tied to http.Request (historically, this was done so as not to break the API when context appeared in Go).
The context is useful because it carries two kinds of signals.
First, a cancellation signal: ctx.Done() returns a channel that is closed on cancellation. Second, a cancellation reason: ctx.Err() returns an error explaining what happened (usually context.Canceled or context.DeadlineExceeded).
In practice, r.Context() is canceled in situations like these: the client disconnected, the server begins shutdown, the request timeout expired (at the server level or at the level of an “internal” deadline you set yourself). You do not need to guess exactly what happened — you only need to react correctly: stop working quickly and do nothing extra.
Mini-demo: just read ctx.Err().
package main
import (
"fmt"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Println("ctx err:", r.Context().Err()) // ctx err: <nil>
_, _ = w.Write([]byte("ok\n"))
}
2. Basic rules for handlers
Do not replace r.Context() with context.Background()
When you are just starting out, it seems logical: “I need a context? Fine, I will take context.Background()”. This is almost always a mistake in HTTP code.
context.Background() is the root of the context tree; it is not canceled at all. That is, if you replace r.Context() with Background(), you throw away the main signal: “the client is gone / the request is no longer needed”.
The proper start inside a handler is almost always this: take ctx := r.Context() and then use it as a “pass” into all layers: app layer, storage, external calls. Yes, even if today storage is “a slice in memory” and there are no locks or network calls there. We are building a habit now that will save a lot of time later.
A minimal pattern skeleton:
package main
import (
"net/http"
)
func listTasksHandler(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
if err := ctx.Err(); err != nil {
return
}
_ = ctx // we will pass it into the app layer next
_, _ = w.Write([]byte("todo\n"))
}
Pay attention to if err := ctx.Err(); err != nil { return }. At the beginning of a request this is almost always nil, but such a “guard check” is useful when the handler is complex and may be called under interesting conditions (for example, the client cut the connection almost immediately).
Early return on ctx.Err()
In previous lectures, we actively used guard clauses: “if there is an error, return”. With context, it is the same: “if the context is canceled, return”. The important thing is to remember that cancellation is not a “server error”, but a signal that continuing makes no sense.
It is convenient to introduce a small helper so that the code reads like text:
package main
import "context"
func isCanceled(ctx context.Context) bool {
return ctx.Err() != nil
}
And use it in handlers:
package main
import (
"net/http"
)
func createTaskHandler(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
if isCanceled(ctx) {
return
}
// read JSON, validate, save...
_, _ = w.Write([]byte("created\n"))
}
This approach is good because you do not pretend “I will definitely answer the client” if the client is already gone. Sometimes beginners try to “still return a JSON error” — but if the connection is already closed, you are simply wasting time on a beautiful response package that nobody will see.
Pass ctx through layers
The greatest practical value of r.Context() appears when you thread it through layers. It looks boring: one more parameter gets added to signatures. But you gain control: any link in the chain can stop in time.
Suppose we have a teaching “task tracker” application and a service:
package app
import "context"
type TaskService struct {
// storage and other dependencies
}
func (s *TaskService) List(ctx context.Context) ([]Task, error) {
_ = ctx
return nil, nil
}
Notice: ctx is a method parameter, not a struct field. This matters: a context should not “live” longer than the operation it is meant for. Storing context inside a structure is usually a bad idea: lifecycles get mixed, and the caller loses control over deadlines and cancellation.
At the handler level, it looks like this:
package httpapi
import (
"context"
"net/http"
)
type TaskLister interface {
List(ctx context.Context) ([]any, error) // simplified for the example
}
type Handlers struct {
Service TaskLister
}
func (h *Handlers) list(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
_ = ctx
_, _ = w.Write([]byte("ok\n"))
}
In real code, of course, there will be proper types ([]Task instead of []any), but the idea is the same: the context goes “downward” as the first argument of the operation.
3. Long work and cancellation checking
Sometimes you do work that takes time: filtering a large list, importing, generating a report, “slow” disk writes, a trip to the network (even if we are simulating it with Sleep right now). And even if you do not use select and channels, you can still be “polite” to request cancellation: do the work in chunks and check ctx.Err() between chunks.
Example: simulate a heavy operation in 5 steps.
package app
import (
"context"
"time"
)
func slowCompute(ctx context.Context) error {
for i := 0; i < 5; i++ {
if err := ctx.Err(); err != nil {
return err
}
time.Sleep(200 * time.Millisecond)
}
return nil
}
There is no magic here. But the effect is huge: if the client leaves on the first step, you do not “finish the next second just because you started”. You stop almost immediately and free resources.
And in the handler:
package httpapi
import (
"net/http"
)
func slowHandler(w http.ResponseWriter, r *http.Request) {
if err := slowCompute(r.Context()); err != nil {
return
}
_, _ = w.Write([]byte("done\n"))
}
4. Internal timeouts via context.WithTimeout()
Sometimes request cancellation is an “external event” (the client left). But sometimes you yourself want to limit the time of a specific operation inside the request. For example: “reading tasks from storage should not take more than 300 ms, otherwise it is better to return an error than to keep the connection open”.
It is important to do this exactly like this: use r.Context() as the parent. Then you preserve the relationship between lifecycles: “if the request died — the child operations died too”.
package httpapi
import (
"context"
"net/http"
"time"
)
func handler(w http.ResponseWriter, r *http.Request) {
opCtx, cancel := context.WithTimeout(r.Context(), 300*time.Millisecond)
defer cancel()
_ = opCtx
_, _ = w.Write([]byte("ok\n"))
}
This pattern is valuable for two reasons. First, defer cancel() frees timer resources even if the operation finished earlier. Second, you can distinguish an ordinary error from a timeout: errors.Is(err, context.DeadlineExceeded).
5. Cancellation and the HTTP response
What to do with context.Canceled and context.DeadlineExceeded
It is very tempting to have a “table: which error → which HTTP status”. And yes, that is useful, but it is important not to turn it into bureaucracy. In the context of request cancellation, there is a practical minimum.
In the case of context.Canceled, most often the client has already left, and you physically cannot respond correctly. Therefore, the most reasonable behavior is to stop working and exit silently (possibly log at debug level, but not as a “server error”).
In the case of context.DeadlineExceeded, you need to understand whose deadline it is. If it is the request deadline (for example, the server WriteTimeout or a client timeout) — the picture is similar: the client may already not wait long enough. If it is your internal operation timeout (via WithTimeout), then you may still have time to send a neat error. Often 504 (Gateway Timeout) or 503 (Service Unavailable) is used for this, but in a teaching project the principle is more important: this is not a “500 internal”, because the system worked normally and simply did not fit within the limit.
A small cheat sheet as a guide:
| ctx.Err() | What it usually means | What to do in the handler |
|---|---|---|
|
request is alive, we are working | continue |
|
client left / request canceled | stop working and exit |
|
request or operation deadline expired | stop working; with an internal timeout, you can return a neat error |
Nuance with ResponseWriter
Beginners often have a very human desire: “but I have to return JSON!”. The problem is that if the context is canceled, writing to w may end with an error (for example, broken pipe). Technically, you can ignore the write error, but it is better to not do heavy work for a response that will not be delivered.
So the practical trick looks like this: before forming a large response (sorting, JSON marshaling, tables), check ctx.Err() once more. This is especially useful if the response is large or takes a long time to build.
package httpapi
import (
"net/http"
)
func safeWrite(w http.ResponseWriter, r *http.Request, b []byte) {
if err := r.Context().Err(); err != nil {
return
}
_, _ = w.Write(b)
}
In “real” code, you probably have writeJSON, and you can add such a check there. Not as a “silver bullet”, but as a final sanity filter: “if the request died, do not draw a postcard”.
6. Example
To tie everything into one piece, let us imagine that we have a handler called “export tasks”, which runs a little longer than usual. We create an internal timeout for the operation and do the work in chunks to respect cancellation.
package httpapi
import (
"context"
"net/http"
"time"
)
func exportHandler(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 1*time.Second)
defer cancel()
if err := slowCompute(ctx); err != nil {
return
}
_, _ = w.Write([]byte("exported\n"))
}
Yes, there is no JSON envelope and no pretty errors yet — and that is normal for the focus of today’s lecture. The main goal is to build the habit that any handler works by the contract “I do the work while the context is alive; if it dies, I leave without drama”.
7. Common mistakes when handling request cancellation
Mistake #1: replacing r.Context() with context.Background().
This is often done “just to make it work”, especially when down in the code you need to pass ctx, but “for some reason” it is not there. The price of this replacement is high: you throw away the most important ability — to stop when the request is no longer needed. As a result, the server may continue heavy work after the client leaves and gradually turn into a factory of useless computations.
Mistake #2: checking cancellation once at the beginning and forgetting about it.
if ctx.Err() != nil { return } in the first line of the handler is useful, but it will not save you if a long processing stage follows. A context can be canceled at any moment. Therefore, in “long” logic, chunking is needed: loops, stages, steps — and a check of ctx.Err() between them. Then cancellation works like a stop lever, not as a decorative lamp.
Mistake #3: trying to “definitely return a response” on context.Canceled.
When the client closes the connection, you are no longer obliged to (and often cannot) “say goodbye nicely”. Trying to marshal JSON at that moment, write headers, and log it as a “server error” usually only makes things worse: you spend resources and get noise in the logs. The correct behavior is simply to stop working and exit.
Mistake #4: storing context.Context inside a service or storage structure.
This looks like a convenient “parameter optimization”: put it into a struct once — and do not pass it further. But this mixes lifecycles and deprives the caller of control over deadlines. A context should be a parameter of a specific operation, not a hidden field “somewhere inside the object”. That is why in Go people usually write Do(ctx, ...), not “stored and forgotten”.
Mistake #5: setting a timeout via WithTimeout(), but forgetting cancel().
Even if the operation completed successfully, the timer and its related infrastructure must be released. If you do not use defer cancel(), you can accumulate resources under high load, and it will look like “some weird leak” that you really do not want to hunt down on Friday evening.
GO TO FULL VERSION