Best approach for deleting a cached connection

We are using several connection to mongoDB (Mainly Atlas, but sometimes self-hosted) due to our multi-tenant application (actually one per customer). The app runs through Golang official driver. For that, we cache each connection in a “map Like” (internal dev that take care of concurrency problem). We were wondering how can we delete a connection from this cache in case of connection problem for example if the server is down for some reason.

Currently the flow is as follow:

  1. User send request with his tenant ID
  2. We check if the connection is already cached. If yes, we return the connection, if no, we try to build the connection and cache it.
  3. We perform request with the returned connection or show appropiate error (connection fail, unknow tenant…).

I was thinking about using the PoolMonitor and/or ServerMonitor which looks promising for our use case. In case of a connection problem (ServerHeartbeatFailed seems to be the more appropriate), we delete the connection from the cache. The next time a user from this tenant will try to access his database, it will try to build the connection (not cached anymore) and fail if the server is still down or success if the server is up.

The idea behind it is to delete the invalid connection from our cache without the need to restart the app if one of our customer has problem with his connection.

Does the ServerHeartbeatFailed event is the more appropriate ?

@Sebastien_Tachier thanks for the question! A Client will manage its own pool of connections and create new connections when there is any issue connecting to the database, so if everything about the connection parameters are the same, there should be no need to drop and re-create a Client.

  1. Are you running into a condition where a Client becomes permanently “broken” after a database issue?
  2. When a customer’s database becomes unavailable and then recovers, does anything about the connection string change (e.g. hostname, username, password, etc)?
  3. What version of the Go Driver are you using?