go network_error ai_generated true

rpc error: code = Canceled desc = context canceled

ID: go/grpc-canceled-context-canceled

Also available as: JSON · Markdown · 中文
80%Fix Rate
86%Confidence
0Evidence
2024-07-21First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.x active — — —

Root Cause

The context passed to the RPC was canceled before completion, either by an explicit cancel() call, a parent context canceling, or a client-side interceptor. The server sees the cancellation and aborts the handler.

generic

中文

传给 RPC 的上下文在完成前被取消,可能由显式 cancel() 调用、父上下文取消,或客户端拦截器引起。服务器感知到取消并中止处理程序。

Workarounds

  1. 88% success
    Derive a fresh context for retries and never reuse a canceled parent:
    
    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()
    resp, err := client.Do(ctx, req)
    if status.Code(err) == codes.Canceled {
        // parent was canceled; abort cleanly, don't retry with same ctx
    }
  2. 82% success
    Trace where the cancel is coming from — check for deferred cancel() firing too early or a request-scoped context tied to an HTTP handler that already returned:
    
    // ensure cancel() is deferred AFTER the RPC completes, not before
    ctx, cancel := context.WithTimeout(r.Context(), time.Second)
    defer cancel()
    resp, err := client.Do(ctx, req)

Dead Ends

Common approaches that don't work:

  1. 95% fail

    The context is already done; every call with it returns Canceled immediately without even reaching the server.

  2. 90% fail

    A canceled RPC returns a nil/zero response; proceeding as if it succeeded produces corrupt state downstream.