Problem Statement
Master context.Context for cancellation, timeouts, and request-scoped values in Go applications.
Context Interview Questions
Q1: Why should context.Context be the first argument?
Answer: Convention established by Go team. Makes it immediately clear that the function supports cancellation. Example: func DoWork(ctx context.Context, args ...)
Q2: Two ways a Context can be cancelled?
Q3: Does cancelling parent cancel children?
Answer: Yes. Cancellation propagates down the tree.
Q4: Does cancelling child cancel parent?
Answer: No. Cancellation only propagates downward.
Q5: What is context.WithValue used for?
Use for: Request-scoped data (trace IDs, auth tokens).
NOT for: Optional function parameters, database connections.
Q6: Is context.Context thread-safe?
Answer: Yes, fully immutable and safe for concurrent use.
Q7: How to handle timeout in select?
Q8: What happens with nil context?
Q9: context.Background() vs context.TODO()?
Answer: Semantically equivalent, both return empty contexts.
- Background(): Use at top-level (main, init, tests)
- TODO(): Placeholder when unsure which context to use
Q10: Should you store Context in a struct?
Answer: No. Context should flow through call stack, not be stored.