Go Context: gRPC Calls Not Cancelled
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
Right
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
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists - 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
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