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?
// 1. Manual cancel
ctx, cancel := context.WithCancel(parent)
cancel() // Explicit cancellation
// 2. Timeout/Deadline
ctx, cancel := context.WithTimeout(parent, 5*time.Second)
ctx, cancel := context.WithDeadline(parent, time.Now().Add(5*time.Second))Q3: Does cancelling parent cancel children?
parent, cancelParent := context.WithCancel(context.Background())
child, _ := context.WithCancel(parent)
cancelParent() // Both parent AND child are cancelledAnswer: 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?
type ctxKey string
const traceIDKey ctxKey = "traceID"
ctx := context.WithValue(parent, traceIDKey, "abc-123")
traceID := ctx.Value(traceIDKey).(string)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?
select {
case result := <-workChan:
return result, nil
case <-ctx.Done():
return nil, ctx.Err() // context.DeadlineExceeded or context.Canceled
}Q8: What happens with nil context?
var ctx context.Context = nil
ctx.Done() // PANIC: nil pointer dereferenceQ9: 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?
// ❌ Anti-pattern
type Server struct {
ctx context.Context
}
// ✅ Pass through function arguments
func (s *Server) Handle(ctx context.Context, req Request)Answer: No. Context should flow through call stack, not be stored.