Coding/Learn/go/go context propagation
Go Foundational Course
01.Introduction, Toolchain & Package main
02.Variables, Zero Values, Constants & iota
03.Control Flow: If with Init Statements & Switch
04.The Unified For Loop & Range Iteration
05.Functions, Multiple Return Values & Named Returns
06.Arrays vs Slices: Dynamic Memory & Headers
07.Maps: Key-Value Hash Tables & Safe Access
08.Pointers & Value vs Pointer Semantics
09.Structs, Receiver Methods & Composition
10.Implicit Interfaces & Duck Typing with Typesafety
11.Explicit Error Handling, Wrapping & Inspection
12.Defer, Panic & Recover: Resource Cleanup
13.Strings, Runes & UTF-8 Encoding Internals
14.Goroutines & The M:N Work-Stealing Scheduler
15.Channels: CSP Concurrency & Pipelines
16.Select Statement, Non-Blocking IO & Timeouts
17.Mutexes, RWMutex & Atomic Primitives
18.Context Propagation, Cancellation & Deadlines
19.JSON Serialization, Tags & net/http Routing
20.Capstone: High-Performance Concurrent Microservice Engine
Course Certificate0%

Complete all lessons to earn

LearnContext Propagation, Cancellation & Deadlines
18 / 20 0%
Lesson 18 of 20
15 mins read

Context Propagation, Cancellation & Deadlines

PreviousNext Lesson
In Plain English

The context package is the standard Go mechanism for managing request lifecycles, cancellation trees, timeouts, and deadlines across goroutine boundaries and microservice boundaries.

The Mental Model

"A context is like a visitor badge with an expiration timer. As a request passes through multiple microservices, if the user cancels, the badge flashes red and all workers stop instantly."

Deep Dive: How It Works

Cancellation Trees: context.WithCancel creates child contexts that automatically cancel when parent cancels.

Timeouts & Deadlines: context.WithTimeout cancels automatically when duration expires.

Convention: ctx is always passed as the first parameter of functions (func DoWork(ctx context.Context, ...)).

Syntax Blueprint

ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
select {
case <-workChan: ...
case <-ctx.Done(): fmt.Println(ctx.Err())
}

Create timeout context, defer cancel(), and select on <-ctx.Done() for early aborts.

PointCore Rules to Remember

Point star
Explicit Lifecycle: Context signals when an operation should stop work and free resources.
Point star
Always Defer Cancel: Always call defer cancel() right after WithTimeout or WithCancel to prevent timer leaks.
Point star
First Parameter: Pass context as the first explicit function parameter, never inside a struct.

Common Beginner Traps & How to Fix Them

Mistake:Storing context.Context inside a struct field instead of passing it as a function parameter.

Why it happens: Encapsulating context inside structs obscures request lifecycles and creates stale reference bugs.

How to fix: Pass ctx context.Context as the first parameter in methods.

Pro Tip: Use context.WithoutCancel(ctx) (Go 1.21+) when you need to spawn background tasks that outlive the parent request.

Live Interactive Example

Hit Run Code to see it live
Graceful Task Cancellation with Context
Go 1.22 / Runtime
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Output Console
Click "Run Code" to view the rendered output.
How it works: The 10ms timeout expired before the 100ms task completed, triggering <-ctx.Done().

Your Turn: Micro Challenge

No pressure! Edit the starter code below and test your solution with instant feedback.

Micro Exercise

Manual Context Cancellation

  • PointCreate a context with context.WithCancel(context.Background()).
  • PointCall cancel() immediately.
  • PointCheck <-ctx.Done() inside a select block and print "Cancelled successfully: " followed by ctx.Err().
1
2
3
4
5
6
7
8
9
10
11
Sandbox Output
Click "Run & Check" to test your solution.

Finished reading and practicing?

Mark this lesson as completed to update your course progress.

PreviousNext Lesson
Overview100 SheetLearnCertificates