Microservices in NestJS

Microservices in NestJS

NestJS Microservices: Building Big by Thinking Small

Microservices architecture is a design paradigm that divides complicated programs into smaller, loosely linked services that may be created, deployed and maintained independently. NestJS is a popular Node.js framework for developing scalable and maintainable server-side applications, such as microservices.

The Architecture of Microservices:

  • Microservices divide huge applications into smaller, self-contained services.

  • Each microservice is responsible for a certain function and communicates with the others.

  • Microservices may be independently designed, deployed, and maintained.

it includes the following steps:

  1. Project Setup: NestJS allows you to structure your application into modules. Each microservice requires its module. This helps to encapsulate each service's functionality and dependencies.

  2. Module Organization: NestJS allows you to structure your application into modules. Each microservice requires its module. This helps to encapsulate each service's functionality and dependencies.

  3. Communication: Microservices interact with one another using HTTP, TCP, or message brokers such as RabbitMQ, Kafka, and others. To manage communication between microservices, NestJS provides the @nestjs/microservices package. TCP, Redis, NATS, and other transporters are available.

  4. Service Implementation: Each microservice's business logic should be implemented in its module. Examples include controllers, services, and data models. NestJS's dependency injection makes it easy to manage service dependencies within each module.

  5. Service Discovery: Services in a microservices architecture must discover and communicate with one another. For service discovery, tools such as Consul and Eureka can be utilized. Alternatively, cloud systems such as Kubernetes provide service discovery.

  6. Load Balancing: Microservices sometimes require load balancing to distribute incoming requests evenly among service instances. This may be handled by tools such as Kubernetes or load balancers.

  7. Error Handling and Resilience: Because microservices can fail on their own, you must include error handling and resilience techniques. Circuit breakers, retries, and timeouts are all critical topics to understand.

  8. Data Management: Databases may be required to interface with microservices. Depending on your design and data requirements, each microservice might have its database or share databases with other microservices.

  9. Security: For each microservice, implement security procedures like authentication and authorization. API Gateways can also serve as a centralized point of contact for external customers.

  10. Monitoring and Logging: Implement monitoring and logging to track each microservice's health and performance. Tools such as Prometheus, Grafana, and the ELK stack can be beneficial.

  11. Deployment and Scalability: Deploy each microservice separately. Containerization with Docker and orchestration with Kubernetes can make deployment and scaling easier.

NestJS Advantages for Microservices:

  • NestJS is a popular Node.js framework for developing microservices.

  • Its modular design and dependency injection technology encourage clean, maintainable code.

  • NestJS has built-in capabilities for inter-service communication, such as @nestjs/microservices.

Setup of the Project:

Step 1: Install Nest CLI using npm:

npm install -g @nestjs/cli

Step 2: New Microservice should be Created

You will build a new NestJS application. To create a new application, use the Nest CLI:

nest new microservice-name

Step 3: Navigate to the directory of the newly created microservice application

cd microservice-name

Step 4: Creating a Module

Make a new module for your microservice. This is where you will define controllers, services, and other microservice-specific components:

nest generate module module-name

Step 5: Creating a Controller:

Create a controller within your module to manage incoming requests to your microservice:

nest generate controller controller-name

Step 6: Creating a Service

Create a service that contains your microservice's business logic. Services are used to carry out tasks and communicate with other components

nest generate service service-name

Step 7: Configure Communication

Use @nestjs/microservices module for communication between microservices, setting appropriate transporters and communication patterns.

Step 8: Main File Configuration

Bootstrap your microservice in the src/main.ts file.

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { Transport } from '@nestjs/microservices';

async function bootstrap() {
  const app = await NestFactory.createMicroservice(AppModule, {
    transport: Transport.TCP,
    options: { port: 3000 }, // Change the port as needed
  });
  await app.listenAsync();
}
bootstrap();

Step 9: Start your microservice by running

npm run start

Module Organization

NestJS enables application module structure, encapsulating microservice functionality and dependencies.

Example: How to organize a microservice in NestJS with its module, controller, and service.

Step 1: Create a new microservice called "user-service

nest new user-service

Step 2: Navigate to Microservice Directory

cd user-service

Step 3: Create a new module for the microservice

nest generate module users

//This will encapsulate the functionality and dependencies

Step 4: Create a controller that handles incoming HTTP requests

nest generate controller users

Step 5: Create a service that contains the business logic

nest generate service users

Step 6: Define routes for the controller

Open the users.controller.ts file in the src/users

//src/users/users.controller.ts 

import { Controller, Get } from '@nestjs/common';
import { UsersService } from './users.service';

@Controller('users')
export class UsersController {
  constructor(private readonly usersService: UsersService) {}

  @Get()
  getUsers() {
    return this.usersService.getAllUsers();
  }
}

Step 7: Service Logic

import { Injectable } from '@nestjs/common';

@Injectable()
export class UsersService {
  private users = [
    { id: 1, name: 'Alice' },
    { id: 2, name: 'Bob' },
  ];

  getAllUsers() {
    return this.users;
  }
}

Step 8: Update Module Definition- import the controller and service

//src/users/users.module.ts
import { Module } from '@nestjs/common';
import { UsersController } from './users.controller';
import { UsersService } from './users.service';

@Module({
  controllers: [UsersController],
  providers: [UsersService],
  exports: [UsersService], 
})
export class UsersModule {}

Step 9: Bootstrap the Microservice: Update the src/main.ts

//src/main.ts
import { NestFactory } from '@nestjs/core';
import { UsersModule } from './users/users.module';

async function bootstrap() {
  const app = await NestFactory.createMicroservice(UsersModule);
  await app.listenAsync();
}
bootstrap();

Step 10: Run the microservice

npm run start

Building microservices requires careful planning, considering application requirements, and designing architecture and infrastructure based on specific use cases and business needs.

Summary
NestJS is a microservice architecture that organizes applications into modules, with each microservice having its module. These microservices communicate using protocols like HTTP, TCP, or message brokers. NestJS provides the @nestjs/microservices package to handle communication between microservices. Service implementation involves implementing business logic, service discovery, load balancing, error handling and resilience, data management, security measures, monitoring and logging, and deployment and scaling. Tools like Prometheus, Grafana, and ELK stack can help manage microservices' health and performance.

We appreciate your interest in our blog and hope you find our insights valuable.

We are truly grateful for the overwhelming response to our blogs. Your continued support, likes, shares, and valuable comments are highly encouraging to us. We sincerely hope that you will continue to engage with our content and provide us with your valuable feedback. Your participation means a lot to us, and we look forward to providing you with more informative and engaging articles in the future.

Warm regards,

ByteScrum Blog Team,

ByteScrum Technologies Private Limited! 🙏

Did you find this article valuable?

Support ByteScrum Technologies by becoming a sponsor. Any amount is appreciated!