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:
- User send request with his tenant ID
- 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.
- 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 ?