Golang / GoLang Concurrency Mastery Interview Questions
Write a complete example of implementing operation timeouts in Go using select.
Timeouts are critical for preventing goroutine leaks in service calls. The idiomatic Go approach uses context.WithTimeout (production preferred) or time.After (quick one-off). A crucial detail: the result channel must be buffered to avoid a goroutine leak when the timeout fires first.
// Pattern 1: context.WithTimeout (production preferred)
func callService(ctx context.Context, req Request) (Response, error) {
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel() // ALWAYS: releases resources even on happy path
result := make(chan Response, 1) // buffered — prevents goroutine leak!
errCh := make(chan error, 1)
go func() {
resp, err := doServiceCall(ctx, req) // honours context cancellation
if err != nil { errCh <- err; return }
result <- resp
}()
select {
case resp := <-result: return resp, nil
case err := <-errCh: return Response{}, err
case <-ctx.Done(): return Response{}, fmt.Errorf("service: %w", ctx.Err())
}
}
// Pattern 2: time.After (simpler for standalone use)
func computeWithTimeout(input int) (int, error) {
result := make(chan int, 1) // MUST be buffered — see below
go func() {
result <- expensiveCompute(input)
}()
select {
case v := <-result:
return v, nil
case <-time.After(3 * time.Second):
// The goroutine is NOT killed — it still runs to completion
// Buffered channel lets it send and exit without blocking
return 0, errors.New("computation timed out")
}
}
// WHY unbuffered channel leaks:
// result := make(chan int) ← unbuffered
// If timeout fires first, the goroutine blocks forever on 'result <-'
// (nobody receives) → GOROUTINE LEAK
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...
