Skip to content

Go Context: gRPC Calls Not Cancelled

DodaTech Updated 2026-06-24 1 min read

In this tutorial, you'll learn about Go Context: gRPC Calls Not Cancelled. We cover key concepts, practical examples, and best practices.

gRPC context propagation -- Pass context with deadline to gRPC calls to enable cancellation and timeout propagation.

The Problem

gRPC calls without context ignore deadlines and cancellation. Always pass a context with timeout to gRPC client calls. The server should also check the incoming context.

Wrong

resp, err := client.GetUser(ctxbg, &pb.GetUserRequest{Id: 42})

Output:

// Using background context - no timeout or cancellation
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
resp, err := client.GetUser(ctx, &pb.GetUserRequest{Id: 42})
if err != nil {
    statusCode := status.Code(err)
    // Handle deadline exceeded, cancelled, etc.
}

Output:

// gRPC call respects timeout and cancellation

Prevention

  • Always pass context with timeout/deadline to gRPC calls
  • Use defer cancel() to release context resources
  • gRPC passes context metadata from client to server
  • Server extracts metadata from incoming context
  • Check status.Code(err) for gRPC specific errors

Common Mistakes with context grpc

  1. Misunderstanding that String is [Char] with poor performance for large text operations
  2. Using foldl instead of foldl' causing stack overflow on large lists
  3. Forgetting deriving (Show, Eq) on custom data types needed for debugging

These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

**How does gRPC propagate context?**

Metadata in the context is sent as gRPC headers.

What happens if gRPC context times out?

Client receives status.Error with code DeadlineExceeded.

Can I add metadata to gRPC context?

Yes. Use metadata.NewOutgoingContext(ctx, md).


Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro