Go Grpc Streaming
In this tutorial, you'll learn about grpc: streaming rpc pattern. We cover key concepts, practical examples, and best practices.
gRPC streaming -- Implement server-side, client-side, and bidirectional streaming RPCs with proper flow control.
The Problem
Streaming RPCs manage flow control internally. Server must call Send and check error. Client must Recv in a loop until EOF.
Wrong
func (s *server) ListUsers(req *pb.ListReq, stream pb.User_ListUsersServer) error {
users := getUsers()
for _, u := range users {
stream.Send(u) // Error ignored!
}
return nil
}
Output:
// Send errors ignored. Client may miss data.
Right
func (s *server) ListUsers(req *pb.ListReq, stream pb.User_ListUsersServer) error {
users := getUsers()
for _, u := range users {
if err := stream.Send(u); err != nil {
return err // Client disconnected
}
}
return nil
}
// Client:
for {
user, err := stream.Recv()
if err == io.EOF { break }
if err != nil { log.Fatal(err) }
process(user)
}
Output:
// Server stops on client disconnect. Client iterates correctly.
Prevention
- Always check Send error for client disconnection
- Client loops Recv until io.EOF
- Use flow control: gRPC handles backpressure
- Use ctx.Done() for cancellation in streaming handlers
- Bidirectional: use goroutines with select for both directions
Common Mistakes with grpc streaming
- Mixing let bindings with <- bindings in do notation, producing type errors
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
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