By Abhijith N M · Reviewed 24 October 2026 · Editorial standards
As soon as work runs in the background or on behalf of a caller, a new question appears: what if the caller cancels, the deadline passes, or the whole server shuts down? A goroutine that keeps working after its result stopped mattering is wasted work, and it can hold resources long after anyone wanted the answer.
Go's answer is the context. A context carries a cancellation signal and an optional deadline down a call chain. Any function that receives one can ask "should I still be working?" and stop early.
Contexts form a tree. The root is context.Background(). You derive a child with context.WithCancel, context.WithTimeout or context.WithDeadline. Cancelling a parent closes the Done channels of every child below it.
context.Background() is the root: it is never cancelled and it carries no deadline. context.WithTimeout(parent, duration) returns a child context plus a cancel function. Always call cancel, usually with defer, even when the deadline makes it redundant: it releases the timer.
This program gives pretend work five seconds, but only a twenty millisecond deadline. The work checks ctx.Done() and gives up:
package main
import (
"context"
"fmt"
"time"
)
// expensiveWork pretends to call a slow service that respects cancellation.
func expensiveWork(ctx context.Context) error {
select {
case <-time.After(5 * time.Second):
return nil
case <-ctx.Done():
return ctx.Err()
}
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
defer cancel()
if err := expensiveWork(ctx); err != nil {
fmt.Println("gave up:", err)
}
}The output is stable because the deadline is twenty milliseconds and the pretend work needs five seconds: only one case can be ready. That is the same determinism rule you learned for goroutines. When you write concurrent code, make examples where exactly one outcome is possible.
context.WithCancel(parent) is the manual version: nothing expires, and you cancel by calling the returned function. Cancellation propagates downward. Cancelling a child does not cancel its parent or its siblings.
package main
import (
"context"
"fmt"
"sort"
"sync"
)
func main() {
ctx, cancel := context.WithCancel(context.Background())
results := make(chan string, 2)
var wg sync.WaitGroup
for _, name := range []string{"worker-a", "worker-b"} {
wg.Add(1)
go func(name string) {
defer wg.Done()
<-ctx.Done()
results <- name + " stopped: " + ctx.Err().Error()
}(name)
}
cancel()
wg.Wait()
close(results)
lines := make([]string, 0, 2)
for line := range results {
lines = append(lines, line)
}
sort.Strings(lines)
for _, line := range lines {
fmt.Println(line)
}
fmt.Println("main: all workers stopped")
}| Function | Its Done channel closes when |
|---|---|
context.Background() | never: it is the root of the tree |
context.WithCancel(parent) | you call the returned cancel function |
context.WithTimeout(parent, d) | the duration d passes, or cancel is called |
context.WithDeadline(parent, t) | the clock reaches t, or cancel is called |
Context is a value you pass, not a setting you store. The convention is short and every Go programmer follows it:
func worker(ctx context.Context, name string). A reader sees at once that the function can be cancelled.nil panics as soon as someone calls ctx.Done().select that also watches the work channel.defer cancel(), to release the timer or signal parents that nothing else is waiting.A server should stop in a controlled way when the program is asked to quit. http.Server.Shutdown(ctx) stops accepting new connections and waits for in-flight requests to finish. signal.NotifyContext turns Ctrl+C into a cancelled context, so the same mechanism you learned above drives the shutdown.
package main
import (
"context"
"fmt"
"net/http"
"os"
"os/signal"
"time"
)
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, `{"status":"ok"}`)
})
server := &http.Server{Addr: ":8080", Handler: mux}
// Catch Ctrl+C and turn the interrupt into a cancelled context.
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
go func() {
fmt.Println("Penny API listening on http://localhost:8080")
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
fmt.Println("server error:", err)
}
}()
<-ctx.Done()
stop()
fmt.Println("interrupt received, shutting down...")
// The old ctx is already cancelled, so Shutdown needs a fresh context
// with its own deadline.
shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := server.Shutdown(shutdownCtx); err != nil {
fmt.Println("shutdown error:", err)
}
fmt.Println("goodbye")
}Read the order once more: create the server, run ListenAndServe in a goroutine, wait for the interrupt in main, then call Shutdown with a fresh deadline. ListenAndServe returns http.ErrServerClosed after a normal shutdown, so the goroutine checks for that error and stays quiet.
Change the timeout example so the work finishes first: make expensiveWork return after ten milliseconds and keep the twenty millisecond deadline. Print finished in time when it returns nil. Run it, then set the deadline back to one millisecond and explain the difference. Next, add a third worker to the cancellation example and confirm that all three report the same error, in sorted order.
Key takeaways
A context carries cancellation and deadlines down a call chain; context.Background() is the root.
WithTimeout closes Done when the deadline passes; WithCancel closes it when you call cancel.
Cancelling a parent cancels every child context below it, and ctx.Err() says why it stopped.
Pass ctx as the first parameter, never pass nil, check Done around slow work, and always call cancel.
http.Server.Shutdown needs a fresh context with its own deadline to let in-flight requests finish.
Written and edited by the nexGenCoders team. Spotted a mistake? Tell us and we will fix it.
Don't lose this lesson
Create a free account to save your progress, keep your streak, and work toward a shareable certificate.