Go's context Package: Timeouts, Cancellation, and Stopping Work on Time
How context.Context propagates deadlines and cancellation across goroutines and HTTP calls so abandoned work never leaks.
You'll learn why almost every real Go function takes ctx context.Context as its first argument, how context.WithTimeout and defer cancel() prevent goroutine leaks, and how to listen for <-ctx.Done() inside long-running loops. Assumes familiarity with goroutines and channels.
1. The problem: orphaned work after a user leaves
Suppose a user hits your /search endpoint. Your server spins up a database query and two external API calls. Half a second later, the user gets impatient and closes the browser tab.
Without cancellation, your server keeps running that database query and those API calls anyway, burning CPU, memory, and database connections for a response nobody will ever read. Under heavy load, orphaned goroutines pile up until your server runs out of memory.
Go solves this with context.Context: a small, thread-safe cancellation signal passed down the call chain as the first parameter (ctx context.Context). When the user disconnects—or a deadline expires—ctx.Done() closes, telling every downstream function to stop and clean up.
2. Setting a deadline with context.WithTimeout
context.WithTimeout creates a child context that automatically cancels after a duration (say, 200ms)—and gives you a cancel function so you can clean up its internal timer early if work finishes sooner:
package main
import (
"context"
"fmt"
"time"
)
func slowWork(ctx context.Context) error {
select {
case <-time.After(500 * time.Millisecond):
fmt.Println("Work finished!")
return nil
case <-ctx.Done():
return ctx.Err()
}
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 150*time.Millisecond)
defer cancel()
if err := slowWork(ctx); err != nil {
fmt.Println("Stopped:", err)
}
}Stopped: context deadline exceededLook at two crucial rules in that snippet:
defer cancel()right away. Even ifslowWorkfinishes in 10ms,WithTimeoutallocates an internal timer that stays alive until the deadline unless you callcancel(). Alwaysdefer cancel().- Check
<-ctx.Done()insideselect. Creating a context does not magically kill a goroutine from the outside. Functions have to cooperate by checkingctx.Done()(or passingctxto stdlib functions likehttp.NewRequestWithContextordb.QueryContext, which already listen to it).
Change 150*time.Millisecond to 700*time.Millisecond and run go run .—now slowWork finishes in 500ms and defer cancel() cleans up the remaining 200ms timer.
3. Rules of thumb for context.Context
- First parameter, never in a struct: Write
func FetchUser(ctx context.Context, id string), never storectxinside aServicestruct (except rare request-scoped structs). context.Background()vscontext.TODO(): Usecontext.Background()at the top entry point (main, tests, background jobs). Usecontext.TODO()temporarily when wiring a function that doesn't receive actxyet.- In HTTP handlers, use
r.Context():net/httpautomatically cancelsr.Context()the moment the client disconnects or closes their browser tab.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
Forgot defer cancel() after WithTimeout | Timer leaks in memory until deadline expires | Always write defer cancel() on the very next line |
Ignored ctx inside a long loop | Function keeps running after timeout/disconnect | Check ctx.Err() or select { case <-ctx.Done(): return ctx.Err() default: } |
Stored ctx in a long-lived struct | Later requests inherit an already-canceled context | Pass ctx as the first argument to each method |
Practice
- What does
ctx.Err()return when aWithTimeoutcontext expires vs whencancel()is called manually?
Answer: context.DeadlineExceeded when the timeout expires; context.Canceled when cancel() is called manually.
What you learned
context.Contextcarries deadlines and cancellation signals down the call stack.- Always
defer cancel()immediately aftercontext.WithTimeoutorcontext.WithCancel. - Pass
ctxas the first function parameter and listen to<-ctx.Done()in long-running work.
Video walkthrough
YouTubeClick play to load video (YouTube)