NestJS – Combine HTTP with RabbitMQ in microservices

NestJS – Combine HTTP with RabbitMQ in microservices

I have a few microservices, which are exposed through an API-Gateway. The gateway takes care of handling authentication and routing into the system. The services behind the gateway are mostly simple CRUD-Services. Each service exposes its own API and they communicate synchronously via HTTP. All of these services, including the API-Gateway, are “default” NestJS applications.
Let’s stick with the Cats example. Whenever the Cat-Service updates or creates a new Cat, I want an CatCreatedEvent or CatUpdatedEvent to be emmited. The event should be pushed into some message broker like RabbitMQ and another service should listen to this event and process the event asynchronously.
I am not sure how to achive this, in terms of how to “inject” RabbitMQ the right way and I am wondering if this approach makes sense in generel. I have seen the CQRS Module for NestJS, but i think CQRS is a bit too much for this domain. Especially because there is no benefit in this domain to split read- and write-models. Maybe I am totally on the wrong track, so I hope you can give me some advises.


Solution 1:

RabbitMQ is supported in nestjs as a microservice. If you want your application to support both http requests and a message broker, you can create a hybrid application.

// Create your regular nest application.
const app = await NestFactory.create(ApplicationModule);

// Then combine it with a RabbitMQ microservice
const microservice = app.connectMicroservice({
  transport: Transport.RMQ,
  options: {
    urls: [`amqp://localhost:5672`],
    queue: 'my_queue',
    queueOptions: { durable: false },

await app.startAllMicroservicesAsync();
await app.listen(3001);


Related:  Getting swagger working with multiple microservices