Golang / Golang Internals and Memory Management Interview Questions
How does context.Context work and when do you use each context type?
context.Context carries deadlines, cancellation signals, and request-scoped values across API boundaries and goroutines. It is the standard way to propagate cancellation in Go services.
// Context hierarchy â child inherits cancellation from parent ctx := context.Background() // root â never cancelled, never has deadline // WithCancel â explicit cancellation ctx1, cancel1 := context.WithCancel(ctx) defer cancel1() // ALWAYS defer cancel to prevent goroutine leaks // WithTimeout â automatically cancelled after duration ctx2, cancel2 := context.WithTimeout(ctx, 5*time.Second) defer cancel2() // WithDeadline â cancelled at absolute time deadline := time.Now().Add(10 * time.Second) ctx3, cancel3 := context.WithDeadline(ctx, deadline) defer cancel3() // WithValue â carry request-scoped data (use sparingly) type ctxKey string ctx4 := context.WithValue(ctx, ctxKey("traceID"), "abc-123") traceID := ctx4.Value(ctxKey("traceID")).(string) // Propagate through function calls func fetchData(ctx context.Context, url string) ([]byte, error) { req, _ := http.NewRequestWithContext(ctx, "GET", url, nil) resp, err := http.DefaultClient.Do(req) // cancels if ctx is done if err != nil { return nil, err } defer resp.Body.Close() return io.ReadAll(resp.Body) } // Checking cancellation in a long loop func processItems(ctx context.Context, items []Item) error { for _, item := range items { select { case <-ctx.Done(): return ctx.Err() // context.DeadlineExceeded or context.Canceled default: process(item) } } return nil }
Rules: (1) always pass Context as the first argument, never store it in a struct (for long-lived objects use context.Background() stored at service init). (2) always call the cancel function to avoid goroutine leaks — even if the deadline or timeout fires naturally. (3) use context.WithValue only for truly request-scoped data (trace IDs, auth tokens) — not as a general parameter-passing mechanism.
More Related questions...