go network_error ai_generated true

Get "https://api.example.com/data": context deadline exceeded

ID: go/http-request-canceled-context

Also available as: JSON · Markdown · 中文
80%Fix Rate
88%Confidence
0Evidence
2024-03-12First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.18 active — — —
1.21 active — — —
1.22 active — — —

Root Cause

The http.Client request context timed out or was canceled before the server responded. Often caused by a too-short context.WithTimeout, a slow upstream, or reusing a canceled context across requests.

generic

中文

http.Client 请求的上下文在服务器响应前超时或被取消。常见原因:context.WithTimeout 设置过短、上游过慢,或在多个请求间复用了已取消的 context。

Workarounds

  1. 90% success
    ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
    defer cancel()
    req, _ := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
    resp, err := client.Do(req)
  2. 80% success
    Use context.WithoutCancel(parentCtx) when a downstream call must outlive the parent request lifetime.

Dead Ends

Common approaches that don't work:

  1. 70% fail

    If the deadline comes from the request context, the client Timeout is irrelevant; the context still fires first.

  2. 85% fail

    Retrying with the same canceled context immediately fails again and amplifies load.