Implementation of NestJS Microservice with Nats

Ali Karimi
Software Genesis Group
2 min readApr 28, 2024

In this article, we will explore a project that demonstrates the implementation of a microservice architecture using NestJS. The project consists of three modules: main, mailer, and user, each serving a specific purpose within the overall system. We will dive into the code and explain how these modules are created, connected, and executed.

Some code is better than many sentences. (github repo)

Bootstrap Functions: The project defines three async functions: bootstrapMain(), bootstrapMailer(), and bootstrapUser(). Each function creates an instance of the respective module using NestFactory.create(). Then, a microservice is connected to the module using the NATS transport protocol and the specified URL. Finally, the microservice is started using app.startAllMicroservices(), and the module is initialized using app.listen().

If your application does not handle HTTP requests then you should use the app.init() method instead.

Requester and Responder

According to this article, I use ‘Requester’ for the app that fires events to the NATS server to route to other services, and ‘Responder’ for the app that handles those events and may or may not send back responses , and some apps, such as ‘User’, may play roles in both capacities.

connectMicroservice

As evidenced in the main.ts file within the GitHub repository, I utilize connectMicroservice for both the user and mailer services. This choice is made because they each contain a controller designed to manage NATS events, effectively acting as Responder. (represented by a dot in the image below. 👇)

NestJS microservice with NATS

ClientsModule

For services requiring event transmission(send or emit) to NATS, it’s necessary to register the client within modules such as main main/app.module.ts and user user/user.module.ts, where they function as Requester. (represented by a orange arrow in the image. 👆)

Queue or Group

Consider a scenario where we require three instances of each service. What happens if a client sends a request to create a user?

Take a look at the connectMicroservice options in the NestJS documentation. There’s an option called queue which, in my opinion, should be group . look at the NATS documentation.

When we set the queue option in connectMicroservice, if we launch three instances of the mailer service, when a user is created, the ‘UserService’ emits a user-created event. The NATS server then selects one instance and sends the event exclusively to it. But if we don’t set the queue option, it means that we want all three mailer services to be notified about that event.

Good luck :)

--

--