skip to Main Content

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.

2

Answers


  1. Chosen as BEST ANSWER

    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.


  2. I would suggest that you make a connection proxy for MongoDB. Ever time a lambda gets invoked, it will open up a new connection to MongoDB. AWS generally provides a service that allows you to proxy requests through one connect, this is a common issue with RDS etc.

    This may help you though: https://www.mongodb.com/docs/atlas/manage-connections-aws-lambda/

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search