API with NestJS #20. Communicating with microservices using the gRPC framework

JavaScript NestJS TypeScript

This entry is part 20 of 168 in the API with NestJS

With NestJS, we have quite a few transport layer implementations prepared for microservices. Among them, the gRPC transporter is definitely one of the most interesting. In this article, we explore the idea and implement it with NestJS.

gRPC is, at its core, a Remote Procedure Call (RPC) framework. Its main idea revolves around creating services in the form of functions that we can call remotely. It’s open-source and developed by Google. The gRPC framework is language-agnostic. Therefore, we can use it for communication across microservices using multiple programming languages.

The gRPC clients can directly call a method specified on a server. To describe the interface of the service and the payload messages, we use the protocol buffers. It is an efficient binary message format. It serializes very quickly and results in small messages.

Creating a .proto file

A first step to use gRPC is to create a file using the protocol buffer language. This article uses the microservice that we’ve created in one of the previous parts of this series. Let’s break down the creation of the step by step.

We’ll start by defining the version of the protocol buffers language. While there are some advantages and drawbacks to both, in this article, we use .

We also want to use the keyword with a name. We will later refer to it when setting up gRPC with NestJS.

The file’s job is to describe the service and the methods we want to use remotely.

Even though we don’t need any parameters for the method, we need to specify some message here – even if it is empty.

Assigning types and numbers to fields

Another important thing is to define our .

Above, we use fundamental field types: integer and strings. There are various types that we can assign to fields. For a full list, visit the official documentation.

A more interesting topic is assigning field numbers. Every field in a massage needs a unique number. The gRPC framework uses the numbers to identify the fields in the message binary format.

Deep knowledge of the gRPC encoding is not needed to start working with the framework. Although, it is important to know that field numbers from 1 to 15 take just one byte to encode the field number and the type. If the field number is 16 and bigger, it takes two bytes. Therefore, we should keep the smaller number for parameters that frequently occur in our messages. We might even want to leave some room in the range of 1 through 15 to add new parameters here later.

Changing the name of the field does not affect the protocol buffer encoding. Changing the number assigned to property does break the compatibility between applications, so we need to watch out for that.

Dealing with arrays

The method is supposed to return an array. Unfortunately, there is no straightforward way for our gRPC methods to return an array (other than a stream). Therefore, we create a method that returns an object with the property.

The keyword means that this field can be repeated any number of times.

Using gRPC with NestJS

Aside from installing the package, we also need the following:

Defining the microservice

For starters, let’s start with defining our microservice. Here, we need three things:

  1. the package’s name that we’ve defined in our file,
  2. the path to the file,
  3. the connection URL – defaults to .
main.ts

It is worth mentioning that, by default, our build process does not copy the files to the directory. Therefore, in my configuration, I point to the in the directory. Another approach would be to create a directory at the top of our project. We could also create a script that copies the files to .

Running the above code initiates a gRPC server under the hood that can be accessed by the provided URL.

If we look under the hood, we can see that NestJS creates an instance of the class and begins handling requests. You can read more about it here.

In this article, we store the URL in our file:

.env

With gRPC, we don’t use the decorator anymore. Instead, we mark our functions using the .

subscribers.service.ts

Please note that we don’t have the anymore. This time, we only have the that we mark with the  decorator. It works thanks to the fact that it matches the name of the service in the file. We also add it to the array in our :

subscribers.module.ts

There are other ways to define a gRPC service with NestJS with additional arguments passed to the decorator. If you want to know more, check out the documentation.

Creating a client

Once we have the microservice ready, we can connect to it from a client. The first thing to realize is that we need the same for the client also. We also need the same environment variable that we’ve called .

subscribers.module.ts

Since the is in another application, we need to create an interface to use it.

subscribers.service.interface.ts

Please note that we expect an empty object to be passed to the method because, with gRPC, we need to have some sorts of parameters. Even if they are empty.

Once we’ve registered our microservice, we can inject it into a controller. To use our remote service, we need to use the method that NestJS calls once it resolves all of its dependencies.

subscribers.controller.ts

With all of the above, we have a working connection with our microservice!

Summary

In this article, we’ve looked into the basics of establishing a gRPC connection with NestJS. This covered the fundamentals of the gRPC framework and Protocol Buffers language. We’ve also looked under to hood of NestJS to understand better what it does. Thanks to doing all of that, we learned about yet another transporter that we can use to communicate with our microservices.

Series Navigation<< API with NestJS #19. Using RabbitMQ to communicate with microservicesAPI with NestJS #21. An introduction to CQRS >>
Subscribe
Notify of
guest
4 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Pawel
Pawel
3 years ago

Marcin, it is a great job that you are doing here! Really appreciate it 🙂 one question though: are you planning also to deploy that project to ‘production’ somewhere(AWS,Google Cloud, etc.)? Is that process rather complicated ? What would be the best option to deploy such project?
Best,

Yannis
Yannis
3 years ago

Hi,

If I am not mistaken for this to work you have to define both Subscriber and CreateSubscriberDto in both the client and the server. Doesn’t this break SOLID principles you mention in another article?

Last edited 3 years ago by Yannis
SpaceCowboy74
SpaceCowboy74
3 years ago

The latest version of Nest requires you to include the @grpc/grpc-js package as well.

descholar
descholar
2 years ago

I have followed all of these instructions but when I send a request I get the following error:

Any help though?