context.DeadlineExceeded
GoERRORCommonContext

context deadline exceeded

Quick Answer

Use errors.Is(err, context.DeadlineExceeded) to detect timeouts and consider increasing the deadline or optimizing the operation.

What this means

Returned when a context deadline elapses before the operation completes. Indicates the operation took longer than the allotted time.

Why it happens
  1. 1context.WithTimeout duration elapsed before the operation returned
  2. 2context.WithDeadline absolute time passed while waiting on I/O or a lock

Fix

Detect and handle timeout

Detect and handle timeout
if errors.Is(err, context.DeadlineExceeded) {
    log.Println("operation timed out")
    return ErrTimeout
}

Why this works

Mapping to a domain-specific error keeps callers decoupled from the context package.

Code examples
Detectgo
ctx, cancel := context.WithTimeout(
    context.Background(), time.Second)
defer cancel()
err := doWork(ctx)
if errors.Is(err, context.DeadlineExceeded) {
    fmt.Println("timed out")
}
Increase timeoutgo
ctx, cancel := context.WithTimeout(
    context.Background(), 10*time.Second)
defer cancel()
HTTP client timeoutgo
client := &http.Client{Timeout: 5 * time.Second}
resp, err := client.Get(url)
Sources
Official documentation ↗

Go standard library

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Go errors