hoangvvo / nextjs-mongodb-app

A Next.js and MongoDB web application, designed with simplicity for learning and real-world applicability in mind.
https://nextjs-mongodb.now.sh/
MIT License
1.54k stars 289 forks source link

Database pooling in Serverless environment #59

Closed lishine closed 4 years ago

lishine commented 4 years ago

Question: Your API are deployed serverless, how then the connections get pooled, and the time it takes for db client to create the connection...

hoangvvo commented 4 years ago

Thanks @lishine. That is a good question. This is the best I can get.

https://github.com/hoangvvo/nextjs-mongodb-app/blob/master/middlewares/database.js#L3-L6

The way the client variable is defined make it like a "cached" variable because it is on the outside of the function database. Therefore, it is not recreated on every unless the function "go to sleep". We also first check if it is connected before trying to creating a new connection. Doing so give us some sort of "pooling".

Here is the similar setup by Vercel (Zeit) themself.

I will look into this to see how well the client or db can be reused and comment to this issue.

hoangvvo commented 4 years ago

But definitely, it is still pretty ... eh, not so good on serverless env anyway. Perhaps something like MongoDB Stitch would help.

hoangvvo commented 4 years ago

I will reopen this since it will be valuable to others.

hoangvvo commented 4 years ago

Closed in favor of #89