title: Sharing DB Connection across AWS Lambda function calls
body: <p>So I'm following the example here <a href="https://www.mongodb.com/blog/post/optimizing-aws-lambda-performance-with-mongodb-atlas-and-nodejs" rel="nofollow noreferrer">https://www.mongodb.com/blog/post/optimizing-aws-lambda-performance-with-mongodb-atlas-and-nodejs</a>, to optimize my lambda functions.</p>
  
  <p>I've tried two approaches and tested them locally using <code>serverless-offline</code> and both don't seem to work.</p>
  
  <h2>First Approach</h2>
  
  <pre><code>// endpoint file
  
  import {connectToDatabase} from "lib/dbUtils.js";
  
  let cachedDb = null;
  
  export function post(event, context, callback) {
    let response;
    context.callbackWaitsForEmptyEventLoop = false;
    connectToDatabase()
      .then(//do other stuff
  
  // lib/dbUtils.js
  
  export async function connectToDatabase() {
    if (cachedDb &amp;&amp; cachedDb.serverConfig.isConnected()) {
      console.log(" using cached db instance");
      return cachedDb;
    }
    cachedDb = await mongoose.createConnection(
      process.env.DB_URL,
      async err =&gt; {
        if (err) {
          throw err;
        }
      }
    );
    return cachedDb;
  }
  </code></pre>
  
  <h2>Second Approach</h2>
  
  <pre><code>global.cachedDb = null;
  
  export function post(event, context, callback) {
    let response;
    context.callbackWaitsForEmptyEventLoop = false;
    connectToDatabase()
      .then(connection =&gt; createUser(event.body, connection))
  
  
  // lib/dbUtils.js
  
  export async function connectToDatabase() {
    // eslint-disable-next-line
    if (global.cachedDb &amp;&amp; global.cachedDb.serverConfig.isConnected()) {
      // eslint-disable-next-line
      console.log(" using cached db instance");
      // eslint-disable-next-line
      return global.cachedDb;
    }
    // eslint-disable-next-line
    global.cachedDb = await mongoose.createConnection(
      process.env.DB_URL,
      async err =&gt; {
        if (err) {
          throw err;
        }
      }
    );
    // eslint-disable-next-line
    return global.cachedDb;
  }
  </code></pre>
  
  <p>In both cases the <code>using cached db instance</code> console log does not run. </p>
  
  <p>Why does this not work? Is this because of serverless-offline?</p>