Skip to content

Go Context Deadline: Timeout Not Working

DodaTech Updated 2026-06-24 1 min read

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.
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

  1. Using head and tail instead of pattern matching, causing runtime errors on empty lists
  2. Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
  3. Using return to 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

**What is the difference between WithTimeout and WithDeadline?**

WithTimeout sets duration. WithDeadline sets absolute time.

Can I combine parent contexts?

Yes. parent context deadline cascades to child.

What happens if I don't call cancel?

Resources leak until parent context is cancelled.


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