diff --git a/lib/connection.js b/lib/connection.js index 2e0caf5c59..eea265260d 100644 --- a/lib/connection.js +++ b/lib/connection.js @@ -106,6 +106,18 @@ Object.setPrototypeOf(Connection.prototype, EventEmitter.prototype); Object.defineProperty(Connection.prototype, 'readyState', { get: function() { + // If connection thinks it is connected, but we haven't received a heartbeat in 2 heartbeat intervals, + // that likely means the connection is stale (potentially due to frozen AWS Lambda container) + if ( + this._readyState === STATES.connected && + this._lastHeartbeatAt != null && + // LoadBalanced topology (behind haproxy, including Atlas serverless instances) don't use heartbeats, + // so we can't use this check in that case. + this.client?.topology?.s?.description?.type !== 'LoadBalanced' && + typeof this.client?.topology?.s?.description?.heartbeatFrequencyMS === 'number' && + Date.now() - this._lastHeartbeatAt >= this.client.topology.s.description.heartbeatFrequencyMS * 2) { + return STATES.disconnected; + } return this._readyState; }, set: function(val) { diff --git a/lib/drivers/node-mongodb-native/connection.js b/lib/drivers/node-mongodb-native/connection.js index 641703e4b1..a17fc64131 100644 --- a/lib/drivers/node-mongodb-native/connection.js +++ b/lib/drivers/node-mongodb-native/connection.js @@ -426,9 +426,6 @@ function _setClient(conn, client, options, dbName) { } conn.onOpen(); - if (client.topology?.s?.state === 'connected') { - conn._lastHeartbeatAt = Date.now(); - } for (const i in conn.collections) { if (utils.object.hasOwnProperty(conn.collections, i)) {