DevPath
Foundation lesson · 14 min

Carry cancellation through Go services

Propagate request context and bound work across service calls.

A context follows the request

Pass the incoming context to database and HTTP operations so they can stop when the client disconnects or a deadline expires. Do not replace it with context.Background inside a request path; that severs cancellation.

Own the deadline

Set a deadline at a boundary that understands the latency budget. Defer the cancel function to release timer resources. A child deadline cannot outlive its parent's deadline. Check ctx.Err when distinguishing cancellation from another failure.

ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
defer cancel()
rows, err := db.QueryContext(ctx, query)

Propagate through every layer

An HTTP handler passes r.Context to the service, which passes it to the repository and outbound client. A single call using a background context breaks the chain. A timeout at the handler can cap the entire operation; a shorter child timeout can reserve time for a slow dependency. Always defer the cancel function created by WithTimeout.

Test cancellation, not just time

Use a fake dependency that waits on ctx.Done. Cancel the parent context and assert that the service returns promptly with a cancellation error and no further work. Avoid tests that only sleep for a fixed duration; they are slower and less reliable. For database rows, close them and check rows.Err after iteration as well.

Check your understanding

What happens if a handler uses context.Background for a slow database query?

Show explanation

The query no longer observes request cancellation or its deadline and may keep using resources after the request ends.

Try it at foundation level

Sketch a handler that passes its request context through two service calls. Mark where cancellation and a timeout stop work.

Check your work

Both calls receive the derived context; every exit path cancels it; no background task outlives the request without an explicit owner.

Self-guided practice. This does not record assessed mastery.

Put this lesson into practice

A related activity in this module at mid level.

Try: Fan out with a bounded worker pool

Further reading

Primary references for this module. Check the current version when behavior or framework guidance may have changed.