THPubs
August 22, 2017, 4:02am
1
In my lambda function, I tried to close the mongo connection as soon as I send a callback. But it has a problem.
When I send a request, the function performs its duties, send the callback and close the database connection.
When the second request is sent, the function times out.
When I remove the db.close()
things work perfectly.
I think lambda re-use the connection for all the functions because I open the connection in the top of the handler:
// Connect to database
mongoose.connect(process.env.DATABASE_URL);
const handleCreateUser = async (event, context, callback) => {
// eslint-disable-next-line no-param-reassign
context.callbackWaitsForEmptyEventLoop = false;
const data = JSON.parse(event.body);
const { user, userProfile } = data;
await createUser({ callback, user, userProfile });
};
Any idea what how to fix this? Do we really have to close the connection at this point?
1 Like
buggy
August 22, 2017, 4:54am
2
Code outside the handler is only executed when the Lambda is initialized during a cold start. When the Lambda runs a second time it’s trying to use a connection that’s been closed. Either move the mongoose.connect()
inside the handleCreateUser
or look at connection pooling.
1 Like
THPubs
August 22, 2017, 5:30am
3
Is there a way to close the connection just before the lambda function exit?
buggy
August 22, 2017, 11:28pm
4
Yes. Just close it at the bottom of the handler function but remember to move the open to the top of the handler function or it won’t run a second time
1 Like
rowanu
August 24, 2017, 9:25pm
5
Just to add to @buggy ’s answer, I attempted to visualise what he’s described in a blog post .
3 Likes
THPubs
August 26, 2017, 3:34am
6
Thanks @buggy I think that’s the best way to do it. Thank you @rowanu your article explained a lot more! Now things are getting more clear
kaiyes
November 16, 2017, 4:06am
7
offtopic. @THPubs nice to see you here too. Saw you in meteor forums !
THPubs
September 16, 2018, 6:24am
8
Guys… Almost an year have passed. In the present day, is there a better solution for the mongo database connection closing issue?