Learn / Go Service Engineering
Context and Cancellation
Make timeouts and shutdown signals flow through every expensive operation.
Course: Go Service Engineering. Level: Intermediate. Topic: Reliable services.
Stage: basic - Basic lifecycle control - Context propagation and cancellation. Make request deadlines and shutdown signals flow through every expensive operation.
Outcomes
- Pass context intentionally.
- Set operation-level deadlines.
- Stop work cleanly during deploys.
Concepts
- context
- deadline
- goroutine
- graceful shutdown
Concept flow
Show how context propagation and cancellation moves from trigger to implementation outcome in Go Services.
- HTTP request
- Service method
- Database call
- Worker
- Shutdown signal
Session flow
- Model context (concept, 9 min) — Name the decisions behind context before writing code.
- Pass context intentionally.
- Explain where context belongs in ticket processing platform.
- Build the vertical slice (walkthrough, 15 min) — Implement the smallest useful slice in jobs/worker.go.
- Set operation-level deadlines.
- Connect deadline to a working example.
- Verify and harden (exercise, 10 min) — Log cancellation separately from failure.
- Stop work cleanly during deploys.
- Record one risk or follow-up before moving on.
Code example
Go in jobs/worker.go.
package jobs
import (
"context"
"log/slog"
"time"
)
type Job struct {
ID string
Payload []byte
}
func Run(ctx context.Context, jobs <-chan Job, handle func(context.Context, Job) error) {
for {
select {
case <-ctx.Done():
return
case job, ok := <-jobs:
if !ok {
return
}
jobCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
if err := handle(jobCtx, job); err != nil {
slog.Error("job failed", "id", job.ID, "error", err)
}
cancel()
}
}
}
Walkthrough examples
- Context and Cancellation in a ticket processing platform — A team is extending a small Go service plus worker and needs this lesson's pattern to be clear enough for review, testing, and future maintenance.
- File: jobs/worker.go
- File: tests/context-and-cancellation.spec
- File: docs/go-services/context-and-cancellation.md
- Start from the provided Go snippet and make the intent visible in names and boundaries.
- Apply the checklist item "Thread context through calls" before adding extra behavior.
- Write down how the implementation changes when deadline fails or becomes slow.
Practice
- Add a timeout to one handler path.
- Close the jobs channel in a worker test and assert the loop exits.
- Log cancellation separately from failure.
Checklist
- Thread context through calls
- Add deadline
- Handle shutdown
- Verify logs
Quiz prompts
- What should happen when a request context is canceled? — Context cancellation is the signal to release resources and stop work tied to a request or shutdown.
- A teammate wants to hide context inside a convenient helper. What should you check first? — Place context at the boundary that keeps ticket processing platform behavior explicit, testable, and reviewable.
- Which artifact best proves this Go Services lesson is ready for review? — Production-ready learning needs evidence: a test, trace, command, screenshot, or log that catches the risk again.
- Basic lifecycle control: a teammate says the happy path works, but "Context threading" is still implicit. What should you ask for before merging? — Context threading belongs in the basic stage only when the decision is visible, testable, and tied to a realistic failure mode.
- A reviewer has five minutes to evaluate this basic Go Services slice. Which evidence is strongest? — Add lifecycle control to a Go service path: propagated context, dependency timeout, worker cancellation proof, and shutdown log evidence.
Flashcards
- Basic lifecycle control: what decision does "Context threading" force you to make? Pass context through service, database, worker, and external API calls without hiding ownership. Evidence prompt: Trace one request context from handler to database call and remove any background context misuse.
- Basic lifecycle control: what decision does "Operation deadlines" force you to make? Set local deadlines for slow dependencies so one request cannot exhaust service resources. Evidence prompt: Add an operation-level timeout and test the timeout branch.
- Basic lifecycle control: what decision does "Shutdown proof" force you to make? Prove workers and in-flight requests stop gracefully during deployment. Evidence prompt: Write a test or manual proof that a worker exits when its context is canceled.
- In Go Services, what should you remember about context? context matters here because it supports "Pass context intentionally.".
- In Go Services, what should you remember about deadline? deadline matters here because it supports "Set operation-level deadlines.".
- In Go Services, what should you remember about goroutine? goroutine matters here because it supports "Stop work cleanly during deploys.".
- In Go Services, what should you remember about graceful shutdown? graceful shutdown matters here because it supports "Pass context intentionally.".
Labs
- Ship a context and cancellation slice — Extend a small Go service plus worker with a small but reviewable feature that proves the lesson's architecture in code.
- Add lifecycle control to a Go service path: propagated context, dependency timeout, worker cancellation proof, and shutdown log evidence.
- Trace one request context from handler to database call and remove any background context misuse.
- Add an operation-level timeout and test the timeout branch.
- Write a test or manual proof that a worker exits when its context is canceled.
- Add a timeout to one handler path.
- Close the jobs channel in a worker test and assert the loop exits.
- The lab demonstrates the basic lifecycle control outcome without skipping earlier contract evidence.
- Each subtopic has a concrete artifact: Context threading, Operation deadlines, Shutdown proof.
- The review notes explain how this level changes ownership, verification, or operational risk.
Challenge
- Review-ready context and cancellation (Stretch) — Add lifecycle control to a Go service path: propagated context, dependency timeout, worker cancellation proof, and shutdown log evidence.
- All checklist items are either implemented or documented with a reason.
- The change can be understood from jobs/worker.go plus one short note.
- The concept diagram names ownership, failure handling, and verification points.
- A teammate could run the verification steps without asking for hidden context.
Canonical lesson URL