Skip to content

Commit d168bce

Browse files
committed
fix: avoid heartbeat check on LoadBalanced topologies, dont treat connection as heartbeat to avoid other cases where there is no heartbeat
1 parent 94f1bc8 commit d168bce

File tree

2 files changed

+12
-3
lines changed

2 files changed

+12
-3
lines changed

lib/connection.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,18 @@ Object.setPrototypeOf(Connection.prototype, EventEmitter.prototype);
106106

107107
Object.defineProperty(Connection.prototype, 'readyState', {
108108
get: function() {
109+
// If connection thinks it is connected, but we haven't received a heartbeat in 2 heartbeat intervals,
110+
// that likely means the connection is stale (potentially due to frozen AWS Lambda container)
111+
if (
112+
this._readyState === STATES.connected &&
113+
this._lastHeartbeatAt != null &&
114+
// LoadBalanced topology (behind haproxy, including Atlas serverless instances) don't use heartbeats,
115+
// so we can't use this check in that case.
116+
this.client?.topology?.s?.description?.type !== 'LoadBalanced' &&
117+
typeof this.client?.topology?.s?.description?.heartbeatFrequencyMS === 'number' &&
118+
Date.now() - this._lastHeartbeatAt >= this.client.topology.s.description.heartbeatFrequencyMS * 2) {
119+
return STATES.disconnected;
120+
}
109121
return this._readyState;
110122
},
111123
set: function(val) {

lib/drivers/node-mongodb-native/connection.js

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -426,9 +426,6 @@ function _setClient(conn, client, options, dbName) {
426426
}
427427

428428
conn.onOpen();
429-
if (client.topology?.s?.state === 'connected') {
430-
conn._lastHeartbeatAt = Date.now();
431-
}
432429

433430
for (const i in conn.collections) {
434431
if (utils.object.hasOwnProperty(conn.collections, i)) {

0 commit comments

Comments
 (0)