Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kill nestjs - node.js process while lost redis connection (microservice)

app.connectMicroservice({
  transport: Transport.REDIS,
  options: {
    url: redis://ip:6379,
    retryAttempts: 5,
    retryDelay: 5000,
  }
});

This is how I connect to microservice in nestjs, simple and basic in Windows.

During the process the connection to redis could be gone but I can't catch it.

It means that the app will be still alive and nothing happen if the redis connection will be restored, I won't be able to subscribe new events.

How can I handle it or add a timeout or catch issue like that. The fix for now is only restart the service manually. I want to kill the process with exit(1) in that case

like image 656
Tuz Avatar asked Mar 19 '26 08:03

Tuz


1 Answers

You could emit health check messages periodically and then start your recovery process when the connection is closed:

Register your redis client in your module's imports:

imports: [ClientsModule.register([
  { name: 'REDIS_CLIENT', transport: Transport.REDIS },
])],

Then, in your onModuleInit, connect your client and start the health check periodically:

constructor(@Inject('REDIS_CLIENT') private readonly client: ClientProxy) {
}

async onModuleInit() {
  await this.client.connect();
  setInterval(async () => {
    try {
      await this.client.emit('healthcheck', 'healthcheck').toPromise();
    } catch (e) {
      // Sending the message has failed, start recovery
      console.error(e);
      process.exit(1);
    }
  }, 1000);
}
like image 56
Kim Kern Avatar answered Mar 21 '26 22:03

Kim Kern