Go Context Deadline: Timeout Not Working
In this tutorial, you'll learn about Go Context Deadline: Timeout Not Working. We cover key concepts, practical examples, and best practices.
Context deadline -- Use context.WithDeadline or context.WithTimeout to enforce time limits on operations.
The Problem
Creating a context with timeout does not automatically cancel it. You must pass the context to operations that respect cancellation (DB queries, HTTP calls).
Wrong
ctx := context.Background()
db.QueryContext(ctx, "SELECT pg_sleep(10)") // Runs for 10s!
Output:
// No deadline. Query runs full 10 seconds.
Right
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
db.QueryContext(ctx, "SELECT pg_sleep(10)") // Cancelled after 2s
Output:
// Query cancelled after 2 seconds. Returns error.
Prevention
- Use WithTimeout or WithDeadline to set time limits
- Always call cancel() to release resources
- Pass context to all blocking operations
- Check ctx.Err() after operation to detect cancellation
- Deadline exceeded returns context.DeadlineExceeded
Common Mistakes with context deadline
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists - Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
- Using
returnto exit a function early instead of wrapping a pure value in the monad
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