Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can NestFactory.create in Nestjs subscribe to topics on kafka?

The documentation suggests using NestFactory.createMicroservice to create a transport subscribing app.

I currently have a REST based microservice that contains domain logic and connection to the database. I'd like to subscribe on that microservice to Kafka messages. Is it possible to do this in a scope of this single microservice? I can't see that in the docs.

It makes me wonder if the pattern should be: I should create an extra microservice with NestFactory.createMicroservice that will connect to Kafka and then will distribute message to my REST API... over REST? This would mean that the rest api would have all possible "actions" happen over rest, but the intermittent microservice will be triggering it upon Kafka's message.

If that was true, does that mean that as my application scales, I might end up with one Kafka subscribing microservice per one rest microservice? Or will there be one subscribing microservice that will trigger multiple REST APIs? Or perhaps... it depends on the use case?

like image 237
Adam Avatar asked Oct 22 '25 14:10

Adam


1 Answers

It is possible to connect both approaches in nest - microservice and normal app. The documentation doesn't mention it, but FAQ explains how to make a Hybrid application.

The GRPC example shows it in action

import { NestFactory } from '@nestjs/core';
import { MicroserviceOptions } from '@nestjs/microservices';
import { AppModule } from './app.module';
import { grpcClientOptions } from './grpc-client.options';

async function bootstrap() {

  const app = await NestFactory.create(AppModule);
  app.connectMicroservice<MicroserviceOptions>(grpcClientOptions);

  await app.startAllMicroservicesAsync();
  await app.listen(3001);
  console.log(`Application is running on: ${await app.getUrl()}`);
}
bootstrap();

This way you can have rest api with kafka/rabbit/grpc connected

like image 154
Adam Avatar answered Oct 25 '25 16:10

Adam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!