Go Context WithTimeout: Context Not Cancelled
In this tutorial, you'll learn about Go Context WithTimeout: Context Not Cancelled. We cover key concepts, practical examples, and best practices.
Context timeout cleanup -- Always call cancel() in a defer statement to release context resources when using WithTimeout.
The Problem
context.WithTimeout returns a cancel function. If you don't call it, the context and its goroutine remain active until the timeout expires. Always defer cancel().
Wrong
ctx, _ := context.WithTimeout(context.Background(), 10*time.Minute)
// Do something quick...
// Context stays for 10 minutes!
Output:
// Cancel function not called. Resources held for 10 min.
Right
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
defer cancel() // Released when function returns
result, err := doSomething(ctx)
Output:
// Context cancelled immediately when function returns
Prevention
- Always defer cancel() for WithTimeout contexts
- cancel() is idempotent -- safe to call multiple times
- Early return? cancel() still runs via defer
- Check ctx.Err() to distinguish DeadlineExceeded vs Canceled
- For RPC calls, set timeout based on expected latency
Common Mistakes with context with timeout
- Using
returnto exit a function early instead of wrapping a pure value in the monad - Mixing let bindings with <- bindings in do notation, producing type errors
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro