Connect timeout and execution timeout in nodejs driver

Hi @Vlad_Kote, welcome to the community forums! I’ll try to answer your questions in two sections below:

connectTimeoutMS

The connectTimeoutMS option is used by the driver to determine when to timeout an attempt to connect an individual connection to a server (one of many in your connection pool). It does not have a direct relation to MongoClient#connect. When you attempt to connect a MongoClient it attempts server selection, which means that it will attempt for up to serverSelectionTimeoutMS to connect to the cluster before reporting that it was unable to find a suitable server.

If you want to get “fast fail” behavior on your connect, you can pass serverSelectionTimeoutMS to your MongoClient:

const client = new MongoClient(..., { serverSelectionTimeoutMS: 5000 });
await client.connect();

socketTimeoutMS

The socketTimeoutMS option corresponds to Node’s Socket#setTimeout method, and guides the behavior around socket inactivity. In your case it seems like you want to guarantee that an operation succeeds or fails in a given time range. Your best bet for this today is to use a combination of socketTimeoutMS (in case the socket is indeed inactive, due to network issues) and maxTimeMS which will cause the operation to fail after the specified time on the server side:

try {
  const collection = client.db().collection('test_collection');

  console.time('find');
  await collection.find({ $where: 'sleep(1000)' }).limit(10).maxTimeMS(10).toArray();
  console.timeEnd('find');
} catch (err) {
  console.timeEnd('find');
  console.dir({ err });
}

in this case will result in:

find: 44.282ms
{
  err: MongoError: operation exceeded time limit
      at MessageStream.messageHandler (/home/mbroadst/Development/mongo/node-mongodb-native/lib/cmap/connection.js:261:20)
      at MessageStream.emit (events.js:209:13)
      at processIncomingData (/home/mbroadst/Development/mongo/node-mongodb-native/lib/cmap/message_stream.js:144:12)
      at MessageStream._write (/home/mbroadst/Development/mongo/node-mongodb-native/lib/cmap/message_stream.js:42:5)
      at doWrite (_stream_writable.js:428:12)
      at writeOrBuffer (_stream_writable.js:412:5)
      at MessageStream.Writable.write (_stream_writable.js:302:11)
      at Socket.ondata (_stream_readable.js:722:22)
      at Socket.emit (events.js:209:13)
      at addChunk (_stream_readable.js:305:12) {
    ok: 0,
    errmsg: 'operation exceeded time limit',
    code: 50,
    codeName: 'ExceededTimeLimit',
    operationTime: Timestamp { _bsontype: 'Timestamp', low_: 1, high_: 1585574598 },
    '$clusterTime': { clusterTime: [Timestamp], signature: [Object] },
    name: 'MongoError',
    [Symbol(mongoErrorContextSymbol)]: {}
  }
}

Hope that helps!

2 Likes