Golang / GoLang Concurrency Mastery Interview Questions
How does context.Context enable clean goroutine cancellation and why is 'defer cancel()' critical?
context.Context is Go's standard mechanism for propagating cancellation, deadlines, and request-scoped values across API boundaries. Every blocking or long-running function should accept a context as its first parameter.
// Creating contexts ctx, cancel := context.WithCancel(context.Background()) defer cancel() // ALWAYS defer â releases resources even on the happy path ctx2, cancel2 := context.WithTimeout(context.Background(), 5*time.Second) defer cancel2() ctx3, cancel3 := context.WithDeadline(context.Background(), time.Now().Add(30*time.Second)) defer cancel3() // Worker that respects cancellation func worker(ctx context.Context, jobs <-chan Job) error { for { select { case <-ctx.Done(): return ctx.Err() // context.Canceled or context.DeadlineExceeded case job, ok := <-jobs: if !ok { return nil } if err := processWithCtx(ctx, job); err != nil { return err } } } } // Cancellation propagates through the context tree parent, cancelParent := context.WithCancel(context.Background()) child1, _ := context.WithTimeout(parent, 10*time.Second) child2, _ := context.WithCancel(parent) cancelParent() // cancels parent, child1, AND child2 simultaneously // What ctx.Err() returns: // nil â context still active // context.Canceled â cancel() was called // context.DeadlineExceeded â deadline or timeout passed
Why always defer cancel(): failing to call cancel() leaks the goroutine that monitors the context for deadline expiry. This goroutine runs until either cancel() is called or the parent context is cancelled. In a high-traffic server, thousands of leaked monitor goroutines accumulate quickly.
More Related questions...