Keep on getting MongoNetworkError connection 6 to xx.x.xx.xx:xxxxx closed

256 Views Asked by At

I keep on getting the below error in an AWS Lambda with Node.js 16 + MongoDB v4, this usually happens for a lambda that has high traffic, other lambdas seem fine with the current setup.

MongoNetworkError: connection 6 to xx.x.xx.xx:xxxxx closed at Connection.onClose (/var/task/node_modules/mongodb/lib/cmap/connection.js:135:19)

MongoDB connection inside the lambda:

const MongoClient = require('mongodb').MongoClient;
const logger = require(''); const log = logger(__filename);

const getDbClient = async (uri) => {
  try {
    log.info('Connecting to Mongo client...');
    const dbClient = await MongoClient.connect(uri);
    log.info('Connected to Mongo client');
    return dbClient;
  }
  catch (err) {
    log.error('Error encountered connecting to database: ', err);
    throw err;
  }
};

module.exports = {
  getDbClient
};

The mongodb uri has an option of maxPoolSize=10 since I recently did an upgrade from MongoDB v3 to v4, and v4 has a maxPoolSize of 100 by default and v3 had it to 10. https://github.com/mongodb/node-mongodb-native/blob/HEAD/etc/notes/CHANGES_4.0.0.md#connection-pool-options

MongoDB hardware:

3 x M4.XLarge(4Core/16GB RAM)

This issue started happening after I upgraded MongoDB driver from v3 to v4 and stopped checking inside the lambda if there is an existing connection so I can use it because in v4 apparently this is done automatically.

I used to use: MongoClient.isConnected() from MongoDB v3.

Do you guys have any idea what could be the cause of this?

1

There are 1 best solutions below

9
Mink On

I don't have enough reputation to comment, so I'll just post an answer :D

I think your Lambda function is on extremely high traffic now, so it's even over the pool size of mongodb