gRPC for communication between microservices. Protocol Buffers, streaming and examples in Node.js.
Why gRPC?¶
- ~10x faster serialization (Protobuf vs JSON)
- HTTP/2 multiplexing
- Bi-directional streaming
- Generated clients from definition
Proto Definition¶
syntax = "proto3";
service OrderService {
rpc CreateOrder (CreateOrderRequest) returns (Order);
rpc ListOrders (ListRequest) returns (stream Order);
}
message Order {
string id = 1;
string customer_id = 2;
double total = 3;
string status = 4;
}
Node.js Implementation¶
// Server
const grpc = require('@grpc/grpc-js');
const proto = grpc.loadPackageDefinition(protoLoader.loadSync('order.proto'));
const server = new grpc.Server();
server.addService(proto.order.OrderService.service, {
createOrder: (call, cb) => {
const order = { id: genId(), ...call.request, status: 'CREATED' };
cb(null, order);
}
});
server.bindAsync('0.0.0.0:50051', grpc.ServerCredentials.createInsecure(), () => {});
Summary¶
gRPC is excellent for internal services. For public APIs, stick with REST/GraphQL.
Need Help with Implementation?¶
Our team has experience designing and implementing modern architectures. We’re happy to help.