Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in AWS by (19.1k points)

Env.:

  • AWS Lambda (Node.js, v. 8.10), waitForEmptyEventLoop === false
  • MongoDB (Atlas)
  • Mongoose

Problem: sometimes (randomly) I get the next error:

MongoNetworkError: connection 6 to db_host:27017 timed out

  File "/opt/nodejs/node_modules/mongodb-core/lib/connection/connection.js", line 259, col 7, in TLSSocket.<anonymous>

    new MongoNetworkError(f('connection %s to %s:%s timed out', self.id, self.host, self.port)),

  File "events.js", line 313, col 30, in Object.onceWrapper

  File "events.js", line 106, col 13, in emitNone

  File "events.js", line 208, col 7, in TLSSocket.emit

  File "net.js", line 420, col 8, in TLSSocket.Socket._onTimeout

  File "timers.js", line 482, col 11, in ontimeout

  File "timers.js", line 317, col 5, in tryOnTimeout

  File "timers.js", line 277, col 5, in Timer.listOnTimeout

Code of db connection:

const mongoose = require('mongoose');

const log = require('./log');

const options = {

  reconnectTries: 30,

  reconnectInterval: 500,

  poolSize: Number(process.env.DB_POOLSIZE) || 1,

  socketTimeoutMS: 30000,

  keepAlive: true,

  bufferCommands: false,

  bufferMaxEntries: 0,

};

let isConnected;

module.exports.connect = () => new Promise((resolve, reject) => {

  if (isConnected) {

    return resolve();

  }

  return mongoose.connect(process.env.DB_URI, options)

    .then((db) => {

      isConnected = db.connections[0].readyState;

      resolve();

    }).catch((error) => {

      log.error('DB:', error);

      reject(error);

    });

});

I've checked - isConnected cached successfully, MongoDB connection cached in mongoose. All must be okay, but sometimes I get this error.

Anybody have any ideas how can I solve this issue?

1 Answer

0 votes
by (44.4k points)
edited by

Just increase socketTimeoutMS to 2000000, this is enough to keep the connection between lambdas invocation of "warm" container. Use the next config (mongoose):

{ reconnectTries: 30, reconnectInterval: 500, poolSize: 1, socketTimeoutMS: 2000000, keepAlive: true, }

Need help mastering AWS Lambda and other AWS skills? Go through AWS Training Page and become an AWS expert! 

Related questions

0 votes
1 answer

Want to get 50% Hike on your Salary?

Learn how we helped 50,000+ professionals like you !

0 votes
1 answer
0 votes
2 answers
asked Oct 16, 2019 in Web Technology by Sammy (47.6k points)
0 votes
2 answers
0 votes
2 answers

Browse Categories

...