Add a function for determining if a connection object is still healthy
If an application needs to cache database connections to MongoDB. It would be helpful to have a function to call when retrieving a cached database connection. This function would ensure the connection is healthy before use. It could just return a boolean and allow the client application to handle a bad connection accordingly.
Using a disconnected event handler is not always reliable especially with FaaS serverless functions.
-
Kevin commented
Just an update that is quite relevant:
The mongoose library, which relies on the Node.js driver for MongoDB, has issued a healthcheck fix for version 8.7.x as described here in this pull request:
https://github.com/Automattic/mongoose/pull/14812
This will definitely help the stale connection issue above, but we will have to see if that resolves all of the issues experienced.
-
AdminAlex (Admin, MongoDB) commented
Thanks for the suggestion Kevin! Just for additional context, this type of connection health checking is typically done automatically by the MongoClient when a connection is checked out of the connection pool and used.
If the checked out connection cannot be used successfully (such as the underlying connection being closed), it will be discarded and a new connection created in it's place.
Connection health checking (such as using [Mongoose's `readyState`](https://mongoosejs.com/docs/api/connection.html#Connection.prototype.readyState) can potentially misreport health as a result of the underlying execution environment (ex: Lambda) freezing/thawing between invokations, resulting in possible internal state inconsistencies. I've filed [this ticket](https://github.com/Automattic/mongoose/issues/14727) for Mongoose specifically, but we will continue to look for ways to improve the developer experience of our drivers in these stateless environments as well.
Note that [Mongoose's Lambda docs](https://mongoosejs.com/docs/lambda.html) don't use `readyState` and also rely on the underlying driver's connection management mechanism.
(Edited by admin) -
Sam commented
This is a great idea, and would be incredibly valuable.