Use context.Context for Deadlines and Cancellation
Pass context.Context as the first parameter, create deadlines with context.WithTimeout, and always defer cancel(). After this, slow or abandoned work stops instead of hanging.
Course content
Sign in to save your progress.
-
Interfaces and Standard Abstractions
-
Interfaces Are Satisfied Implicitly
-
Read and Stream With io.Reader and io.Writer
-
-
-
Context, Timeouts, and Cancellation
-
Use context.Context for Deadlines and Cancellation
-
Set Timeouts on HTTP Clients and Server Handlers
-
-
-
Goroutines, Channels, and Coordination
-
Run Concurrent Work Safely With sync.WaitGroup
-
Coordinate Pipelines and Timeouts With Channels and select
-
-
-
Structured Logging and Databases
-
Write Structured JSON Logs With log/slog
-
Query Relational Data Safely With database/sql
-
-
-
Middleware and Production-Ready Services
-
Wrap HTTP Handlers With Middleware
-
Build a Multi-Route Service With Graceful Shutdown
-
-
-
Generics, Transactions, Timers, and Test Doubles
-
Generics, Constraints, and slices/maps Packages
-
SQL Transactions and Connection Pool Limits
-
Timers, Tickers, and Avoiding time.After Leaks
-
Testing With Interface Fakes, t.TempDir, and testdata
-
-
Imagine an HTTP request hits your API, kicks off a slow PostgreSQL query and two downstream HTTP calls, and the user closes their browser tab 40 milliseconds later. Without cancellation propagation, all three backend calls keep running to completion—holding database locks, burning CPU, and occupying connection pool slots for a response nobody will ever read.
Go solves cancellation and deadlines across every package boundary with one standard value: context.Context, passed explicitly as the first argument (ctx context.Context) to every I/O function.
Skip ahead
If you already derive child contexts with context.WithTimeout, always call defer cancel(), and check ctx.Done() in worker loops, move on to "Set Timeouts on HTTP Clients and Server Handlers."
Experiment 1: Parent cancellation cascades down to every child
Contexts form a tree. When a parent context cancels (such as r.Context() when a user disconnects), every child derived from it cancels immediately—even if the child still had 5 seconds left on its own timeout:
package main
import (
"context"
"fmt"
"time"
)
func main() {
parent, cancelParent := context.WithCancel(context.Background())
child, cancelChild := context.WithTimeout(parent, 5*time.Second)
defer cancelChild()
cancelParent() // client disconnected!
<-child.Done()
fmt.Printf("parent=%v child=%v\n", parent.Err(), child.Err())
}
parent=context canceled child=context canceled
Cancellation only flows downward, never upward: if a child's 200 ms timeout expires, sibling contexts and the parent request stay alive so your handler can gracefully return a fallback response instead of aborting the whole request.
Experiment 2: Setting a per-call timeout and always calling defer cancel()
Every call to context.WithTimeout or context.WithCancel registers cleanup state on the parent context (and a timer for timeouts). Always call defer cancel() on the very next line—even if you expect the work to finish quickly—so that timer and parent link are freed immediately instead of lingering until the deadline:
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
defer cancel()
rows, err := db.QueryContext(ctx, "SELECT id, name FROM orders WHERE user_id = $1", userID)
if err != nil {
if errors.Is(err, context.DeadlineExceeded) {
http.Error(w, "upstream timeout", http.StatusGatewayTimeout)
return
}
http.Error(w, "query failed", http.StatusInternalServerError)
return
}
Notice the subtle trap if you accidentally write context.WithTimeout(context.Background(), 2*time.Second) inside a handler instead of using r.Context(): you just severed the tree! Now if the HTTP client disconnects at 20 ms, your database query keeps grinding for the full 2 seconds.
Experiment 3: Checking ctx.Done() in your own loops
Passing ctx into db.QueryContext or http.NewRequestWithContext lets those libraries abort automatically, but Go never preempts your own pure-Go loops automatically. Inside a long worker loop, check ctx.Done() explicitly:
for _, item := range batch {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
process(item)
}
Experiment 4: Background, TODO, and WithoutCancel
r.Context()/ incomingctx: Use this 99% of the time so every downstream call obeys the caller's deadline.context.Background(): Only at top-level roots (main(), startup initialization, top-level tests).context.WithoutCancel(ctx): For rare async audit/telemetry work that should keep request trace metadata after the HTTP response finishes—always wrap it in its ownWithTimeoutso it cannot hang forever!
Common mistakes
- Storing
ctxin a struct field (type Service struct { ctx context.Context }): Ties every request to one stale lifetime. Always passctxas the first parameter of each method. - Omitting
defer cancel()afterWithTimeout: Leaks timers and parent references until the timeout expires;go vetwarns about this directly. - Using
context.WithValuefor required dependencies like*sql.DB: Hides dependencies and panics on type mismatches; pass real dependencies as explicit parameters or struct fields.
💡 Tip
In Go 1.21+, context.WithTimeoutCause(parent, 2*time.Second, ErrSlowUpstream) lets you attach a custom cause error readable via context.Cause(ctx)—making logs immediately tell you which timeout fired.
What happens if you skip this step
Services that pass context.Background() inside handlers keep hammering slow databases and upstream APIs long after users hit refresh—turning a brief slowdown into a full retry storm and connection-pool exhaustion.
An HTTP handler creates ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) instead of deriving from r.Context(). What happens to the database query if the user closes their browser 100 ms into the request?
About
Pass context.Context as the first parameter, create deadlines with context.WithTimeout, and always defer cancel(). After this, slow or abandoned work stops instead of hanging.
- Duration
- 5 min
- Last update
- 11/27/2026
Comments
Sign in to commentNo comments yet.