Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
in AWS by (19.1k points)

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




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 Answer

0 votes
by (44.4k points)

You have two options. Stop calling db.close() or move mongoose.connect code inside the function handler. You have a database, which is reused on multiple invocations, but you are closing the connection in the first invocation itself.

Related questions

Browse Categories