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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
