Problem Statement
At Netflix, a single user request fans out to 50+ microservices. If the user cancels their request (closes browser), we need to immediately stop all downstream work to save resources. Implement a service that properly propagates cancellation using Go's context package.
The Three Context Functions
Production Example: HTTP Client with Timeout
Cancellation Propagation Pattern
Context Values: Use Sparingly
Anti-Patterns to Avoid
- ❌ Storing optional function parameters in context
- ❌ Storing database connections in context
- ❌ Storing the context inside a struct field
- ❌ Passing nil context (causes panic)
Follow-up Questions
- Does cancelling a child context cancel the parent?
- What's the difference between
context.Background()andcontext.TODO()? - How do you implement graceful shutdown using context?