NestJS Microservices with TCP.

A microservice is an application that uses a transport layer other than HTTP. In this example microservices Communicate with each other using TCP.

Table of contents:

  • General Introduction — What is Microservice
  • Why Microservice
  • NestJS Microservices Overview
  • Microservice Client
  • User Microservice
  • Conclusion

General Introduction — What is Microservice:

  • The microservice architecture enables an organization to deliver large, complex applications rapidly, frequently, reliably and sustainably.
  • In a microservice, each software application feature is separated from the other, in most cases with their respective servers and databases.

Why Microservice:

  • Microservice offers flexibility and performance benefits that can’t be achieved with a monolithic application.
  • The event-driven architecture of Node.js makes it a perfect choice for microservices, being fast, highly scalable, and easy to maintain.
                • Independently deployable
                • Loosely coupled
                • supports distributed development
                • better scalability
                • faster development cycles
                • isolated services are easier to debug and maintain

NestJS Microservices Overview:

  • It supports different approaches such as Request Response and Event-Based.
  • we will be looking at Nest JS Microservice using Request Response approach with TCP Transporter.
  • l which will be responsible for operations and we will use Packet Sender for testing purposes, an open-source application that allows us to send network packets that support TCP.
  • Asynchronous pattern with TCP packets which we will communicate with our microservice, and hence the choice of Nest.JS as it has many built-in features making it easier for us to create a microservices architecture.

First, you need to install Nest JS, Run npm i -g @nestjs/cli

Microservice Client:

  • Run nest new nest_producer to create the Client service. Relocate the project directory and run the project.

start:dev for watch the changes in your files. To create the app as microservice, we need to install the required package:

npm i — save @nestjs/microservices

Go to main.ts file and re-write the code as given below:

  • NestFactory exposes a few static methods that allow creating an application instance. The create() method returns an application object, which fulfills the INestApplication interface.

Go to app.module.ts and replace the code as given below:

Run nest g resource user command generates all the NestJS building blocks (module, service, controller class, entity class, DTO classes ,testing (.spec) files).

  • Clients Module exposes the static register() method.
  • This method takes an argument which is an array of objects representing microservices.
  • Each such object has a name property as well as a microservice-specific options object.

  • In this example, Register the user details (name, email ,password ,phone number)
  • we can send a message using the send()method of the Client Proxy instance. The send() method takes the message pattern and the actual data or the payload as input.
  • Client service send Request with Message pattern {cmd:’register_user’} to User service.

User Microservice:

Run nest new user_service to create the User service.Relocate the project directory and run the project.

we need to install the required package:

npm i — save @nestjs/microservices

Go to main.ts file and re-write the code as given below:

  • The INest Application instance can be connected with INest Microservice instances through the connect Microservice()
  • To connect multiple microservice instances, issue the call to connect Microservice() for each microservice.
  • This method takes an argument which is an objects representing microservices communication transport and options.

Go to app.module.ts and replace the code as given below:

  • Run nest g resource user command generates all the NestJS building blocks. Run npm install — save typeorm
  • In this example , we choose the MySQL database and Create database name nestdb.

Now go to src and Create data-source.ts file to add code as given below:

Go to User Module folder into user.module.ts and write the code as given below:

Add the given code User Entity folder into user.entity.ts file.

 

Go to user.controller.ts file and re-write the code as given below:

Add given below code into user.service.ts

Open your postman and send action with localhost:5000/register_user

Conclusion:

we have learnt how to create a NestJS Microservices with TCP using Request Response approach. NestJS makes it possible to create outstanding, well-organized, and lightweight microservices. The framework allows you to create extensible software solutions where there is no strong coupling between the components.

Faq's

How do you set up NestJS microservices using TCP transport?

To set up NestJS microservices with TCP transport, you first install the @nestjs/microservices package. In your main.ts, use NestFactory.createMicroservice() with { transport: Transport.TCP, options: { host: ‘127.0.0.1’, port: 3001 } }. This initializes a TCP server that listens for defined message patterns in controller methods, enabling efficient inter-service communication via the TCP protocol

What are message patterns and how are they used in NestJS microservices?

In NestJS microservices, you define message patterns in controllers using @MessagePattern(‘patternName’). The pattern matches incoming TCP messages and routes them to specific handler functions. When another service uses a ClientProxy.send({ cmd: ‘sum’ }, data), it triggers the corresponding handler—this decoupled architecture enables scalable and maintainable service integration

How do TCP-based NestJS microservices work within Docker or multi-service environments?

When deploying NestJS microservices in Docker or clustered environments, ensure the TCP service binds to 0.0.0.0 instead of localhost to allow external access. This setup, combined with Docker networking, enables your client service to connect over TCP using hostnames (e.g., service-name:3001). Without correct host binding, you may encounter connection refusals—an issue often resolved by using 0.0.0.0

Can you secure TCP communication in NestJS microservices?

Yes, secure TCP communication in NestJS by enabling TLS encryption. In your createMicroservice() transport options, include a tlsOptions object with your private key and certificate. On the client side, add the trusted CA certificate. This ensures data encryption and secure communication channels between services over TCP

How do you handle fault tolerance and timeouts in TCP-based microservices with NestJS?

To improve resilience in NestJS microservices, apply timeouts using RxJS’s timeout() operator in the client’s send() method to prevent hanging requests (e.g., .pipe(timeout(5000))). For fault isolation, incorporate a circuit breaker library like opossum. These practices ensure services fail gracefully and maintain stability under load or network issues

Connect With Us!