Handle cancellation and metadata
Handle cancellation and metadata
A service deadline is a time budget; cancellation tells local work to stop cooperatively. Pass the incoming context into downstream calls. gRPC metadata carries call-associated key/value information such as correlation IDs and credentials, separately from messages. In HTTP, headers serve related purposes. Metadata supplied by a caller is not proof of identity. Verify credentials and propagate only an allowlist.
package main
import ( "context" "errors" "fmt")
func work(ctx context.Context) error { select { case <-ctx.Done(): return ctx.Err() default: return nil }}func main() { ctx, cancel := context.WithCancel(context.Background()) cancel() fmt.Println(errors.Is(work(ctx), context.Canceled))}Cancellation is observed at a cooperative checkpoint. A longer task must check during work and use cancellable I/O. Cancellation does not roll back a completed remote operation; avoid retrying non-idempotent operations blindly. In gRPC use a deadline on calls and return appropriate status errors; the real transport is not installed here.
Expected output:
trueForward only approved metadata
package main
import ( "fmt" "net/http")
func forward(in http.Header) http.Header { out := make(http.Header) if v := in.Get("X-Request-ID"); v != "" && len(v) <= 64 { out.Set("X-Request-ID", v) } return out}func main() { h := make(http.Header) h.Set("X-Request-ID", "demo-1") h.Set("Authorization", "demo-secret") out := forward(h) fmt.Println(out.Get("X-Request-ID"), out.Get("Authorization") == "")}This HTTP allowlist drops authorization instead of indiscriminately forwarding headers. A real request ID also needs format validation and a duplicate-value policy; use authenticated service credentials for downstream access. For gRPC use metadata.FromIncomingContext and metadata.AppendToOutgoingContext with explicit keys. Never log tokens; preserve the parent context rather than replacing it with Background.
Expected output:
demo-1 trueTry it locally
Create a child context of a canceled parent and check that the child reports cancellation.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Service protocols and cloud 03: Handle cancellation and metadata
Check the lesson objective before moving on.
Does cancellation prove a remote write did not happen?
Which metadata should be forwarded?