Backend Development 1 min read 1,199 views

Building Microservices with NestJS: Architecture and Best Practices

Design and build scalable microservices using NestJS framework. Learn about message queues, service discovery, and API gateways.

Microservices architecture

Microservices with NestJS

Build scalable, maintainable microservices using NestJS framework.

Project Setup

npm i -g @nestjs/cli
nest new user-service
cd user-service
npm install @nestjs/microservices

Creating a Microservice

// main.ts
import { NestFactory } from '@nestjs/core';
import { Transport, MicroserviceOptions } from '@nestjs/microservices';

async function bootstrap() {
    const app = await NestFactory.createMicroservice<MicroserviceOptions>(
        AppModule,
        {
            transport: Transport.RMQ,
            options: {
                urls: ['amqp://localhost:5672'],
                queue: 'users_queue',
            },
        },
    );
    await app.listen();
}
bootstrap();

Message Patterns

// users.controller.ts
@Controller()
export class UsersController {
    @MessagePattern({ cmd: 'get_user' })
    getUser(@Payload() data: { id: number }) {
        return this.usersService.findOne(data.id);
    }

    @EventPattern('user_created')
    handleUserCreated(@Payload() data: User) {
        this.analyticsService.trackUserCreation(data);
    }
}

API Gateway

// gateway/users.controller.ts
@Controller('users')
export class UsersController {
    constructor(
        @Inject('USER_SERVICE') private client: ClientProxy,
    ) {}

    @Get(':id')
    async getUser(@Param('id') id: number) {
        return this.client.send({ cmd: 'get_user' }, { id });
    }
}

Service Discovery with Consul

// Register service on startup
const consul = new Consul();
await consul.agent.service.register({
    name: 'user-service',
    address: 'localhost',
    port: 3001,
    check: { http: 'http://localhost:3001/health', interval: '10s' },
});

NestJS provides excellent patterns for building enterprise-grade microservices.

Share this article:
ES
Written by

Edrees Salih

Full-stack software engineer with 9 years of experience. Passionate about building scalable solutions and sharing knowledge with the developer community.

View Profile

Comments (0)

Leave a Comment

Your email will not be published.

No comments yet. Be the first to share your thoughts!

Related Articles

Related Articles

Need Help With Your Project?

Book a free 30-minute consultation to discuss your technical challenges and explore solutions together.