Sobes.tech
Middle

What is the difference between stream and unary calls?

sobes.tech AI

Answer from AI

In gRPC:

Unary call: Client sends a single request, server processes it and sends a single response. Client is blocked until the response is received. Used for simple request-response type interactions.

Streaming call: Allows the client and/or server to send multiple messages over a single connection. Supports:

  • Client streaming: Client sends a sequence of messages, server sends a single response.
  • Server streaming: Client sends a single request, server sends a sequence of messages.
  • Bidirectional streaming: Client and server send sequences of messages independently. Allows handling large volumes of data or maintaining long-lived connections.
Feature Unary call Streaming call
Number of requests 1 1 or N
Number of responses 1 1 or N
Behavior Blocking (for client) Non-blocking (partial/full)
Examples Get profile information Upload file, receive status updates
// Unary call example
func (s *server) GetProfile(ctx context.Context, req *pb.ProfileRequest) (*pb.ProfileResponse, error) {
	// ... request processing logic
	return &pb.ProfileResponse{ /* ... */ }, nil
}

// Server streaming example
func (s *server) ListFeatures(req *pb.Rectangle, stream pb.RouteGuide_ListFeaturesServer) error {
	for _, feature := range features {
		if inRectangle(feature.Location, req) {
			if err := stream.Send(feature); err != nil {
				return err
			}
		}
	}
	return nil
}

// Bidirectional streaming example
func (s *server) RouteChat(stream pb.RouteGuide_RouteChatServer) error {
	for {
		in, err := stream.Recv()
		if err == io.EOF {
			return nil // Stream ended
		}
		if err != nil {
			return err
		}
		// ... process received message and send responses
		if err := stream.Send(reply); err != nil {
			return err
		}
	}
}