Careeroza
Transports
Creating a Microservice
Example
npm i @nestjs/microservicesExample output
added 1 package in 2s
apps/inventory/src/main.ts
import { NestFactory } from '@nestjs/core';
import { MicroserviceOptions, Transport } from '@nestjs/microservices';
import { InventoryModule } from './inventory.module';
async function bootstrap() {
const app = await NestFactory.createMicroservice<MicroserviceOptions>(InventoryModule, {
transport: Transport.TCP,
options: { host: '0.0.0.0', port: 4001 },
});
await app.listen();
}
bootstrap();Choosing a Transport
| Transport | Options example | Good for |
|---|---|---|
| TCP | { host, port } | Simple request-response inside a private network |
| Redis | { host, port } | Light pub/sub when you already run Redis |
| RabbitMQ (RMQ) | { urls: ['amqp://...'], queue: 'orders_queue', queueOptions: { durable: true } } | Reliable work queues, acknowledgements |
| Kafka | { client: { brokers: ['kafka:9092'] }, consumer: { groupId: 'inventory' } } | High-volume event streams, replay, analytics |
| gRPC | { package: 'catalog', protoPath } | Typed, fast service-to-service calls |
| NATS | { servers: ['nats://...'] } | Very fast lightweight messaging |
// Kafka consumer service
const app = await NestFactory.createMicroservice<MicroserviceOptions>(NotificationsModule, {
transport: Transport.KAFKA,
options: {
client: { clientId: 'notifications', brokers: ['kafka:9092'] },
consumer: { groupId: 'notifications-consumer' },
},
});
// RabbitMQ worker
const worker = await NestFactory.createMicroservice<MicroserviceOptions>(InvoicesModule, {
transport: Transport.RMQ,
options: { urls: ['amqp://guest:guest@rabbitmq:5672'], queue: 'invoices', queueOptions: { durable: true }, noAck: false },
});