'Lambda function is not exiting but is logging the return

I have a Lambda function that I am trying to get to work fully. The code works in the sense it does exactly what I need it to however the issue comes in that the function either times out if running on Lambda or if running on serverless framework local invoke, it will just hang there not exiting.

I am looking for help in trying to get my function to exit and not time out/hang. I have included the full function - without helper functions. I can log out every step fine, the end results of DB and billing service are perfectly fine even on larger input data that is fetched from DB.

If I so a serverless invoke local command it will log out {success: true} like my function has at the end and then sit there for what seems like forever.

Code:

module.exports.billing = async (event, context, callback) => {
  context.callbackWaitsForEmptyEventLoop = false
  const { initClientDbConnection } = require('./db')

  // DB setup
  global.clientConnection = initClientDbConnection()
  const dbConnection = await global.clientConnection
  return { success: true }
}

Edit - I have removed a ton of code and added the below file. It hangs with just this little bit of code so I think that is the issue because if I comment out everything except the first line and the return line it exits fine. However, when I uncomment the two remaining lines it hangs.

db.js

const mongoose = require("mongoose");

// Configuration file
const DB_URL = process.env.MONGO_URI

const clientOption = {
  socketTimeoutMS: 30000,
  keepAlive: true,
  useNewUrlParser: true,
  autoIndex: false,
  useUnifiedTopology: true
}

const initClientDbConnection = () => {
  const db = mongoose.createConnection(DB_URL, clientOption)

  db.on("error", console.error.bind(console, "MongoDB Connection Error>> : "))
  db.once("open", function() {
    console.log("MongoDB Connection OK")
  })
  require("./billing")
  return db
};

module.exports = {
    initClientDbConnection
};


Solution 1:[1]

Ended up finding the solution, the issue was the DB connection was not closing which was not clearing the event loop which caused the function to not exit.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 joshk132