Microservices architecture Node js- full guide

Microservices architecture Node js- full guide

Hey reader! Do check out Node js architecture blog before reading this article, here we will be talking about how microservices architecture is used in Node js and a glimpse of what microservices are. Besides this, some practices and enlisted in order to design more architecture patterns in Node js. 

Before moving on to Microservices architecture in Node js, let’s talk about what is microservices.

Microservices– It is an application architecture that accepts all function from the application and gives it to its own service which is isolated from others. These services are independently deployable and are loosely coupled. It resolves the challenge faced by monolithic services by fragmenting the web application into different smaller chunks. 

Why is a microservices architecture used in Node js?

The answer to it is the three most important features that this programming language has as compared to other programming languages. 

  • High speed and scalable
  • Single-Threaded and asynchronous 
  • Event-driven
Microservices architecture
Microservices architecture

Implementing microservices architecture

For understanding microservices architecture in Node js, let’s take an example of creating user management using the microservices architecture of Node js. It will communicate via TCP packets and will be responsible for the CRUD operation of users in a database. In this article, we will be using an asynchronous pattern with TCP protocol in order to communicate with microservices. We will be using Nest js as a framework and REST API.

Below are the following steps for building microservices architecture:

  • Setup of Microservices– It is very easy to set up especially because of the Nest js framework. Nest js is a progressive type of framework. Create the Nestjs application by using the following command.
npx @nestjs/cli new user-microservice

This command creates and initializes a new project. To start building, install the packages.

npm i --save @nestjs/microservices

In order to run the file, write the below code in main.ts

import { INestMicroservice } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { Transport } from '@nestjs/microservices';
import { AppModule } from './app.module';
async function bootstrap() {
const microservicesOptions: any = {
transport: Transport.TCP,
options: {
host: '127.0.0.1',
port: 8875,
},
};
const app: INestMicroservice = await NestFactory.createMicroservice(
AppModule,
microservicesOptions,
);
app.listen(() => console.log('Microservice is listening'));
}
bootstrap();

It supports built-in transporters and binds TCP to port 8875 on the local machine. 

  • Listen for messages– In this, the message or event pattern can be used for communication between the application and server.The message pattern works on the request-response method which is suitable for exchanging messages between events and services without waiting for the response.Therefore, we will use a message pattern to create users in file app.controller.ts
    @Controller()
    export class AppController {
    constructor(private readonly appService: AppService) {}
    @MessagePattern('create_user')
    async createUser(@Payload() payload: CreateUserDto) {
    const user = await this.appService.createUser(payload);
    return user;
    }
    }

    The payload for users can be created using the following code with a simple object like email and password.

import { IsString, IsEmail } from 'class-validator';
export class CreateUserDto {
@IsEmail()
email: string;
@IsString()
password: string;
}

The message pattern works on the request-response method which is suitable for exchanging messages between events and services without waiting for the response.

Therefore, we will use a message pattern to create users in file app.controller.ts

The payload for users can be created using the following code with a simple object like email and password.

  • Testing of microservices– PacketSender is used to test the TCP of applications.  For this, we have to set the address and port as 127.0.01 and 8875 respectively. Configure PacketSender using the following code snippet.
122#{"pattern":"create_user",
"data":{"email":"[email protected]","password":"12345678"},
"id":"ce51ebd3-32b1-4ae6-b7ef-e018126c4cc4"}

Where, 

Pattern – message we are listing for creating user

Data– It is a JSON object that we want to send with an email and password

  • API gateway– To create an API gateway and connect it to microservices, we will create a new NestJs application and update app.module.ts with the following code
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ConfigService } from "./config/config.service";
@Module({
imports: [],
controllers: [AppController],
providers: [
{
provide: 'USER_MICROSERVICE',
useFactory: (configService: ConfigService) => {
const options = {
transport: Transport.TCP,
options: {
host: configService.get('USERS_MICROSERVICE_HOST'),
port: Number(configService.get('USERS_MICROSERVICE_PORT')),
},
};
return ClientProxyFactory.create(options as ClientOptions);
},
inject: [ConfigService],
},
AppService,
],
})
export class AppModule {}

To use connection object, inject AppController using below code

@Controller()
export class AppController {
constructor(
@Inject('USER_MICROSERVICE') private readonly client: ClientProxy,
private readonly appService: AppService
) }
@Post('create-user')
async createUser(@Body() payload: CreateUserDto) {
return this.client.send('create_user', payload).toPromise();
}
}

Now, whenever there is a POST request created for creating a user, the API forwards it to the microservice with the payload, and the response is then sent back to the server.

Node js architecture best patterns

There are 3 designs of architecture’s pattern in Node js

  • Creation- It is the creation of an instance of the object
  • Structural- This pattern refers to the way objects are designed
  • Behavior- This depicts how objects interact with each other

Conclusion

Microservices are very efficient and useful these days. It is been used by many applications because of its performance. Do let us know in the comment section if you have any queries and check out codedamn if you want to learn trending technologies and want to be a part of the developer community

Sharing is caring

Did you like what mansi wrote? Thank them for their work by sharing it on social media.

0/10000

No comments so far