Card 03/ 09

ConceptDifficulty: Intermediate1 min

gRPC: Typed Procedures Over HTTP/2

A service is defined in a .proto file, and both sides call it like a local function with generated code.

gRPC is a remote procedure call framework, first built at Google. A service and its messages are defined in a .proto file, and a compiler generates client and server code in each language, so a client calls GetOrder like a local function. Messages travel as Protocol Buffers, a compact binary format, over HTTP/2, the version of HTTP that sends many requests at once over one connection.

text
syntax = "proto3";

package orders.v1;

service OrderService {
  rpc GetOrder(GetOrderRequest) returns (Order);
  rpc WatchOrder(GetOrderRequest) returns (stream OrderEvent);
}

message GetOrderRequest {
  string order_id = 1;
}

message Order {
  string id = 1;
  string customer_name = 2;
  int64 total_pence = 3;
  repeated Item items = 4;
}
An illustrative .proto file: a service with two procedures, and the messages they exchange

The parts. service names a group of procedures, each rpc one procedure with its request and response types, and each message a type whose fields carry a name, a type and a number. The numbers, not the names, identify fields on the wire, which the card on Protocol Buffers covers.

Streaming in four shapes. A call can be unary, one request and one response; server streaming, one request and many responses, as WatchOrder does with stream; client streaming; or bidirectional, both sides sending as they please.

Errors. gRPC has its own status codes, such as NOT_FOUND, PERMISSION_DENIED and UNAVAILABLE, rather than HTTP's.

Browsers. A browser cannot make native gRPC calls, so web clients need gRPC-Web and a proxy that translates. That is why gRPC is mostly used between services, where both ends are code the team controls.

So gRPC suits fast, typed calls between services, and is a poor fit for clients the team does not control.