What is gRPC?

Anyone who’s working on, with, or has been reading about microservices has probably heard of gRPC in some form or another. In fact, anyone using a library from Google is probably already using it without even knowing.

gRPC is an open source project aimed to make service communication easy. Pinching the description from the gRPC website:

gRPC is a modern open source high performance RPC framework that can run in any environment. It can efficiently connect services in and across data centers with pluggable support for load balancing, tracing, health checking and authentication. It is also applicable in last mile of distributed computing to connect devices, mobile applications and browsers to backend services. — https://grpc.io/about/

Using gRPC with Node.js

Define your service

Before we start writing our code we need to outline what our services API will look like, defining the functions we wish to expose and the parameters that they will be expecting. With gRPC this is done via a protobuf file. Profobuf is a schema definition language more documentation can be found here:

Let’s define a really simple service called Calculator, that will expose a single function named Add. It will take two numbers and simply return the result of adding these together:

Note: With gRPC we cannot have an input or output type that is a singular value. This is notable on the AddReply message. Normally we would just return the value directly rather than an object of result. The reason for this is extensibility, doing this allows us to add new data points without it being a breaking change.

Expose your service

Now that our service is defined we need to implement it using Node.js. As with most things in Javascript this starts off by installing a couple of node modules.

$ npm install grpc @grpc/proto-loader

Now we need to create our Node.js server, this is actually fairly simple. There is some simple bootstrapping of our gRPC server. But mainly we just need to implement the Add function:

Talk to your service

Now that we have our gRPC server running, we need to be able to call the functions that we have exposed. This is where our .proto file comes in to play again.

Each client that talks to your server needs to have a copy of your proto definitions. This allows the gRPC module to know what shape requests should take. There are a number of ways of sharing these but for now we can just copy and paste them around.

Creating a gRPC client is relatively simple and isn’t dissimilar from the code for the server:

And Thats It

We now have a very simple gRPC client / server. This can be expanded significantly and there are lots of awesome guides on line and examples available here