Search code examples
node.jsmongodbaws-lambdanestjsnestjs-mongoose

NestJs for lambda with mongodb creating too many connections


We are using nestjs for lambda which connects with mongodb for data. We are using nestjs mongoose module. However on deployment for each invocation a new set of connection are made and the previous ones are not released.

We are using forRootAsync

MongooseModule.forRootAsync({
      useClass: MongooseConfigService,
    })

service looks like this:

@Injectable({ scope: Scope.REQUEST })
export class MongooseConfigService implements MongooseOptionsFactory {
  constructor(@Inject(REQUEST) private readonly request: Request) {}

  async createMongooseOptions(): Promise<MongooseModuleOptions> {
    if (Buffer.isBuffer(this.request.body)) {
      this.request.body = JSON.parse(this.request.body.toString());
    }
    const { db } = this.request.body;
    console.log('connecting database', db);
    return {
      uri: process.env.MONGO_URL,
      dbName: db || '',
    };
  }
}

I understand we need to reuse the same connection. We have achieved it in nodejs by simply checking if the connection already exists and if it does not connect again. Not sure how to achieve the same in nest.js

tried changing the scope of service to Scope.DEFAULT but that didn't help.


Solution

  • We were able to resolve the issue by using a durable provider. NestJs documentation we created a strategy at the root that would use a parameter coming in each request. NestJs would than call the connection module only when a new connection was required.

    Note: When you use durable providers, Requests doesn't have all the parameters anymore and now only has the tenantId as per the example.