Search code examples
gomgo

MGO and long running Web Services - recovery


I've written a REST web service that uses mongo as the backend data store. I was wondering at this stage (before deployment), what the best practices were, considering a service that essentially runs forever(ish).

Currently, I'm following this type of pattern:

// database.go
...

type DataStore struct {
  mongoSession  *mgo.Session
}

...
func (d *DataStore) OpenSession () {
   ... // read setup from environment

   mongoSession, err = mgo.Dial(mongoURI)
   if err != nil {}
   ...
}

func (d *DataStore) CloseSession() {...}

func (d *DataStore) Find (...) (results...) {
    s := d.mongoSession.Copy()
    defer s.Close()

    // do stuff, return results
}

In main.go:

func main() {
    ds := NewDataStore()
    ds.OpenSession()
    defer ds.CloseSession()


    // Web Service Routes..
    ...
    ws.Handle("/find/{abc}", doFindFunc)
    ...
}

My question is - what's the recommended practice for recovery from session that has timed out, lost connection (the mongo service provider I'm using is remote, so I assume that this will happen), so on any particular web service call, the database session may no longer work? How do people handle these cases to detect that the session is no longer valid and a "fresh" one should be established?

Thanks!


Solution

  • what you may want is to do the session .Copy() for each incoming HTTP request (with deffered .Close()), copy again from the new session in your handlers if ever needed..

    connections and reconnections are managed by mgo, you can stop and restart MongoDB while making an HTTP request to your web service to see how its affected.

    if there's a db connection problem while handling an HTTP request, a db operation will eventually timeout (timeout can be configured by using DialWithTimeout instead of the regular Dial, so you can respond with a 5xx HTTP error code in such case.