title: How to properly close the database connection in a lambda function?
body: <p>In my lambda function, I tried to close the mongo connection as soon as I send a callback. But it has a problem.</p>
  
  <ul>
  <li>When I send a request, the function performs its duties, send the callback and close the database connection.</li>
  <li>When the second request is sent, the function times out.</li>
  <li>When I remove the <code>db.close()</code> things work perfectly.</li>
  </ul>
  
  <p>I think lambda re-use the connection for all the functions because I open the connection in the top of the handler:</p>
  
  <pre><code>// Connect to database
  mongoose.connect(process.env.DATABASE_URL);
  
  
  const handleCreateUser = async (event, context, callback) =&gt; {
    // 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 });
  };
  </code></pre>
  
  <p>Any idea what how to fix this? Do we really have to close the connection at this point?</p>