2

I'm connecting a golang webservice to a MongoDB database. I'm a little confused about what's the best and safest way of creating and storing the database sessions. In other languages I am used to an approach where I can open and close a connection for every request like (pseudocode)

conn = db.newConnection()
query = conn.query({id: 'my-id'})
conn.close()

which would ensure that the connection is always closed properly and resources are freed. Whenever there is a connectivity hiccup it will be affected only temporarily. Performance hits are not to be expected as databases are heavily optimized for such behavior.

Now, the mgo docs on Dial()(which is used for establishing a connection) state:

This method is generally called just once for a given cluster. Further sessions to the same cluster are then established using the New or Copy methods on the obtained session. This will make them share the underlying cluster, and manage the pool of connections appropriately.

which led to me having a single package level connection that I create on package init and which is then shared by all instantiated clients:

var database *mgo.Database
// Setup runs all the needed steps to establish a database connection
func Setup() error {
    var sessionErr error
    mongoSession, sessionErr = mgo.Dial(os.Getenv("MONGO_HOST"))
    if sessionErr != nil {
        return sessionErr
    }
    database = mongoSession.DB(os.Getenv("DB_NAME"))
    return nil
}

This works kind of ok, yet I am running into issues where about once a month the connection to the database is lost and cannot be recovered during the lifetime of the process (making all requests return EOF and requiring someone to restart the process). I have never seen this happen using the connect-and-close-on-each-query approach I have described above.

I'm pretty sure I must be doing something wrong, but I feel I am doing what the docs tell me and all examples I can find on the web are one-off things that do not cover the case of a long-running application.

What is the recommended way of handling Mongo connections in a failure safe way inside long-running applications using mgo? Is there an established pattern of using Copy() or New() which are mentioned in the documentation? Will using them prevent permanently failed connections?

m90
  • 11,434
  • 13
  • 62
  • 112
  • Check at this stack as some of your issues are addressed here https://stackoverflow.com/questions/26574594/best-practice-to-maintain-a-mgo-session – reticentroot Jul 18 '17 at 16:56
  • @reticentroot cool thanks for digging that up, somehow wasn't able to find it. – m90 Jul 18 '17 at 17:15

0 Answers0