go network_error ai_generated true

rpc error: code = Canceled desc = grpc: the client connection is closing

ID: go/grpc-stream-interrupted-client-cancel

Also available as: JSON · Markdown · 中文
80%Fix Rate
83%Confidence
0Evidence
2024-10-02First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.1 active

Root Cause

The gRPC client cancelled the context, causing the streaming RPC to terminate prematurely.

generic

中文

gRPC客户端取消了上下文,导致流式RPC过早终止。

Workarounds

  1. 90% success Handle context cancellation gracefully and restart stream.
    for {
        stream, err := client.StreamRPC(ctx)
        if err != nil { return }
        for {
            msg, err := stream.Recv()
            if errors.Is(err, context.Canceled) { break }
        }
    }
  2. 85% success Use a separate context for stream to avoid parent cancellation.
    streamCtx, cancel := context.WithCancel(context.Background())
    defer cancel()
    stream, _ := client.StreamRPC(streamCtx)

Dead Ends

Common approaches that don't work:

  1. Ignore the cancellation and retry the same stream. 95% fail

    Stream is closed; must create a new stream.

  2. Increase context timeout to avoid cancellation. 70% fail

    Cancellation may be intentional (e.g., user abort).