context deadline exceeded
Go Programming Language
Severity: ModerateWhat Does This Error Mean?
This error means an operation took too long and hit its timeout. Go's context system cancelled the operation before it could finish. This is expected behavior — you need to handle it gracefully.
Affected Models
- Go 1.21
- Go 1.22
- Go 1.23
- Go 1.24
Common Causes
- A network request (HTTP, database, gRPC) took longer than the context timeout allows
- The timeout value is too short for the operation being performed
- A slow or unresponsive external service is not responding in time
- A parent context was cancelled (e.g. HTTP request was cancelled by the client)
- context.WithTimeout or context.WithDeadline was used and the deadline passed
How to Fix It
-
Check where the context is created and what timeout is set.
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) — is 5 seconds enough for this operation?
-
Increase the timeout if the operation legitimately needs more time.
Be careful — raising timeouts too high can make failures slow to detect. Balance is key.
-
Check ctx.Err() after the call to distinguish deadline exceeded from cancellation.
ctx.Err() == context.DeadlineExceeded means timeout. ctx.Err() == context.Canceled means the caller cancelled it.
-
Investigate why the dependency is slow — database query, HTTP endpoint, or disk I/O.
Adding logging around slow calls helps identify which operation is the bottleneck.
-
Implement retry logic with exponential backoff for transient timeouts.
Libraries like github.com/cenkalti/backoff make this easy. Don't retry forever — set a max attempts limit.
When to Call a Professional
If deadlines are being hit frequently in production, involve your team. This often signals a slow dependency or a misconfigured timeout. Auditing timeouts system-wide is a senior-level architectural task.
Frequently Asked Questions
What is the difference between context.DeadlineExceeded and context.Canceled?
DeadlineExceeded means the time limit ran out before the operation finished. Canceled means someone explicitly called the cancel() function. Both are normal — check ctx.Err() to tell them apart.
Should I always pass a context to every function?
Yes — this is Go best practice. Passing context.Context as the first parameter allows callers to cancel long-running operations. The standard library and most Go libraries expect this pattern.
What happens if I ignore the context and don't check ctx.Done()?
Your function will keep running even after the deadline passes. The caller gets the error, but your goroutine keeps consuming resources. Always check ctx.Done() in long-running loops or blocking operations.