PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, November 4, 2022

[FIXED] How to properly close the database connection in a lambda function?

 November 04, 2022     aws-lambda, lambda, serverless-framework     No comments   

Issue

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?


Solution

Either move the mongoose.connect code inside the handler, or stop calling db.close(). You currently have a single database connection being reused by multiple invocations of your Lambda function, but you are closing it after the first invocation completes.



Answered By - Mark B
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing