Lesson 7 / 25

Defining Services and RPC Types

Four kinds of methods.

Unary and streaming RPCs

A service lists rpc methods with request and response messages. There are four kinds: unary (one request, one response), server streaming (one request, a stream of responses), client streaming (a stream of requests, one response) and bidirectional streaming (both sides stream independently). Use dedicated request and response messages for every method, even if they wrap a single field, so you can add fields later without breaking the signature.

From contract to running code

Service definitions describe methods; code generators produce clients and servers in each language.

Three ideas: service definitions, code generation, a unary call end to end.
Figure 3.1 — Services, codegen and unary calls.

An order service

All four RPC kinds.

service OrderService {
  rpc GetOrder(GetOrderRequest) returns (Order);                        // unary
  rpc WatchOrder(WatchOrderRequest) returns (stream OrderEvent);        // server streaming
  rpc UploadItems(stream OrderItem) returns (UploadItemsResponse);     // client streaming
  rpc Chat(stream SupportMessage) returns (stream SupportMessage);     // bidirectional
}

message GetOrderRequest { string id = 1; }
message WatchOrderRequest { string id = 1; }
message OrderEvent { string order_id = 1; OrderStatus status = 2; }
message UploadItemsResponse { int32 accepted = 1; }
message SupportMessage { string text = 1; }

One request and response message per RPC

Sharing a message between methods couples them; separate messages evolve independently.

Quick check: Which RPC kind sends one request and receives a stream of responses?

  • Server streaming
  • Unary
  • Client streaming
  • Bidirectional streaming
Answer

Server streaming — stream on the response side.