DEV Community

Discussion on: A crash course on Serverless APIs with Express and MongoDB

Collapse
 
thinkdeepan profile image
Deepan Purushothaman

Thanks the info. I could able to get this working but I noticed that each call to the api is creating new connection to mongo and is not closed unless I explicitly close the mongoose connection at the end of each function call. Is this the correct approach to handle mongo connections in serverless?

Collapse
 
adnanrahic profile image
Adnan Rahić

It's not creating a new connection for every call. What's happening is that every time a lambda function is created the connection is pooled and kept alive for that instance. Every subsequent invocation that runs in that instance of the lambda function will re-use the already opened connection.

This is the preferred behavior of accessing databases with serverless functions. Cache the connection so it can be re-used as long as the function is alive. Once the function is destroyed, the connection will be closed.

Collapse
 
thinkdeepan profile image
Deepan Purushothaman

Thanks Adnan. I had my offline serverless started without "--skipCacheInvalidation" which was causing to create new connection for every call.. Add the --skipCacheInvalidation resolved the issue.

But with --skipCacheInvalidation every time I need to manually restart the offline app to load my changes which is difficult for the development.. the document says that nodemon should be combined with it but not sure how to do that.. Appreciate if you could share how that is setup for development debugging..